<?php

namespace App\Controllers;

use App\Models\ProductModel;
use CodeIgniter\Controller;

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

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

        $products = $productModel->where('company_id', $companyId)
            ->orderBy('designation', 'ASC')
            ->paginate(20);

        return view('products/index', ['products' => $products, 'pager' => $productModel->pager]);
    }

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

        if ($this->request->getMethod() === 'post') {
            $productModel = new ProductModel();
            $data = $this->request->getPost();
            $data['company_id'] = $companyId;

            if ($productModel->insert($data)) {
                session()->setFlashdata('success', 'Produit cree');
                return redirect()->to('/products');
            }
        }

        return view('products/form', ['product' => null]);
    }

    public function edit(int $id)
    {
        $productModel = new ProductModel();
        $product = $productModel->find($id);

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

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

        return view('products/form', ['product' => $product]);
    }

    public function delete(int $id)
    {
        $productModel = new ProductModel();
        $productModel->delete($id);
        return $this->response->setJSON(['success' => true]);
    }

    public function ajaxList()
    {
        $companyId = session()->get('company_id') ?? 1;
        $productModel = new ProductModel();
        $term = $this->request->getGet('q');

        $builder = $productModel->where('company_id', $companyId)->where('is_active', 1);
        if ($term) {
            $builder->groupStart()
                ->like('designation', $term)
                ->orLike('reference', $term)
                ->groupEnd();
        }

        $products = $builder->limit(20)->findAll();
        return $this->response->setJSON($products);
    }
}
