<?php
namespace App\Models;

use App\Core\Database;

final class ReductionParameter
{
    public static function all(): array
    {
        return Database::connection()->query(
            "SELECT r.*,a.libelle AS annee_libelle
             FROM regles_reduction r
             INNER JOIN annees_scolaires a
                     ON a.id=r.annee_scolaire_id
             ORDER BY r.actif DESC,r.priorite,r.libelle"
        )->fetchAll();
    }

    public static function currentYear(): ?array
    {
        return Database::connection()->query(
            "SELECT id,libelle,date_debut,date_fin
             FROM annees_scolaires
             WHERE active=1
             ORDER BY id DESC
             LIMIT 1"
        )->fetch() ?: null;
    }

    public static function create(array $data): int
    {
        $stmt=Database::connection()->prepare(
            "INSERT INTO regles_reduction(
                organisation_id,
                annee_scolaire_id,
                code,
                libelle,
                type_reduction,
                valeur,
                condition_type,
                ville_cible,
                seuil,
                explication,
                justificatif_requis,
                cumulable,
                priorite,
                date_debut,
                date_fin,
                actif
             ) VALUES(
                :organisation_id,
                :annee_scolaire_id,
                :code,
                :libelle,
                :type_reduction,
                :valeur,
                :condition_type,
                :ville_cible,
                :seuil,
                :explication,
                :justificatif_requis,
                :cumulable,
                :priorite,
                :date_debut,
                :date_fin,
                :actif
             )"
        );
        $stmt->execute($data);
        return (int)Database::connection()->lastInsertId();
    }
}
