<?php
use App\Core\Csrf;
use App\Core\Permission;

$canManage = Permission::can('parametres.contrats.manage');
?>

<link rel="stylesheet" href="/public/assets/css/cda-contracts.css?v=7210">

<section class="contract-page-head">
    <div>
        <span class="page-kicker">Studio RH · Référentiel</span>
        <h2>Types de contrats</h2>
        <p>Définissez les contrats disponibles dans les dossiers des professeurs.</p>
    </div>

    <?php if ($canManage): ?>
        <button type="button" class="button button-primary" data-contract-create>
            <span aria-hidden="true">＋</span>
            Nouveau type
        </button>
    <?php endif; ?>
</section>

<section class="contract-toolbar" aria-label="Outils de recherche">
    <label class="contract-search">
        <span aria-hidden="true">⌕</span>
        <input
            type="search"
            placeholder="Rechercher un type de contrat…"
            autocomplete="off"
            data-contract-search
        >
    </label>

    <div class="contract-counter">
        <strong data-contract-count><?= count($types) ?></strong>
        type<?= count($types) > 1 ? 's' : '' ?>
    </div>
</section>

<?php if (!$types): ?>
    <section class="contract-empty">
        <span>📄</span>
        <h3>Aucun type de contrat</h3>
        <p>Créez le premier type utilisé dans les dossiers professeurs.</p>
    </section>
<?php else: ?>
    <section class="contract-type-grid" data-contract-grid>
        <?php foreach ($types as $type):
            $color = $type['couleur'] ?: '#64748B';
            $searchText = mb_strtolower(
                (string)$type['libelle'] . ' ' .
                (string)$type['code'] . ' ' .
                (string)($type['description'] ?? '')
            );
        ?>
            <article
                class="contract-type-card"
                style="--contract-color:<?= htmlspecialchars($color) ?>"
                data-contract-card
                data-search="<?= htmlspecialchars($searchText) ?>"
            >
                <header class="contract-card-head">
                    <span class="contract-icon" aria-hidden="true">
                        <?= htmlspecialchars($type['icone'] ?: '📄') ?>
                    </span>

                    <div class="contract-title">
                        <strong><?= htmlspecialchars($type['libelle']) ?></strong>
                        <span class="contract-code"><?= htmlspecialchars($type['code']) ?></span>
                    </div>
                </header>

                <p class="contract-description">
                    <?= htmlspecialchars($type['description'] ?: 'Aucune description renseignée.') ?>
                </p>

                <div class="contract-flags">
                    <span class="<?= $type['compte_anciennete'] ? 'is-enabled' : 'is-disabled' ?>">
                        <?= $type['compte_anciennete'] ? '✓' : '—' ?> Ancienneté
                    </span>
                    <span class="<?= $type['autorise_avenants'] ? 'is-enabled' : 'is-disabled' ?>">
                        <?= $type['autorise_avenants'] ? '✓' : '—' ?> Avenants
                    </span>
                    <span class="<?= $type['autorise_vacances'] ? 'is-enabled' : 'is-disabled' ?>">
                        <?= $type['autorise_vacances'] ? '✓' : '—' ?> Vacances
                    </span>
                </div>

                <?php if ($canManage): ?>
                    <footer class="contract-card-actions">
                        <button
                            type="button"
                            class="contract-action contract-action-edit"
                            data-contract-edit
                            data-id="<?= (int)$type['id'] ?>"
                            data-code="<?= htmlspecialchars($type['code']) ?>"
                            data-libelle="<?= htmlspecialchars($type['libelle']) ?>"
                            data-description="<?= htmlspecialchars($type['description'] ?? '') ?>"
                            data-icone="<?= htmlspecialchars($type['icone'] ?: '📄') ?>"
                            data-couleur="<?= htmlspecialchars($color) ?>"
                            data-ordre="<?= (int)($type['ordre_affichage'] ?? 100) ?>"
                            data-anciennete="<?= (int)$type['compte_anciennete'] ?>"
                            data-avenants="<?= (int)$type['autorise_avenants'] ?>"
                            data-vacances="<?= (int)$type['autorise_vacances'] ?>"
                        >
                            ✎ Modifier
                        </button>

                        <form
                            method="post"
                            action="/public/parametres/types-contrats/archiver"
                            onsubmit="return confirm('Archiver ce type de contrat ?');"
                        >
                            <?= Csrf::field() ?>
                            <input type="hidden" name="id" value="<?= (int)$type['id'] ?>">
                            <button type="submit" class="contract-action contract-action-archive">
                                ▣ Archiver
                            </button>
                        </form>
                    </footer>
                <?php endif; ?>
            </article>
        <?php endforeach; ?>
    </section>

    <section class="contract-no-result" data-contract-no-result hidden>
        <span>⌕</span>
        <strong>Aucun résultat</strong>
        <p>Modifiez les termes de votre recherche.</p>
    </section>
<?php endif; ?>

<?php if ($canManage): ?>
<div class="contract-modal" data-contract-modal hidden>
    <div class="contract-modal-backdrop" data-contract-close></div>

    <section
        class="contract-modal-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="contract-modal-title"
    >
        <header>
            <div>
                <span class="page-kicker">Référentiel RH</span>
                <h3 id="contract-modal-title" data-contract-modal-title>Nouveau type de contrat</h3>
            </div>
            <button type="button" class="contract-modal-close" data-contract-close aria-label="Fermer">×</button>
        </header>

        <form method="post" action="/public/parametres/types-contrats" data-contract-form>
            <?= Csrf::field() ?>
            <input type="hidden" name="id" value="" data-field="id">

            <div class="contract-form-grid">
                <label>
                    <span>Code <em>*</em></span>
                    <input
                        required
                        maxlength="20"
                        name="code"
                        placeholder="Ex. CDI"
                        data-field="code"
                    >
                </label>

                <label class="wide">
                    <span>Libellé <em>*</em></span>
                    <input
                        required
                        maxlength="150"
                        name="libelle"
                        placeholder="Ex. Contrat à durée indéterminée"
                        data-field="libelle"
                    >
                </label>

                <label>
                    <span>Icône</span>
                    <input
                        maxlength="8"
                        name="icone"
                        value="📄"
                        data-field="icone"
                    >
                </label>

                <label>
                    <span>Couleur</span>
                    <input
                        type="color"
                        name="couleur"
                        value="#64748B"
                        data-field="couleur"
                    >
                </label>

                <label>
                    <span>Ordre d’affichage</span>
                    <input
                        type="number"
                        min="0"
                        max="9999"
                        name="ordre_affichage"
                        value="100"
                        data-field="ordre"
                    >
                </label>

                <fieldset class="contract-options wide">
                    <legend>Comportement du contrat</legend>

                    <label>
                        <input type="checkbox" name="compte_anciennete" data-field="anciennete">
                        <span><strong>Ancienneté</strong><small>La période compte dans le calcul.</small></span>
                    </label>

                    <label>
                        <input type="checkbox" name="autorise_avenants" data-field="avenants">
                        <span><strong>Avenants</strong><small>Des avenants peuvent être rattachés.</small></span>
                    </label>

                    <label>
                        <input type="checkbox" name="autorise_vacances" data-field="vacances">
                        <span><strong>Vacances</strong><small>Le contrat autorise les périodes de vacances.</small></span>
                    </label>
                </fieldset>

                <label class="wide">
                    <span>Description</span>
                    <textarea
                        rows="4"
                        name="description"
                        placeholder="Précisez l’usage de ce type de contrat."
                        data-field="description"
                    ></textarea>
                </label>
            </div>

            <footer>
                <button type="button" class="button button-secondary" data-contract-close>
                    Annuler
                </button>
                <button type="submit" class="button button-primary">
                    Enregistrer
                </button>
            </footer>
        </form>
    </section>
</div>
<?php endif; ?>

<script>
(() => {
    const search = document.querySelector('[data-contract-search]');
    const cards = [...document.querySelectorAll('[data-contract-card]')];
    const counter = document.querySelector('[data-contract-count]');
    const noResult = document.querySelector('[data-contract-no-result]');

    const normalize = value => (value || '')
        .toLocaleLowerCase('fr')
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '');

    search?.addEventListener('input', () => {
        const query = normalize(search.value.trim());
        let visible = 0;

        cards.forEach(card => {
            const match = normalize(card.dataset.search).includes(query);
            card.hidden = !match;
            if (match) visible++;
        });

        if (counter) counter.textContent = String(visible);
        if (noResult) noResult.hidden = visible !== 0;
    });

    const modal = document.querySelector('[data-contract-modal]');
    const form = document.querySelector('[data-contract-form]');
    if (!modal || !form) return;

    const title = modal.querySelector('[data-contract-modal-title]');
    const field = name => form.querySelector(`[data-field="${name}"]`);
    const open = () => {
        modal.hidden = false;
        document.body.classList.add('contract-modal-open');
        requestAnimationFrame(() => field('code')?.focus());
    };
    const close = () => {
        modal.hidden = true;
        document.body.classList.remove('contract-modal-open');
    };

    document.querySelector('[data-contract-create]')?.addEventListener('click', () => {
        form.reset();
        form.action = '/public/parametres/types-contrats';
        field('id').value = '';
        field('icone').value = '📄';
        field('couleur').value = '#64748B';
        field('ordre').value = '100';
        field('anciennete').checked = true;
        field('avenants').checked = true;
        field('vacances').checked = false;
        title.textContent = 'Nouveau type de contrat';
        open();
    });

    document.querySelectorAll('[data-contract-edit]').forEach(button => {
        button.addEventListener('click', () => {
            form.reset();
            form.action = '/public/parametres/types-contrats/modifier';
            field('id').value = button.dataset.id || '';
            field('code').value = button.dataset.code || '';
            field('libelle').value = button.dataset.libelle || '';
            field('description').value = button.dataset.description || '';
            field('icone').value = button.dataset.icone || '📄';
            field('couleur').value = button.dataset.couleur || '#64748B';
            field('ordre').value = button.dataset.ordre || '100';
            field('anciennete').checked = button.dataset.anciennete === '1';
            field('avenants').checked = button.dataset.avenants === '1';
            field('vacances').checked = button.dataset.vacances === '1';
            title.textContent = 'Modifier le type de contrat';
            open();
        });
    });

    modal.querySelectorAll('[data-contract-close]').forEach(button => {
        button.addEventListener('click', close);
    });

    document.addEventListener('keydown', event => {
        if (event.key === 'Escape' && !modal.hidden) close();
    });
})();
</script>
