<?php
namespace App\Controllers;
use App\Core\Auth;use App\Core\Controller;use App\Core\Csrf;use App\Core\Permission;use App\Models\Pricing;use App\Models\PricingCatalog;use App\Models\DiscountRule;use App\Models\PricingDistribution;
final class PricingController extends Controller
{
 private function org():int{return (int)(Auth::user()['organisation_id']??1);}
 public function index():void{Auth::requireLogin();Permission::require('tarifs.view');$o=$this->org();$this->view('pricing_catalog/index',['pageTitle'=>'Catalogue des prestations','items'=>PricingCatalog::all($o),'poles'=>PricingCatalog::poles($o),'disciplines'=>PricingCatalog::disciplines($o),'courses'=>PricingCatalog::courses($o),'publics'=>PricingCatalog::publics($o),'years'=>PricingCatalog::years($o)]);}
 public function addLine():void{Auth::requireLogin();Permission::require('tarifs.manage');Csrf::verify($_POST['_csrf']??null);if(($_POST['form_action']??'')==='create_year'){$this->createSchoolYear();return;}$v=$_POST;$v['mode_tarif']=in_array($v['mode_tarif']??'', ['fixe','libre','modifiable'],true)?$v['mode_tarif']:'fixe';$v['code']=strtoupper(trim((string)($v['code']??'')));$v['libelle']=trim((string)($v['libelle']??''));$labelRequired=($v['mode_libelle']??'propose')!=='libre';if($v['code']===''||($labelRequired&&$v['libelle']==='')||(int)($v['pole_id']??0)<1||($v['mode_tarif']!=='libre'&&($v['montant']??'')==='')||(($v['categorie']??'')==='adhesion'&&(int)($v['annee_scolaire_id']??0)<1)){$_SESSION['error']='Vérifiez le pôle, l’année, le libellé et le montant requis.';$this->redirect('/tarifs');}try{PricingCatalog::save($this->org(),$v);$_SESSION['success']='La prestation a été enregistrée.';}catch(\Throwable $e){$_SESSION['error']=$e->getMessage();}$this->redirect('/tarifs');}
 private function createSchoolYear():void{try{PricingCatalog::createYear($this->org(),$_POST);$_SESSION['success']='La nouvelle année scolaire a été créée.';}catch(\Throwable $e){$_SESSION['error']=$e->getMessage();}$this->redirect('/tarifs');}
 public function createGrid():void{Auth::requireLogin();Permission::require('tarifs.manage');$_SESSION['error']='Les prestations sont gérées dans le catalogue AXIOM.';$this->redirect('/tarifs');}
 public function pdf():void{Auth::requireLogin();Permission::require('tarifs.pdf.generate');$g=Pricing::activeGrid();if(!$g){http_response_code(404);exit('Aucune grille tarifaire disponible.');}$this->view('pricing/pdf',['pageTitle'=>'Tarifs du Carrefour des Arts','grid'=>$g,'lines'=>Pricing::lines((int)$g['id']),'hideNavigation'=>true]);}
 public function reductions():void{Auth::requireLogin();Permission::require('reductions.view');$this->view('pricing/reductions',['pageTitle'=>'Réductions','rules'=>DiscountRule::all($this->org()),'year'=>Pricing::currentYear()]);}
 public function createReduction():void{Auth::requireLogin();Permission::require('reductions.manage');Csrf::verify($_POST['_csrf']??null);$year=Pricing::currentYear();if(!$year){$_SESSION['error']='Créez ou activez d’abord une année scolaire.';$this->redirect('/tarifs/reductions');return;}$condition=in_array($_POST['condition_type']??'', ['multi_activites','plusieurs_membres','residence','cours','pole','public','exceptionnelle','autre'],true)?$_POST['condition_type']:'autre';$free=$condition==='exceptionnelle'&&isset($_POST['valeur_libre']);$code=strtoupper(trim((string)($_POST['code']??'')));$label=trim((string)($_POST['libelle']??''));if($code===''||$label===''){$_SESSION['error']='Le code et le libellé sont obligatoires.';$this->redirect('/tarifs/reductions');return;}$data=['code'=>$code,'libelle'=>$label,'type_reduction'=>in_array($_POST['type_reduction']??'', ['pourcentage','montant_fixe'],true)?$_POST['type_reduction']:'montant_fixe','valeur'=>$free?0:(float)($_POST['valeur']??0),'condition_type'=>$condition,'condition_json'=>json_encode(['seuil'=>(int)($_POST['seuil']??0),'commentaire'=>trim((string)($_POST['commentaire']??'')),'saisie_facturation'=>$free,'validation_requise'=>$free],JSON_UNESCAPED_UNICODE),'cumulable'=>isset($_POST['cumulable'])?1:0,'priorite'=>max(1,(int)($_POST['priorite']??100)),'date_debut'=>$_POST['date_debut']?:$year['date_debut'],'date_fin'=>$_POST['date_fin']?:$year['date_fin'],'actif'=>isset($_POST['actif'])?1:0];try{$id=(int)($_POST['reduction_id']??0);if($id>0){DiscountRule::update($id,$this->org(),$data);$_SESSION['success']='La réduction a été modifiée.';}else{$data['organisation_id']=$this->org();$data['annee_scolaire_id']=(int)$year['id'];unset($data['actif']);DiscountRule::create($data);$_SESSION['success']='La réduction a été enregistrée.';}}catch(\Throwable $e){$_SESSION['error']=$e->getMessage();}$this->redirect('/tarifs/reductions');}
 public function diffusion():void{Auth::requireLogin();Permission::require('tarifs.diffusion.preview');$this->view('pricing/diffusion',['pageTitle'=>'Diffusion de la grille tarifaire','summary'=>PricingDistribution::activeAdherentsSummary(),'adherents'=>PricingDistribution::activeAdherents(),'grid'=>Pricing::activeGrid()]);}
}
