<?php
// app/view/admin/pedagogie/semestre/create-edit/index.php
// Ce fichier est inclus dans la page principale
// Les variables $semestre et $isEdit sont définies avant l'inclusion
?>

<div class="modal-overlay" id="semestreModal">
    <div class="modal modal-lg">
        <div class="modal-header">
            <h2 id="modalTitle"><?= $isEdit ? 'Modifier le Semestre' : 'Nouveau Semestre' ?></h2>
            <button class="modal-close" onclick="closeSemestreModal()">&times;</button>
        </div>
        
        <div class="modal-body">
            <form id="semestreForm">
                <input type="hidden" id="semestreId" value="<?= $isEdit ? $semestre['id'] : '' ?>">

                <!-- ===================== -->
                <!-- INFORMATIONS GENERALES -->
                <!-- ===================== -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-info-circle"></i>
                        Informations générales
                    </h3>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Libellé <span class="required">*</span></label>
                            <input type="text"
                                   id="libelle"
                                   class="form-control"
                                   placeholder="Ex: Semestre 1"
                                   value="<?= $isEdit ? htmlspecialchars($semestre['libelle']) : '' ?>"
                                   required>
                            <small class="form-text text-muted">Nom complet du semestre</small>
                        </div>

                        <div class="form-group">
                            <label>Code <span class="required">*</span></label>
                            <input type="text"
                                   id="code"
                                   class="form-control"
                                   placeholder="Ex: S1"
                                   value="<?= $isEdit ? htmlspecialchars($semestre['code']) : '' ?>"
                                   required>
                            <small class="form-text text-muted">Code unique du semestre</small>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Année universitaire <span class="required">*</span></label>
                            <select id="annee_universitaire" class="form-control" required>
                                <option value="">Sélectionner une année</option>
                                <?php
                                $currentYear = date('Y');
                                for ($i = 0; $i < 5; $i++) {
                                    $year = $currentYear - $i;
                                    $annee = $year . '-' . ($year + 1);
                                    $selected = ($isEdit && $semestre['annee_universitaire'] == $annee) ? 'selected' : '';
                                    echo "<option value='$annee' $selected>$annee</option>";
                                }
                                ?>
                            </select>
                            <small class="form-text text-muted">Année universitaire du semestre</small>
                        </div>

                        <div class="form-group">
                            <label>Statut</label>
                            <select id="status" class="form-control">
                                <option value="actif" <?= $isEdit && $semestre['status'] == 'actif' ? 'selected' : '' ?>>Actif</option>
                                <option value="inactif" <?= $isEdit && $semestre['status'] == 'inactif' ? 'selected' : '' ?>>Inactif</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- ===================== -->
                <!-- DATES -->
                <!-- ===================== -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-calendar-alt"></i>
                        Période du semestre
                    </h3>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Date de début</label>
                            <input type="date"
                                   id="date_debut"
                                   class="form-control"
                                   value="<?= $isEdit && $semestre['date_debut'] ? date('Y-m-d', strtotime($semestre['date_debut'])) : '' ?>">
                        </div>

                        <div class="form-group">
                            <label>Date de fin</label>
                            <input type="date"
                                   id="date_fin"
                                   class="form-control"
                                   value="<?= $isEdit && $semestre['date_fin'] ? date('Y-m-d', strtotime($semestre['date_fin'])) : '' ?>">
                        </div>
                    </div>
                </div>

                <!-- ===================== -->
                <!-- DESCRIPTION -->
                <!-- ===================== -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-align-left"></i>
                        Description
                    </h3>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label>Description</label>
                            <textarea id="description"
                                      class="form-control"
                                      rows="4"
                                      placeholder="Description du semestre..."><?= $isEdit ? htmlspecialchars($semestre['description']) : '' ?></textarea>
                        </div>
                    </div>
                </div>

            </form>
        </div>

        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeSemestreModal()">
                <i class="fas fa-times"></i> Annuler
            </button>
            <button class="btn btn-primary" onclick="saveSemestre()">
                <i class="fas fa-save"></i> Enregistrer
            </button>
        </div>
    </div>
</div>

<script>
    // =========================================
    // SEMESTRE MODAL FUNCTIONS
    // =========================================

    let semestreModal = null;

    function openSemestreModal(data = null) {
        const modal = document.getElementById('semestreModal');
        const title = document.getElementById('modalTitle');
        const form = document.getElementById('semestreForm');

        if (data && data.id) {
            // Mode édition
            title.textContent = 'Modifier le Semestre';
            document.getElementById('semestreId').value = data.id;
            document.getElementById('libelle').value = data.libelle || '';
            document.getElementById('code').value = data.code || '';
            document.getElementById('annee_universitaire').value = data.annee_universitaire || '';
            document.getElementById('status').value = data.status || 'actif';
            document.getElementById('date_debut').value = data.date_debut || '';
            document.getElementById('date_fin').value = data.date_fin || '';
            document.getElementById('description').value = data.description || '';
        } else {
            // Mode création
            title.textContent = 'Nouveau Semestre';
            form.reset();
            document.getElementById('semestreId').value = '';
            document.getElementById('status').value = 'actif';
        }

        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    function closeSemestreModal() {
        const modal = document.getElementById('semestreModal');
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }

    async function saveSemestre() {
        const id = document.getElementById('semestreId').value;
        const data = {
            libelle: document.getElementById('libelle').value.trim(),
            code: document.getElementById('code').value.trim(),
            annee_universitaire: document.getElementById('annee_universitaire').value,
            status: document.getElementById('status').value,
            date_debut: document.getElementById('date_debut').value || null,
            date_fin: document.getElementById('date_fin').value || null,
            description: document.getElementById('description').value.trim()
        };

        // Validation
        if (!data.libelle) {
            showError('Veuillez saisir le libellé du semestre');
            return;
        }
        if (!data.code) {
            showError('Veuillez saisir le code du semestre');
            return;
        }
        if (!data.annee_universitaire) {
            showError('Veuillez sélectionner l\'année universitaire');
            return;
        }

        const method = id ? 'PUT' : 'POST';
        const url = id 
            ? `/est-concours/model/api/semestre.php?id=${id}`
            : '/est-concours/model/api/semestre.php';

        try {
            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                showSuccess(result.message);
                closeSemestreModal();
                // Rafraîchir la liste
                if (typeof loadSemestres === 'function') {
                    loadSemestres();
                }
                // Recharger la page après un délai
                setTimeout(() => location.reload(), 1500);
            } else {
                showError(result.message);
            }
        } catch (error) {
            console.error('Erreur:', error);
            showError('Une erreur est survenue lors de l\'enregistrement');
        }
    }

    // Close modal on overlay click
    document.addEventListener('DOMContentLoaded', function() {
        const modal = document.getElementById('semestreModal');
        if (modal) {
            modal.addEventListener('click', function(e) {
                if (e.target === this) {
                    closeSemestreModal();
                }
            });
        }

        // Close modal on Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeSemestreModal();
            }
        });
    });
</script>

<style>
    /* Styles spécifiques pour le modal */
    .modal-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
        align-items: center;
        justify-content: center;
        animation: fadeIn 0.3s ease;
    }

    .modal-overlay.active {
        display: flex;
    }

    .modal {
        background: white;
        border-radius: 12px;
        max-height: 90vh;
        display: flex;
        flex-direction: column;
        width: 100%;
        max-width: 800px;
        animation: slideUp 0.3s ease;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }

    .modal-lg {
        max-width: 900px;
    }

    .modal-xl {
        max-width: 1100px;
    }

    .modal-header {
        padding: 20px 25px;
        border-bottom: 1px solid #e9ecef;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-shrink: 0;
    }

    .modal-header h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #2c3e50;
    }

    .modal-header h2 i {
        color: #27ae60;
        margin-right: 10px;
    }

    .modal-close {
        background: none;
        border: none;
        font-size: 28px;
        color: #95a5a6;
        cursor: pointer;
        transition: color 0.3s ease;
        padding: 0 5px;
    }

    .modal-close:hover {
        color: #e74c3c;
    }

    .modal-body {
        padding: 25px;
        overflow-y: auto;
        flex: 1;
    }

    .modal-footer {
        padding: 15px 25px;
        border-top: 1px solid #e9ecef;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        flex-shrink: 0;
        background: #f8f9fa;
        border-radius: 0 0 12px 12px;
    }

    .form-section {
        margin-bottom: 25px;
        padding-bottom: 20px;
        border-bottom: 1px solid #f0f2f5;
    }

    .form-section:last-child {
        border-bottom: none;
        margin-bottom: 0;
        padding-bottom: 0;
    }

    .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .section-title i {
        color: #27ae60;
    }

    .form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 15px;
        margin-bottom: 15px;
    }

    .form-group {
        display: flex;
        flex-direction: column;
    }

    .form-group.full-width {
        grid-column: 1 / -1;
    }

    .form-group label {
        font-weight: 500;
        font-size: 13px;
        color: #34495e;
        margin-bottom: 5px;
    }

    .form-group label .required {
        color: #e74c3c;
        font-weight: 700;
    }

    .form-control {
        padding: 10px 12px;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.3s ease;
        font-family: 'Montserrat', sans-serif;
        background: #f8f9fa;
    }

    .form-control:focus {
        border-color: #27ae60;
        outline: none;
        box-shadow: 0 0 0 4px rgba(39, 174, 96, 0.12);
        background: white;
    }

    .form-control.is-invalid {
        border-color: #e74c3c;
        box-shadow: 0 0 0 4px rgba(231, 76, 60, 0.1);
    }

    textarea.form-control {
        resize: vertical;
        min-height: 80px;
    }

    select.form-control {
        appearance: none;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%2334495e' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: right 12px center;
        padding-right: 35px;
    }

    .form-text {
        font-size: 12px;
        color: #7f8c8d;
        margin-top: 4px;
    }

    .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        font-family: 'Montserrat', sans-serif;
    }

    .btn-primary {
        background: linear-gradient(135deg, #27ae60, #2ecc71);
        color: white;
    }

    .btn-primary:hover {
        background: linear-gradient(135deg, #1e8449, #27ae60);
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(39, 174, 96, 0.3);
    }

    .btn-secondary {
        background: #ecf0f1;
        color: #34495e;
    }

    .btn-secondary:hover {
        background: #dde1e3;
    }

    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }

    @keyframes slideUp {
        from {
            opacity: 0;
            transform: translateY(30px) scale(0.95);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }

    /* Responsive */
    @media (max-width: 768px) {
        .form-row {
            grid-template-columns: 1fr;
            gap: 10px;
        }

        .modal {
            max-width: 95%;
            margin: 10px;
        }

        .modal-body {
            padding: 15px;
        }

        .modal-header {
            padding: 15px 20px;
        }

        .modal-header h2 {
            font-size: 17px;
        }
    }

    @media (max-width: 480px) {
        .modal-footer {
            flex-direction: column;
        }

        .modal-footer .btn {
            width: 100%;
            justify-content: center;
        }
    }
</style>