<?php
namespace App\Controllers;
use App\Core\Auth;use App\Core\Controller;use App\Core\Csrf;use App\Core\Permission;use App\Models\Treasury;
final class TreasuryController extends Controller
{
 private function org():int{return (int)(Auth::user()['organisation_id']??1);} private function guard(string $p):void{Auth::requireLogin();Permission::require($p);}
 public function index():void{$this->guard('treasury.view');$this->view('treasury/index',['pageTitle'=>'Trésorerie, caisses et chèques']+Treasury::dashboard($this->org())+['users'=>Treasury::users($this->org()),'clients'=>Treasury::clients($this->org()),'advances'=>Treasury::advances($this->org()),'cashCounts'=>Treasury::recentCounts($this->org()),'pending'=>Treasury::pendingTransfers($this->org())]);}
 public function register():void{$this->guard('treasury.settings');Csrf::verify($_POST['_csrf']??null);Treasury::createRegister($this->org(),$_POST,(int)Auth::id());$this->redirect('/comptabilite/tresorerie');}
 public function transfer():void{$this->guard('treasury.cash.manage');Csrf::verify($_POST['_csrf']??null);Treasury::requestTransfer($this->org(),(int)$_POST['source_register_id'],(int)$_POST['target_register_id'],round((float)$_POST['amount'],2),(int)Auth::id());$this->redirect('/comptabilite/tresorerie');}
 public function accept():void{$this->guard('treasury.treasurer');Csrf::verify($_POST['_csrf']??null);Treasury::acceptTransfer($this->org(),(int)$_POST['id'],(int)Auth::id());$this->redirect('/comptabilite/tresorerie');}
 public function count():void{$this->guard('treasury.cash.manage');Csrf::verify($_POST['_csrf']??null);Treasury::countCash($this->org(),(int)$_POST['register_id'],$_POST['period_month'],$_POST['quantity']??[],(int)Auth::id());$this->redirect('/comptabilite/tresorerie');}
 public function validateCount():void{$this->guard('treasury.treasurer');Csrf::verify($_POST['_csrf']??null);Treasury::validateCount($this->org(),(int)$_POST['id'],(int)Auth::id());$_SESSION['success']='Contrôle mensuel validé par la trésorière.';$this->redirect('/comptabilite/tresorerie');}
 public function createDeposit():void{$this->guard('treasury.treasurer');Csrf::verify($_POST['_csrf']??null);Treasury::createDeposit($this->org(),$_POST['cheque_ids']??[],(int)Auth::id());$this->redirect('/comptabilite/tresorerie');}
 public function deposit():void{$this->guard('treasury.treasurer');Csrf::verify($_POST['_csrf']??null);Treasury::deposit($this->org(),(int)$_POST['id'],(int)Auth::id());$this->redirect('/comptabilite/tresorerie');}
 public function cashDepositForm():void{$this->guard('treasury.treasurer');$this->view('treasury/cash_deposit',['pageTitle'=>'Dépôt espèces en banque','registers'=>Treasury::dashboard($this->org())['registers']]);}
 public function cashDeposit():void{$this->guard('treasury.treasurer');Csrf::verify($_POST['_csrf']??null);Treasury::cashDeposit($this->org(),(int)$_POST['register_id'],round((float)$_POST['amount'],2),$_POST['deposit_date']?:date('Y-m-d'),(int)Auth::id());$this->redirect('/comptabilite/tresorerie');}
 public function clientAdvance():void{$this->guard('treasury.cash.manage');Csrf::verify($_POST['_csrf']??null);Treasury::createClientAdvance($this->org(),(int)$_POST['client_id'],(int)$_POST['register_id'],round((float)$_POST['amount'],2),$_POST['received_date']?:date('Y-m-d'),trim((string)($_POST['notes']??'')),(int)Auth::id());$this->redirect('/comptabilite/tresorerie');}
 public function allocateAdvance():void{$this->guard('facturation.payments');Csrf::verify($_POST['_csrf']??null);Treasury::allocateAdvance($this->org(),(int)$_POST['advance_id'],(int)$_POST['invoice_id'],round((float)$_POST['amount'],2),(int)Auth::id());$_SESSION['success']='Avance affectée à la facture.';$target=!empty($_POST['return_invoice'])?'/facturation/voir?id='.(int)$_POST['invoice_id']:'/comptabilite/tresorerie';$this->redirect($target);}
 public function advanceReceipt():void{$this->guard('treasury.view');$receipt=Treasury::advanceReceipt($this->org(),(int)($_GET['id']??0));if(!$receipt){http_response_code(404);exit('Reçu introuvable.');}header('Content-Type:text/html;charset=UTF-8');require BASE_PATH.'/app/Views/treasury/advance_receipt.php';}
 public function emailAdvanceReceipt():void{$this->guard('treasury.receipts');Csrf::verify($_POST['_csrf']??null);Treasury::emailAdvanceReceipt($this->org(),(int)$_POST['id']);$_SESSION['success']='Reçu d’avance envoyé par e-mail.';$this->redirect('/comptabilite/tresorerie');}
 public function refundAdvance():void{$this->guard('treasury.treasurer');Csrf::verify($_POST['_csrf']??null);Treasury::refundAdvance($this->org(),(int)$_POST['id'],trim((string)($_POST['reason']??'')),(int)Auth::id());$_SESSION['success']='Reliquat remboursé et écritures inversées.';$this->redirect('/comptabilite/tresorerie');}
 public function journal():void{$this->guard('treasury.view');$from=$_GET['from']??date('Y-m-01');$to=$_GET['to']??date('Y-m-t');$register=(int)($_GET['register_id']??0);$this->view('treasury/journal',['pageTitle'=>'Journal de caisse','items'=>Treasury::cashJournal($this->org(),$from,$to,$register),'registers'=>Treasury::dashboard($this->org())['registers'],'from'=>$from,'to'=>$to,'registerId'=>$register]);}
 public function journalCsv():void{$this->guard('treasury.view');$from=$_GET['from']??date('Y-m-01');$to=$_GET['to']??date('Y-m-t');$items=Treasury::cashJournal($this->org(),$from,$to,(int)($_GET['register_id']??0));header('Content-Type:text/csv;charset=UTF-8');header('Content-Disposition:attachment;filename="journal-caisse-'.$from.'-'.$to.'.csv"');echo "\xEF\xBB\xBFDate;Caisse;Type;Libellé;Entrée;Sortie;Adhérent\r\n";foreach($items as $i){$in=in_array($i['movement_type'],['opening','cash_payment','client_advance'],true)?$i['amount']:($i['movement_type']==='transfer'&&$i['target_register_id']==$i['view_register_id']?$i['amount']:0);$out=$in?0:$i['amount'];echo implode(';',[$i['movement_date'],$i['register_name'],$i['movement_type'],str_replace(';',',',$i['label']),number_format((float)$in,2,',',''),number_format((float)$out,2,',',''),str_replace(';',',',$i['client_label']??'')])."\r\n";}exit;}
 public function accountingCsv():void{$this->guard('facturation.accounting');$from=$_GET['from']??date('Y-01-01');$to=$_GET['to']??date('Y-12-31');$journal=trim((string)($_GET['journal']??''));$items=Treasury::accountingEntries($this->org(),$from,$to,$journal);header('Content-Type:text/csv;charset=UTF-8');header('Content-Disposition:attachment;filename="ecritures-'.$from.'-'.$to.'.csv"');echo "\xEF\xBB\xBFDate;Journal;Compte;Libellé;Débit;Crédit\r\n";foreach($items as $e)echo implode(';',[$e['entry_date'],$e['journal_code'],$e['account_number'],str_replace(';',',',$e['label']),number_format((float)$e['debit'],2,',',''),number_format((float)$e['credit'],2,',','')])."\r\n";exit;}
}
