<?php

namespace App\Controllers;

use App\Models\PaymentModel;
use App\Models\InvoiceModel;
use CodeIgniter\Controller;

class PaymentController extends Controller
{
    protected $helpers = ['url', 'form'];

    public function index()
    {
        $paymentModel = new PaymentModel();
        $payments = $paymentModel->select('payments.*, invoices.invoice_number, clients.company_name')
            ->join('invoices', 'invoices.id = payments.invoice_id')
            ->join('clients', 'clients.id = invoices.client_id')
            ->orderBy('payments.payment_date', 'DESC')
            ->paginate(20);

        return view('payments/index', ['payments' => $payments, 'pager' => $paymentModel->pager]);
    }

    public function create(int $invoiceId)
    {
        $invoiceModel = new InvoiceModel();
        $invoice = $invoiceModel->find($invoiceId);

        if (!$invoice) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Facture non trouvee');
        }

        if ($this->request->getMethod() === 'post') {
            $paymentModel = new PaymentModel();
            $data = [
                'invoice_id' => $invoiceId,
                'amount' => $this->request->getPost('amount'),
                'payment_date' => $this->request->getPost('payment_date'),
                'payment_method' => $this->request->getPost('payment_method'),
                'reference' => $this->request->getPost('reference'),
                'notes' => $this->request->getPost('notes'),
                'created_by' => session()->get('user_id'),
            ];

            $paymentModel->insert($data);

            $totalPaid = $paymentModel->getTotalPaid($invoiceId);
            $newStatus = ($totalPaid >= $invoice['net_payable']) ? 'payee' : 'partielle';
            $invoiceModel->update($invoiceId, [
                'status' => $newStatus,
                'paid_at' => ($newStatus === 'payee') ? date('Y-m-d H:i:s') : null,
            ]);

            session()->setFlashdata('success', 'Paiement enregistre');
            return redirect()->to('/invoices/view/' . $invoiceId);
        }

        $remaining = $invoice['net_payable'] - (new PaymentModel())->getTotalPaid($invoiceId);

        return view('payments/form', [
            'invoice' => $invoice,
            'remaining' => $remaining,
        ]);
    }
}
