<?php
namespace App\Controllers;
use App\Core\Auth;use App\Core\Controller;use App\Core\Csrf;use App\Core\Permission;use App\Models\PaymentSchedule;use App\Services\BillingDocumentService;use App\Services\CashReceiptMailer;
final class BillingDocumentsController extends Controller
{
 private function org():int{return (int)(Auth::user()['organisation_id']??1);}
 public function invoice():void{Auth::requireLogin();Permission::require('facturation.view');$d=(new BillingDocumentService())->invoice((int)$_GET['id'],$this->org());header('Content-Type:text/html;charset=UTF-8');echo '<button onclick="window.print()">Imprimer / PDF</button>'.$d['html'];}
 public function receipt():void{Auth::requireLogin();Permission::require('treasury.receipts');$d=(new BillingDocumentService())->receipt((int)$_GET['payment_id'],$this->org(),(int)Auth::id());header('Content-Type:text/html;charset=UTF-8');echo '<button onclick="window.print()">Imprimer / PDF</button>'.$d['html'];}
 public function emailReceipt():void{Auth::requireLogin();Permission::require('treasury.receipts');Csrf::verify($_POST['_csrf']??null);CashReceiptMailer::send((int)$_POST['payment_id'],$this->org(),(int)Auth::id());$_SESSION['success']='Reçu espèces envoyé et journalisé.';$this->redirect('/facturation/voir?id='.(int)$_POST['invoice_id']);}
 public function schedule():void
 {
  Auth::requireLogin();Permission::require('facturation.schedules');Csrf::verify($_POST['_csrf']??null);
  $invoice=(int)($_POST['invoice_id']??0);
  try{
   PaymentSchedule::add($this->org(),$invoice,$_POST,(int)Auth::id());
   $_SESSION['success']='L’échéance a été ajoutée.';
  }catch(\Throwable $e){
   $_SESSION['form_errors']=[$e->getMessage()];
  }
  $this->redirect('/facturation/voir?id='.$invoice);
 }
 public function reminders():void{Auth::requireLogin();Permission::require('facturation.schedules');$this->view('billing/reminders',['pageTitle'=>'Échéances et rappels','items'=>PaymentSchedule::due($this->org())]);}
}
