<?php

namespace App\Controllers\Crm;

use App\Controllers\BaseController;
use App\Models\Companies\CompaniesModel;
use App\Models\Contacts\ContactsModel;

class CompaniesController extends BaseController
{
    protected CompaniesModel $companyModel;
    protected ContactsModel $contactModel;

    public function __construct()
    {
        $this->companyModel = new CompaniesModel();
        $this->contactModel = new ContactsModel();
    }

    /**
     * GET /crm/companies
     */
    public function index()
    {
        $companies = $this->companyModel
            ->orderBy('Company_name', 'ASC')
            ->findAll();

        return view('crm/companies/index', [
            'companies' => $companies
        ]);
    }

    /**
     * GET /crm/companies/view/{id}
     */
    public function view($id)
    {
        $company = $this->companyModel->find($id);

        if (!$company) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Empresa no encontrada');
        }

        $contacts = $this->contactModel
            ->where('PK_Company', $id)
            ->orderBy('First_name', 'ASC')
            ->findAll();

        return view('crm/companies/view', [
            'company'  => $company,
            'contacts' => $contacts
        ]);
    }
}
