<?php

namespace App\Controllers\Crm;

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

class OrdersController extends BaseController
{
    protected $orderModel;

    public function __construct()
    {
        $this->orderModel = new OrderModel();
        $this->apartadoModel = new ApartadoModel();
    }

    /**
     * Listado de todas las órdenes
     */
    public function index()
    {
        // Traemos todas las órdenes (puedes agregar paginación luego)
        $orders = $this->orderModel
            ->orderBy('Created_at', 'DESC')
            ->findAll();
        $apartados = $this->apartadoModel
            ->orderBy('Created_at', 'DESC')
            ->findAll();

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

    public function view($id)
    {
        $order = $this->orderModel->find($id);

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

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

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

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

        $balance = $balanceModel
            ->where('FK_Quote', $order['FK_Quote'])
            ->first();

        // fallback por si no existe
        if (!$balance) {
            $balance = [
                'Total_amount'   => $order['Total_amount'] ?? 0,
                'Paid_amount'    => 0,
                'Balance'        => $order['Total_amount'] ?? 0,
                'Payment_status' => 'Pendiente'
            ];
        }

        // =========================
        // Historial de pagos
        // =========================
        $paymentModel = new QuotePaymentModel();

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

        // =========================
        // Vista
        // =========================
        return view('crm/orders/view', [
            'order'    => $order,
            'services' => $services,
            'balance'  => $balance,
            'payments' => $payments
        ]);
    }

}
