<?php

namespace App\Controllers\Crm;

use App\Controllers\BaseController;
use App\Models\Quotes\QuotesModel;
use App\Models\Quotes\QuoteServicesModel;

class EditQuotesController extends BaseController
{
    protected QuotesModel $quoteModel;
    protected QuoteServicesModel $quoteServiceModel;

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

    public function edit($id)
    {
        $quote = $this->quoteModel->find($id);

        if (!$quote || $quote['Status'] !== 'Cotizacion') {
            return redirect()->to('crm/quotes')
                ->with('error', 'No se puede editar esta cotización');
        }

        $services = $this->quoteServiceModel
            ->where('FK_Quote', $id)
            ->findAll();

        return view('crm/quotes/edit', [
            'quote'    => $quote,
            'services' => $services
        ]);
    }

    public function update($id)
    {
        $quote = $this->quoteModel->find($id);

        if (!$quote || $quote['Status'] !== 'Cotizacion') {
            return redirect()->to('crm/quotes')
                ->with('error', 'No se puede actualizar esta cotización');
        }

        $db = \Config\Database::connect();
        $db->transBegin();

        try {
            $op_cost    = (float) $this->request->getPost('Operation_cost');
            $admin_cost = (float) $this->request->getPost('Administrative_cost');
            $pack_cost  = (float) $this->request->getPost('Packaging_cost');
            /* ================== ACTUALIZAR COTIZACIÓN ================== */
            $quoteData = [
                'Origin_name'          => $this->request->getPost('Origin_name'),
                'Origin_address'       => $this->request->getPost('Origin_address'),
                'Origin_city'          => $this->request->getPost('Origin_city'),
                'Origin_state'         => $this->request->getPost('Origin_state'),
                'Origin_country'       => $this->request->getPost('Origin_country'),
                'Origin_zip'           => $this->request->getPost('Origin_zip'),

                'Destination_name'     => $this->request->getPost('Destination_name'),
                'Destination_address'  => $this->request->getPost('Destination_address'),
                'Destination_city'     => $this->request->getPost('Destination_city'),
                'Destination_state'    => $this->request->getPost('Destination_state'),
                'Destination_country'  => $this->request->getPost('Destination_country'),
                'Destination_zip'      => $this->request->getPost('Destination_zip'),
                'Destination_phone'    => $this->request->getPost('Destination_phone'),

                'Length_cm'            => $this->request->getPost('Length_cm'),
                'Width_cm'             => $this->request->getPost('Width_cm'),
                'Height_cm'            => $this->request->getPost('Height_cm'),
                'Weight_kg'            => $this->request->getPost('Weight_kg'),
                'Declared_value'       => $this->request->getPost('Declared_value'),

                'Operation_cost'       => $op_cost,
                'Administrative_cost'  => $admin_cost,
                'Packaging_cost'       => $pack_cost,
                'Margin_amount'        => $this->request->getPost('Margin_amount'),
                'Taxes'                => $this->request->getPost('Taxes'),
                'Subtotal'             => $this->request->getPost('Subtotal'),
                'Total_amount'         => $this->request->getPost('Total_amount'),
                'Base_cost'            => ($op_cost + $admin_cost + $pack_cost),
                'Comments'             => $this->request->getPost('Comments'),
            ];
            if (!$this->quoteModel->update($id, $quoteData)) {
                throw new \Exception('No se pudo actualizar la cotización');
            }
             //dd($this->request->getPost());

            $this->quoteModel->update($id, $quoteData);

            /* ================== ACTUALIZAR SERVICIOS ================== */
            $services = $this->request->getPost('services');

            if ($services) {
                foreach ($services as $service) {
                    if (empty($service['PK_Quote_Service'])) {
                        throw new \Exception('Servicio inválido detectado');
                    }
                    $this->quoteServiceModel->update(
                        $service['PK_Quote_Service'],
                        [
                            'Service_name' => $service['Service_name'],
                            'Quantity'     => $service['Quantity'],
                            'Unit_price'   => $service['Unit_price'],
                            'Total'        => $service['Total']
                        ]
                    );
                }
            }

            /* ================== COMMIT ================== */
            if ($db->transStatus() === false) {
                throw new \Exception('Error al guardar la cotización');
            }

            $db->transCommit();

            return redirect()->to('crm/quotes/view/'.$id)
                ->with('success', 'Cotización actualizada correctamente');

        } catch (\Throwable $e) {

            $db->transRollback();

            return redirect()->back()
                ->withInput()
                ->with('error', $e->getMessage());
        }
    }

}
