<?php

namespace App\Controllers;

use App\Models\CompanyModel;
use CodeIgniter\Controller;

class SettingsController extends Controller
{
    protected $helpers = ['url', 'form'];

    public function index()
    {
        $companyId = session()->get('company_id') ?? 1;
        $companyModel = new CompanyModel();
        $company = $companyModel->find($companyId);

        if ($this->request->getMethod() === 'post') {
            $data = $this->request->getPost();

            $logo = $this->request->getFile('logo');
            if ($logo && $logo->isValid() && !$logo->hasMoved()) {
                $newName = 'logo_' . time() . '.' . $logo->getExtension();
                $logo->move(FCPATH . 'uploads/logos/', $newName);
                $data['logo'] = $newName;
            }

            if ($companyModel->update($companyId, $data)) {
                session()->setFlashdata('success', 'Parametres mis a jour');
            }

            return redirect()->to('/settings');
        }

        return view('settings/index', ['company' => $company]);
    }
}
