<?php

namespace App\Controllers;

use App\Models\Company;

class CompanyController extends AdminController
{
    public function __construct()
    {
        parent::__construct();
    }

    private $pageTitle = 'Company';

    public function index()
    {
        $this->verifyRole('updateCompany');

        // Validation rules
        $validation = \Config\Services::validation();
        $validation->setRules([
            'company_name' => 'trim|required',
            'service_charge_value' => 'trim|integer',
            'vat_charge_value' => 'trim|integer',
            'address' => 'trim|required',
            'message' => 'trim|required',
        ]);

        $Company = new Company();
        // die(var_dump($validation->getErrors()));
        if ($this->request->getMethod() == 'post' && $validation->withRequest($this->request)->run()) {
            // If the form is valid
            $data = [
                'company_name' => $this->request->getPost('company_name'),
                'service_charge_value' => $this->request->getPost('service_charge_value'),
                'vat_charge_value' => $this->request->getPost('vat_charge_value'),
                'address' => $this->request->getPost('address'),
                'phone' => $this->request->getPost('phone'),
                'phone2' => $this->request->getPost('phone2'),
                'NIF' => $this->request->getPost('nif'),
                'STAT' => $this->request->getPost('stat'),
                'country' => $this->request->getPost('country'),
                'message' => $this->request->getPost('message'),
                'currency' => $this->request->getPost('currency'),
            ];
        
            if ($Company->updateCompany($data, 1)) {
                session()->setFlashdata('success', 'Successfully updated');
                return redirect()->to('/company');
            } else {
                session()->setFlashdata('errors', 'Error occurred!');
                return redirect()->to('/company/index');
            }
        } else {
            // If the form is invalid
            $data = [
                'currency_symbols' => $this->currency(),
                'company_data' => $Company->getCompanyData(1),
                'page_title' => $this->pageTitle,
                'validation_errors' => $validation->getErrors() // Pass the Validation object
            ];
        
            return $this->render_template('company/index', $data);
        }
        
    }
}