<?php
namespace App\Controllers;

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

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

        $this->view('parameters/contract_types', [
            'pageTitle' => 'Types de contrats',
            'types' => ProfessorContractType::all(false),
        ]);
    }

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

        $data = $this->payload();

        if ($data['code'] === '' || $data['libelle'] === '') {
            $_SESSION['error'] = 'Le code et le libellé sont obligatoires.';
            $this->redirect('/parametres/types-contrats');
        }

        ProfessorContractType::create($data + [
            'organisation_id' => (int)(Auth::user()['organisation_id'] ?? 1),
            'actif' => 1,
        ]);

        $_SESSION['success'] = 'Type de contrat créé.';
        $this->redirect('/parametres/types-contrats');
    }

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

        $id = (int)($_POST['id'] ?? 0);
        $data = $this->payload();

        if ($id <= 0 || $data['code'] === '' || $data['libelle'] === '') {
            $_SESSION['error'] = 'Données incomplètes pour modifier ce type de contrat.';
            $this->redirect('/parametres/types-contrats');
        }

        ProfessorContractType::update($id, $data);
        $_SESSION['success'] = 'Type de contrat modifié.';
        $this->redirect('/parametres/types-contrats');
    }

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

        ProfessorContractType::archive((int)($_POST['id'] ?? 0));
        $_SESSION['success'] = 'Type de contrat archivé.';
        $this->redirect('/parametres/types-contrats');
    }

    private function payload(): array
    {
        $color = trim((string)($_POST['couleur'] ?? '#64748B'));
        if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) {
            $color = '#64748B';
        }

        return [
            'code' => mb_strtoupper(trim((string)($_POST['code'] ?? ''))),
            'libelle' => trim((string)($_POST['libelle'] ?? '')),
            'description' => trim((string)($_POST['description'] ?? '')) ?: null,
            'compte_anciennete' => isset($_POST['compte_anciennete']) ? 1 : 0,
            'autorise_avenants' => isset($_POST['autorise_avenants']) ? 1 : 0,
            'autorise_vacances' => isset($_POST['autorise_vacances']) ? 1 : 0,
            'couleur' => $color,
            'icone' => trim((string)($_POST['icone'] ?? '📄')) ?: '📄',
            'ordre_affichage' => max(0, (int)($_POST['ordre_affichage'] ?? 100)),
        ];
    }
}
