<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Permission;
use App\Models\Billing;
use App\Services\InvoicePdfService;

final class FamilyBillingPortalController extends Controller
{
    private function familyInvoice(): array
    {
        $clientId=Permission::familyPortalClientId();
        if (!Permission::isFamilyPortalIdentity() || !$clientId) {
            http_response_code(403);
            exit('Aucun dossier de facturation n’est rattaché à ce portail.');
        }
        $token=strtolower(trim((string)($_GET['facture']??'')));
        if (!preg_match('/^[a-f0-9]{64}$/',$token)) {
            http_response_code(404);
            exit('Facture introuvable dans ce dossier familial.');
        }
        $stmt=Database::connection()->prepare(
            "SELECT id
             FROM cda_invoices
             WHERE public_token=?
               AND organisation_id=?
               AND client_id=?
               AND deleted_at IS NULL
               AND status IN ('issued','part_paid','paid')
             LIMIT 1"
        );
        $stmt->execute([
            $token,
            (int)(Auth::user()['organisation_id']??1),
            (int)$clientId,
        ]);
        $invoice=Billing::find((int)$stmt->fetchColumn(),(int)(Auth::user()['organisation_id']??1));
        if (!$invoice
            || (int)$invoice['client_id'] !== (int)$clientId
            || !empty($invoice['deleted_at'])
            || !in_array((string)$invoice['status'],['issued','part_paid','paid'],true)) {
            http_response_code(404);
            exit('Facture introuvable dans ce dossier familial.');
        }
        return $invoice;
    }

    public function index(): void
    {
        Auth::requireLogin();
        $clientId=Permission::familyPortalClientId();
        if (!Permission::isFamilyPortalIdentity() || !$clientId) {
            http_response_code(403);
            exit('Aucun dossier de facturation n’est rattaché à ce portail.');
        }
        $stmt=Database::connection()->prepare(
            "SELECT i.*,
                    COALESCE((SELECT SUM(p.amount) FROM cda_payments p WHERE p.invoice_id=i.id),0) AS paid_amount
             FROM cda_invoices i
             WHERE i.client_id=:client_id
               AND i.organisation_id=:organisation_id
               AND i.deleted_at IS NULL
               AND i.status IN ('issued','part_paid','paid')
             ORDER BY i.created_at DESC,i.id DESC"
        );
        $stmt->execute(['client_id'=>$clientId,'organisation_id'=>(int)(Auth::user()['organisation_id']??1)]);
        $this->view('family_billing/index',[
            'pageTitle'=>'Ma facturation','invoices'=>$stmt->fetchAll()?:[],
        ]);
    }

    public function print(): void
    {
        Auth::requireLogin();
        $invoice=$this->familyInvoice();
        $settings=Billing::settings((int)(Auth::user()['organisation_id']??1));
        $pdf=(new InvoicePdfService())->render($invoice,$settings);
        $safe=preg_replace('/[^A-Za-z0-9._-]+/','-',(string)($invoice['document_number']?:'facture'));
        Database::connection()->prepare(
            "INSERT INTO audit_logs(
                organisation_id,utilisateur_id,action,module,entite_type,entite_id,description
             ) VALUES(?,?,'download','family_billing','cda_invoice',?,'Téléchargement du PDF depuis le portail Famille')"
        )->execute([
            (int)(Auth::user()['organisation_id']??1),
            (int)(Auth::user()['id']??0)?:null,
            (int)$invoice['id'],
        ]);
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="'.$safe.'.pdf"');
        header('Content-Length: '.strlen($pdf));
        header('Cache-Control: private, no-store, max-age=0');
        header('Pragma: no-cache');
        header('X-Content-Type-Options: nosniff');
        echo $pdf;
        exit;
    }
}
