<?php

namespace App\Controllers\Crm;

use App\Controllers\BaseController;
use App\Models\Quotes\ApartadoModel;
use App\Models\Quotes\QuoteServicesModel;
use App\Models\Payments\QuotePaymentModel;
use App\Models\Payments\QuoteBalanceModel;

class ApartadosController extends BaseController
{
    public function view($id)
    {
        $apartadoModel = new ApartadoModel();
        $apartado = $apartadoModel->find($id);

        if (!$apartado) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        // =========================
        // SERVICIOS
        // =========================
        $servicesModel = new QuoteServicesModel();

        $services = $servicesModel
            ->where('FK_Quote', $apartado['FK_Quote'])
            ->orderBy('Sort_order')
            ->findAll();

        // =========================
        // PAGOS — HISTORIAL
        // =========================
        $paymentModel = new QuotePaymentModel();

        $payments = $paymentModel
            ->where('FK_Quote', $apartado['FK_Quote'])
            ->orderBy('Paid_at', 'DESC')
            ->findAll();

        // =========================
        // BALANCE
        // =========================
        $balanceModel = new QuoteBalanceModel();

        $balanceRow = $balanceModel
            ->where('FK_Quote', $apartado['FK_Quote'])
            ->first();

        // fallback si no existe balance guardado
        if (!$balanceRow) {

            $paidSum = (float) $paymentModel
                ->selectSum('Amount')
                ->where('FK_Quote', $apartado['FK_Quote'])
                ->get()
                ->getRow()
                ->Amount ?? 0;

            $total = (float) ($apartado['Total_amount'] ?? 0);

            $balanceRow = [
                'Total_amount' => $total,
                'Paid_amount'  => $paidSum,
                'Balance'      => $total - $paidSum,
                'Payment_status' => ($paidSum >= $total) ? 'Pagado' : 'Pendiente'
            ];
        }

        // =========================
        // INYECTAR EN ORDER PARA LA VISTA
        // =========================
        $apartado['Paid_amount']    = $balanceRow['Paid_amount'];
        $apartado['Pending_amount'] = $balanceRow['Balance'];
        $apartado['Payment_status'] = $balanceRow['Payment_status'];

        // =========================
        // RETURN VIEW
        // =========================
        return view('crm/apartados/view', [
            'order'      => $apartado,   // reutilizas la vista
            'services'   => $services,
            'payments'   => $payments,   // 👈 historial completo
            'balance'    => $balanceRow, // 👈 resumen
            'isApartado' => true
        ]);
    }
}
