<?php

namespace App\Controllers\Crm;

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

class ContactsController extends BaseController
{
    protected ContactsModel $contactModel;
    protected QuotesModel $quoteModel;

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

    /**
     * Lista de contactos
     * GET /crm/contacts
     */
    public function index()
    {
        $search = $this->request->getGet('search');
        $status = $this->request->getGet('status');

        $builder = $this->contactModel;

        if ($search) {
            $builder = $builder->groupStart()
                ->like('First_name', $search)
                ->orLike('Last_name', $search)
                ->orLike('Email', $search)
                ->groupEnd();
        }

        if ($status) {
            $builder = $builder->where('Lifecycle_stage', $status);
        }

        $contacts = $builder
            ->orderBy('Created_at', 'DESC')
            ->findAll();

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

    /**
     * Mostrar formulario crear contacto
     * GET /crm/contacts/create
     */
    public function create()
    {
        return view('crm/contacts/create');
    }

    /**
     * Guardar contacto
     * POST /crm/contacts/store
     */
    public function store()
    {
        $contactsModel  = new ContactsModel();
        $companiesModel = new CompaniesModel();

        $data = $this->request->getPost();

        $userId = 999; // luego lo sacas de sesión

        // ================== EMPRESA ==================
        $companyId = null;

        if (!empty($data['Company_name'])) {

            $company = $companiesModel
                ->where('Company_name', trim($data['Company_name']))
                ->where('PK_User', $userId)
                ->first();

            if ($company) {
                // Empresa existente
                $companyId = $company['PK_Company'];
            } else {
                // Crear empresa automáticamente
                $companyId = $companiesModel->insert([
                    'PK_User'        => $userId,
                    'Company_name'   => trim($data['Company_name']),
                    'Phone'          => $data['Phone'] ?? null,
                    'Address'        => $data['Address'] ?? null,
                    'City'           => $data['City'] ?? null,
                    'State'          => $data['State'] ?? null,
                    'Country'        => $data['Country'] ?? null,
                    'Postal_code'    => $data['Postal_code'] ?? null,
                    'Lifecycle_stage'=> 'Lead',
                    'Created_at'     => date('Y-m-d H:i:s'),
                ]);
            }
        }

        // ================== CONTACTO ==================
        $contactData = [
            'PK_User'         => $userId,
            'First_name'      => $data['First_name'],
            'Last_name'       => $data['Last_name'] ?? null,
            'Email'           => $data['Email'] ?? null,
            'Work_email'      => $data['Work_email'] ?? null,
            'Phone'           => $data['Phone'] ?? null,
            'Mobile'          => $data['Mobile'] ?? null,
            'Whatsapp'        => $data['Whatsapp'] ?? null,
            'Company_name'    => $data['Company_name'] ?? null,
            'PK_Company'      => $companyId,
            'Job_title'       => $data['Job_title'] ?? null,
            'Sector'          => $data['Sector'] ?? null,
            'Address'         => $data['Address'] ?? null,
            'City'            => $data['City'] ?? null,
            'State'           => $data['State'] ?? null,
            'Country'         => $data['Country'] ?? null,
            'Postal_code'     => $data['Postal_code'] ?? null,
            'Lead_status'     => 'Nuevo',
            'Lifecycle_stage' => 'Lead',
            'Created_at'      => date('Y-m-d H:i:s'),
            'Updated_at'      => date('Y-m-d H:i:s'),
        ];

        $contactId = $contactsModel->insert($contactData);

        return redirect()->to('crm/contacts/view/' . $contactId)
            ->with('success', 'Contacto creado correctamente');
    }

    /**
     * Ver contacto (vista clave del flujo)
     * GET /crm/contacts/view/{id}
     */
    public function view($id)
    {
        
        $contact = $this->contactModel->find($id);

        if (!$contact) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Contacto no encontrado');
        }

        // Más adelante aquí cargaremos:
        // - cotizaciones
        // - pedidos
        // - stepper
        $quote = $this->quoteModel
        ->where('FK_Contact', $id)
        ->orderBy('Created_at', 'DESC')
        ->first();


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

    /**
     * Editar contacto
     * GET /crm/contacts/edit/{id}
     */
    public function edit($id)
    {
        $contact = $this->contactModel->find($id);

        if (!$contact) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Contacto no encontrado');
        }

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

    /**
     * Actualizar contacto
     * POST /crm/contacts/update/{id}
     */
    public function update($id)
    {
        $contact = $this->contactModel->find($id);

        if (!$contact) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Contacto no encontrado');
        }

        $data = [
            'Email'      => $this->request->getPost('Email'),
            'First_Name' => $this->request->getPost('First_Name'),
            'Last_Name'  => $this->request->getPost('Last_Name'),
            'Phone'      => $this->request->getPost('Phone'),
            'Updated_at' => date('Y-m-d H:i:s'),
        ];

        $this->contactModel->update($id, $data);

        return redirect()->to('crm/contacts/view/' . $id)
            ->with('success', 'Contacto actualizado');
    }
}
