<?php
namespace App\Models;
use App\Core\Database;
final class DiscountRule
{
 public static function all(int $organisationId):array{$q=Database::connection()->prepare("SELECT r.*,a.libelle AS annee_libelle FROM regles_reduction r INNER JOIN annees_scolaires a ON a.id=r.annee_scolaire_id WHERE r.organisation_id=? ORDER BY r.actif DESC,r.priorite,r.libelle");$q->execute([$organisationId]);return $q->fetchAll();}
 public static function create(array $data):int{$q=Database::connection()->prepare("INSERT INTO regles_reduction(organisation_id,annee_scolaire_id,code,libelle,type_reduction,valeur,condition_type,condition_json,cumulable,priorite,date_debut,date_fin,actif) VALUES(:organisation_id,:annee_scolaire_id,:code,:libelle,:type_reduction,:valeur,:condition_type,:condition_json,:cumulable,:priorite,:date_debut,:date_fin,1) ON DUPLICATE KEY UPDATE libelle=VALUES(libelle),type_reduction=VALUES(type_reduction),valeur=VALUES(valeur),condition_type=VALUES(condition_type),condition_json=VALUES(condition_json),cumulable=VALUES(cumulable),priorite=VALUES(priorite),date_debut=VALUES(date_debut),date_fin=VALUES(date_fin),actif=1");$q->execute($data);return (int)Database::connection()->lastInsertId();}
 public static function update(int $id,int $organisationId,array $data):void{$data['id']=$id;$data['organisation_id']=$organisationId;$q=Database::connection()->prepare("UPDATE regles_reduction SET code=:code,libelle=:libelle,type_reduction=:type_reduction,valeur=:valeur,condition_type=:condition_type,condition_json=:condition_json,cumulable=:cumulable,priorite=:priorite,date_debut=:date_debut,date_fin=:date_fin,actif=:actif WHERE id=:id AND organisation_id=:organisation_id");$q->execute($data);if($q->rowCount()===0){$c=Database::connection()->prepare("SELECT COUNT(*) FROM regles_reduction WHERE id=? AND organisation_id=?");$c->execute([$id,$organisationId]);if(!(int)$c->fetchColumn())throw new \RuntimeException('Réduction introuvable ou non autorisée.');}}
}
