<?php
$documentIcons = [
    'DEVIS' => 'bi-file-earmark-text',
    'BON_LIVRAISON' => 'bi-truck',
    'FACTURE' => 'bi-receipt',
    'AVOIR' => 'bi-arrow-counterclockwise',
    'COMMANDE_FOURNISSEUR' => 'bi-box-seam',
];

$documentColors = [
    'DEVIS' => 'primary',
    'BON_LIVRAISON' => 'info',
    'FACTURE' => 'success',
    'AVOIR' => 'warning',
    'COMMANDE_FOURNISSEUR' => 'secondary',
];

$currentYear = date('Y');
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">
            <i class="bi bi-123 me-2"></i>Numérotation
        </h1>
        <p class="text-muted mb-0">
            Configurer les préfixes et le format des numéros de documents.
        </p>
    </div>

    <a href="index.php?page=parametres" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i> Retour aux paramètres
    </a>
</div>

<div class="alert alert-info mb-4">
    <i class="bi bi-info-circle me-1"></i>
    Cette page configure les formats de numérotation. Le moteur actuel de génération reste inchangé pour préserver la stabilité de la version 2026.1 LTS.
</div>

<div class="row g-4">
    <?php foreach ($numerotations as $numerotation): ?>
        <?php
        $typeDocument = (string)$numerotation['type_document'];
        $icon = $documentIcons[$typeDocument] ?? 'bi-file-earmark';
        $color = $documentColors[$typeDocument] ?? 'primary';
        $formId = 'numerotation-' . (int)$numerotation['id'];

        $previewPrefix = strtoupper((string)$numerotation['prefixe']);
        $previewLength = (int)$numerotation['longueur_compteur'];
        $previewAnnual = (int)$numerotation['remise_zero_annuelle'] === 1;

        $previewNumber = $previewPrefix
            . ($previewAnnual ? $currentYear : '')
            . '-'
            . str_pad('1', $previewLength, '0', STR_PAD_LEFT);
        ?>

        <div class="col-xl-6">
            <div class="darlink-card overflow-hidden h-100">
                <div class="darlink-admin-block-header d-flex justify-content-between align-items-center">
                    <span>
                        <i class="bi <?= htmlspecialchars($icon) ?> me-2"></i>
                        <?= htmlspecialchars($numerotation['libelle']) ?>
                    </span>

                    <span class="darlink-badge darlink-badge-light">
                        <?= htmlspecialchars($typeDocument) ?>
                    </span>
                </div>

                <form
                    id="<?= $formId ?>"
                    method="post"
                    action="index.php?page=parametres_numerotation_update"
                >
                    <input
                        type="hidden"
                        name="id"
                        value="<?= (int)$numerotation['id'] ?>"
                    >

                    <div class="darlink-card-body">
                        <div class="row g-3">
                            <div class="col-md-6 darlink-form-group">
                                <label class="darlink-label">Préfixe</label>

                                <input
                                    type="text"
                                    name="prefixe"
                                    class="darlink-input numerotation-prefix"
                                    value="<?= htmlspecialchars($numerotation['prefixe']) ?>"
                                    maxlength="20"
                                    data-preview-target="preview-<?= (int)$numerotation['id'] ?>"
                                    required
                                >
                            </div>

                            <div class="col-md-6 darlink-form-group">
                                <label class="darlink-label">Longueur du compteur</label>

                                <input
                                    type="number"
                                    name="longueur_compteur"
                                    class="darlink-input numerotation-length"
                                    value="<?= (int)$numerotation['longueur_compteur'] ?>"
                                    min="3"
                                    max="10"
                                    data-preview-target="preview-<?= (int)$numerotation['id'] ?>"
                                    required
                                >
                            </div>

                            <div class="col-md-6 darlink-form-group">
                                <label class="darlink-label">Remise à zéro annuelle</label>

                                <select
                                    name="remise_zero_annuelle"
                                    class="darlink-select numerotation-annual"
                                    data-preview-target="preview-<?= (int)$numerotation['id'] ?>"
                                >
                                    <option
                                        value="1"
                                        <?= (int)$numerotation['remise_zero_annuelle'] === 1 ? 'selected' : '' ?>
                                    >
                                        Oui
                                    </option>

                                    <option
                                        value="0"
                                        <?= (int)$numerotation['remise_zero_annuelle'] === 0 ? 'selected' : '' ?>
                                    >
                                        Non
                                    </option>
                                </select>
                            </div>

                            <div class="col-md-6 darlink-form-group">
                                <label class="darlink-label">État</label>

                                <select
                                    name="actif"
                                    class="darlink-select"
                                >
                                    <option
                                        value="1"
                                        <?= (int)$numerotation['actif'] === 1 ? 'selected' : '' ?>
                                    >
                                        Actif
                                    </option>

                                    <option
                                        value="0"
                                        <?= (int)$numerotation['actif'] === 0 ? 'selected' : '' ?>
                                    >
                                        Inactif
                                    </option>
                                </select>
                            </div>
                        </div>

                        <div class="darlink-number-preview mt-3">
                            <div class="text-muted small text-uppercase fw-bold mb-2">
                                Aperçu du prochain numéro
                            </div>

                            <div
                                id="preview-<?= (int)$numerotation['id'] ?>"
                                class="darlink-number-preview-value text-<?= htmlspecialchars($color) ?>"
                                data-year="<?= htmlspecialchars($currentYear) ?>"
                            >
                                <?= htmlspecialchars($previewNumber) ?>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between align-items-center gap-2 mt-4 flex-wrap">
                            <button
                                type="button"
                                class="btn btn-outline-secondary"
                                disabled
                                title="Disponible dans Phoenix 2026.2"
                            >
                                <i class="bi bi-arrow-repeat me-1"></i>
                                Réinitialiser le compteur
                            </button>

                            <button
                                type="submit"
                                class="btn darlink-btn-primary"
                            >
                                <i class="bi bi-check-lg me-1"></i>
                                Enregistrer
                            </button>
                        </div>

                        <div class="form-text mt-2">
                            La réinitialisation sécurisée du compteur sera disponible dans Phoenix 2026.2.
                        </div>
                    </div>
                </form>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    function updatePreview(targetId) {
        const preview = document.getElementById(targetId);

        if (!preview) {
            return;
        }

        const card = preview.closest('.darlink-card');

        if (!card) {
            return;
        }

        const prefixInput = card.querySelector('.numerotation-prefix');
        const lengthInput = card.querySelector('.numerotation-length');
        const annualSelect = card.querySelector('.numerotation-annual');

        const prefix = prefixInput
            ? String(prefixInput.value || '').trim().toUpperCase()
            : '';

        let length = lengthInput
            ? parseInt(lengthInput.value || '6', 10)
            : 6;

        if (!Number.isFinite(length)) {
            length = 6;
        }

        length = Math.max(3, Math.min(10, length));

        const annual = annualSelect
            ? annualSelect.value === '1'
            : true;

        const year = annual
            ? String(preview.dataset.year || '')
            : '';

        const counter = String(1).padStart(length, '0');

        preview.textContent =
            prefix +
            year +
            '-' +
            counter;
    }

    document
        .querySelectorAll(
            '.numerotation-prefix, .numerotation-length, .numerotation-annual'
        )
        .forEach(function (field) {
            const targetId = field.dataset.previewTarget;

            if (!targetId) {
                return;
            }

            field.addEventListener('input', function () {
                updatePreview(targetId);
            });

            field.addEventListener('change', function () {
                updatePreview(targetId);
            });

            updatePreview(targetId);
        });
});
</script>