<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Models\PricingV51;
use App\Models\DiscountRuleV51;

final class PricingV51Controller extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('tarifs.view');

        $grid=PricingV51::activeGrid();

        $this->view('pricing_v51/index',[
            'pageTitle'=>'Grille tarifaire TTC',
            'grid'=>$grid,
            'courses'=>PricingV51::courseCatalog(),
            'lines'=>$grid
                ? PricingV51::lines((int)$grid['id'])
                : [],
        ]);
    }

    public function addLine(): void
    {
        Auth::requireLogin();
        Permission::require('tarifs.manage');
        Csrf::verify($_POST['_csrf'] ?? null);

        $gridId=(int)($_POST['grille_id'] ?? 0);
        $courseId=(int)($_POST['atelier_id'] ?? 0);
        $amount=(float)($_POST['montant'] ?? -1);

        if(!$gridId || !$courseId || $amount<0){
            $_SESSION['error']='La ligne tarifaire est incomplète.';
            $this->redirect('/tarifs');
        }

        $course=null;
        foreach(PricingV51::courseCatalog() as $row){
            if((int)$row['id']===$courseId){
                $course=$row;
                break;
            }
        }

        PricingV51::addLine([
            'grille_id'=>$gridId,
            'atelier_id'=>$courseId,
            'libelle'=>$course
                ? $course['code'].' — '.$course['libelle']
                : 'Cours',
            'montant'=>$amount,
            'periodicite'=>$_POST['periodicite'] ?? 'annuel',
        ]);

        $_SESSION['success']='Le tarif TTC a été ajouté.';
        $this->redirect('/tarifs');
    }

    public function reductions(): void
    {
        Auth::requireLogin();
        Permission::require('reductions.view');

        $year=PricingV51::activeGrid();

        $this->view('pricing_v51/reductions',[
            'pageTitle'=>'Réductions',
            'rules'=>DiscountRuleV51::all(),
            'grid'=>$year,
        ]);
    }

    public function createReduction(): void
    {
        Auth::requireLogin();
        Permission::require('reductions.manage');
        Csrf::verify($_POST['_csrf'] ?? null);

        $grid=PricingV51::activeGrid();

        if(!$grid){
            $_SESSION['error']='Crée d’abord une grille tarifaire.';
            $this->redirect('/tarifs/reductions');
        }

        $conditionType=$_POST['condition_type'] ?? 'autre';
        $explication=trim($_POST['explication'] ?? '');

        if($explication===''){
            $_SESSION['error']=
                'Une explication est obligatoire pour chaque réduction.';
            $this->redirect('/tarifs/reductions');
        }

        $city=$conditionType==='residence'
            ? strtoupper(trim($_POST['ville_cible'] ?? 'BRAY-DUNES'))
            : null;

        DiscountRuleV51::create([
            'organisation_id'=>(int)(Auth::user()['organisation_id'] ?? 1),
            'annee_scolaire_id'=>(int)$grid['annee_scolaire_id'],
            'code'=>strtoupper(trim($_POST['code'] ?? '')),
            'libelle'=>trim($_POST['libelle'] ?? ''),
            'type_reduction'=>$_POST['type_reduction'] ?? 'pourcentage',
            'valeur'=>(float)($_POST['valeur'] ?? 0),
            'condition_type'=>$conditionType,
            'condition_json'=>json_encode([
                'seuil'=>(int)($_POST['seuil'] ?? 0),
                'ville'=>$city,
            ],JSON_UNESCAPED_UNICODE),
            'cumulable'=>isset($_POST['cumulable']) ? 1 : 0,
            'priorite'=>(int)($_POST['priorite'] ?? 100),
            'date_debut'=>$_POST['date_debut'],
            'date_fin'=>$_POST['date_fin'] ?: null,
            'actif'=>isset($_POST['actif']) ? 1 : 0,
            'explication'=>$explication,
            'ville_cible'=>$city,
        ]);

        $_SESSION['success']='La réduction a été créée.';
        $this->redirect('/tarifs/reductions');
    }
}
