<?php

namespace App\Controllers;

use App\Models\ClientModel;
use CodeIgniter\Controller;

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

    public function index()
    {
        $companyId = session()->get('company_id') ?? 1;
        $clientModel = new ClientModel();

        $search = $this->request->getGet('search');
        $builder = $clientModel->where('company_id', $companyId);

        if ($search) {
            $builder->groupStart()
                ->like('company_name', $search)
                ->orLike('code', $search)
                ->orLike('email', $search)
                ->groupEnd();
        }

        $clients = $builder->orderBy('company_name', 'ASC')->paginate(20);

        return view('clients/index', [
            'clients' => $clients,
            'pager' => $clientModel->pager,
            'search' => $search,
        ]);
    }

    public function create()
    {
        $companyId = session()->get('company_id') ?? 1;

        if ($this->request->getMethod() === 'post') {
            $clientModel = new ClientModel();
            $data = $this->request->getPost();
            $data['company_id'] = $companyId;
            $data['code'] = $clientModel->generateCode();

            if ($clientModel->insert($data)) {
                session()->setFlashdata('success', 'Client cree avec succes');
                return redirect()->to('/clients');
            }

            session()->setFlashdata('error', 'Erreur lors de la creation');
        }

        return view('clients/form', ['client' => null, 'mode' => 'create']);
    }

    public function edit(int $id)
    {
        $clientModel = new ClientModel();
        $client = $clientModel->find($id);

        if (!$client) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Client non trouve');
        }

        if ($this->request->getMethod() === 'post') {
            $data = $this->request->getPost();
            if ($clientModel->update($id, $data)) {
                session()->setFlashdata('success', 'Client mis a jour');
                return redirect()->to('/clients');
            }
        }

        return view('clients/form', ['client' => $client, 'mode' => 'edit']);
    }

    public function delete(int $id)
    {
        $clientModel = new ClientModel();
        $client = $clientModel->find($id);

        if (!$client) {
            return $this->response->setJSON(['success' => false]);
        }

        $clientModel->delete($id);
        return $this->response->setJSON(['success' => true]);
    }

    public function view(int $id)
    {
        $clientModel = new ClientModel();
        $client = $clientModel->getWithStats($id);

        if (!$client) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Client non trouve');
        }

        return view('clients/view', ['client' => $client]);
    }
}
