<?php
namespace App\Models;

use App\Core\Database;
use PDO;

final class ProfessorContractType
{
    public static function all(bool $activeOnly = true): array
    {
        $sql = "SELECT *
                FROM types_contrats_professeurs
                WHERE deleted_at IS NULL"
            . ($activeOnly ? " AND actif = 1" : "")
            . " ORDER BY ordre_affichage, libelle";

        return Database::connection()->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function create(array $data): int
    {
        $stmt = Database::connection()->prepare(
            "INSERT INTO types_contrats_professeurs (
                organisation_id,
                code,
                libelle,
                description,
                compte_anciennete,
                autorise_avenants,
                autorise_vacances,
                couleur,
                icone,
                ordre_affichage,
                actif
            ) VALUES (
                :organisation_id,
                :code,
                :libelle,
                :description,
                :compte_anciennete,
                :autorise_avenants,
                :autorise_vacances,
                :couleur,
                :icone,
                :ordre_affichage,
                :actif
            )"
        );

        $stmt->execute($data);
        return (int)Database::connection()->lastInsertId();
    }

    public static function update(int $id, array $data): void
    {
        $data['id'] = $id;

        $stmt = Database::connection()->prepare(
            "UPDATE types_contrats_professeurs
             SET code = :code,
                 libelle = :libelle,
                 description = :description,
                 compte_anciennete = :compte_anciennete,
                 autorise_avenants = :autorise_avenants,
                 autorise_vacances = :autorise_vacances,
                 couleur = :couleur,
                 icone = :icone,
                 ordre_affichage = :ordre_affichage,
                 updated_at = CURRENT_TIMESTAMP
             WHERE id = :id
               AND deleted_at IS NULL"
        );

        $stmt->execute($data);
    }

    public static function archive(int $id): void
    {
        Database::connection()->prepare(
            "UPDATE types_contrats_professeurs
             SET actif = 0,
                 deleted_at = CURRENT_TIMESTAMP
             WHERE id = :id"
        )->execute(['id' => $id]);
    }
}
