<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Models\ReductionParameter;

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

        $this->view('parameters/reductions',[
            'pageTitle'=>'Paramétrage des réductions',
            'rules'=>ReductionParameter::all(),
            'year'=>ReductionParameter::currentYear(),
        ]);
    }

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

        $year=ReductionParameter::currentYear();
        $explanation=trim($_POST['explication'] ?? '');

        if(!$year || trim($_POST['code'] ?? '')==='' ||
           trim($_POST['libelle'] ?? '')==='' ||
           $explanation===''){
            $_SESSION['error']=
                'Le code, le libellé et l’explication sont obligatoires.';
            $this->redirect('/parametres/reductions');
        }

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

        ReductionParameter::create([
            'organisation_id'=>
                (int)(Auth::user()['organisation_id'] ?? 1),
            'annee_scolaire_id'=>(int)$year['id'],
            'code'=>strtoupper(trim($_POST['code'])),
            'libelle'=>trim($_POST['libelle']),
            'type_reduction'=>
                $_POST['type_reduction'] ?? 'pourcentage',
            'valeur'=>(float)($_POST['valeur'] ?? 0),
            'condition_type'=>$condition,
            'ville_cible'=>$city,
            'seuil'=>($_POST['seuil'] ?? '') !== ''
                ? (int)$_POST['seuil']
                : null,
            'explication'=>$explanation,
            'justificatif_requis'=>
                isset($_POST['justificatif_requis']) ? 1 : 0,
            'cumulable'=>isset($_POST['cumulable']) ? 1 : 0,
            'priorite'=>(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,
        ]);

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