<?php
session_start();
require_once 'config.php';
require_once 'function.php';

if (!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['super_admin', 'admin'])) {
    header('Location: login.php');
    exit();
}

$current_user = getCurrentUserInfo($pdo);
$message = '';
$message_absence = '';

// Traitement AJOUT enseignant
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    if ($_POST['action'] == 'ajouter_enseignant') {
        try {
            $check = $pdo->prepare("SELECT id_enseignant FROM enseignant WHERE id_enseignant = ?");
            $check->execute([$_POST['id_enseignant']]);
            if ($check->rowCount() > 0) {
                $message = '<div class="alert-error">Cet ID enseignant existe déjà !</div>';
            } else {
                $login = $_POST['id_enseignant'];
                $mot_de_passe = 'enseignant123';
                
                $sql_user = "INSERT INTO utilisateur (nom, prenom, email, login, mot_de_passe, role, etat_compte) 
                            VALUES (:nom, :prenom, '', :login, :mot_de_passe, 'enseignant', 'actif')";
                $stmt_user = $pdo->prepare($sql_user);
                $stmt_user->execute([
                    ':nom' => $_POST['nom'],
                    ':prenom' => $_POST['prenom'],
                    ':login' => $login,
                    ':mot_de_passe' => $mot_de_passe
                ]);
                
                $id_user = $pdo->lastInsertId();
                
                $sql = "INSERT INTO enseignant (id_enseignant, id_user, nom, prenom, specialite, telephone) 
                        VALUES (:id_enseignant, :id_user, :nom, :prenom, :specialite, :telephone)";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    ':id_enseignant' => $_POST['id_enseignant'],
                    ':id_user' => $id_user,
                    ':nom' => $_POST['nom'],
                    ':prenom' => $_POST['prenom'],
                    ':specialite' => $_POST['specialite'],
                    ':telephone' => $_POST['telephone']
                ]);
                
                $message = '<div class="alert-success">Enseignant ajouté! Login: ' . $login . ', Mot de passe: enseignant123</div>';
            }
        } catch(PDOException $e) {
            $message = '<div class="alert-error">Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    if ($_POST['action'] == 'supprimer_enseignant' && isset($_POST['id_enseignant'])) {
        try {
            $stmt = $pdo->prepare("SELECT id_user FROM enseignant WHERE id_enseignant = ?");
            $stmt->execute([$_POST['id_enseignant']]);
            $enseignant = $stmt->fetch();
            
            if ($enseignant && !empty($enseignant['id_user'])) {
                $pdo->prepare("DELETE FROM absence_enseignant WHERE id_enseignant = ?")->execute([$_POST['id_enseignant']]);
                $pdo->prepare("DELETE FROM seance WHERE id_enseignant = ?")->execute([$_POST['id_enseignant']]);
                $pdo->prepare("DELETE FROM enseignant WHERE id_enseignant = ?")->execute([$_POST['id_enseignant']]);
                $pdo->prepare("DELETE FROM utilisateur WHERE id_user = ?")->execute([$enseignant['id_user']]);
            }
            $message = '<div class="alert-success">Enseignant supprimé!</div>';
        } catch(PDOException $e) {
            $message = '<div class="alert-error">Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    if ($_POST['action'] == 'modifier_enseignant' && isset($_POST['id_enseignant'])) {
        try {
            $sql = "UPDATE enseignant SET nom=:nom, prenom=:prenom, telephone=:telephone, specialite=:specialite 
                    WHERE id_enseignant=:id_enseignant";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':nom' => $_POST['nom'], ':prenom' => $_POST['prenom'],
                ':telephone' => $_POST['telephone'], ':specialite' => $_POST['specialite'],
                ':id_enseignant' => $_POST['id_enseignant']
            ]);
            
            if (!empty($_POST['id_user'])) {
                $sql_user = "UPDATE utilisateur SET nom=:nom, prenom=:prenom WHERE id_user=:id_user";
                $stmt_user = $pdo->prepare($sql_user);
                $stmt_user->execute([':nom' => $_POST['nom'], ':prenom' => $_POST['prenom'], ':id_user' => $_POST['id_user']]);
            }
            
            $message = '<div class="alert-success">✅ Enseignant modifié!</div>';
            echo '<meta http-equiv="refresh" content="2">';
        } catch(PDOException $e) {
            $message = '<div class="alert-error">❌ Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    // Absences
    if ($_POST['action'] == 'ajouter_absence_enseignant') {
        try {
            $check = $pdo->prepare("SELECT id_enseignant FROM enseignant WHERE id_enseignant = ?");
            $check->execute([$_POST['id_enseignant']]);
            if ($check->rowCount() == 0) {
                $message_absence = '<div class="alert-error">Enseignant inexistant!</div>';
            } else {
                $check_absence = $pdo->prepare("SELECT id_absence FROM absence_enseignant WHERE id_enseignant = ? AND id_seance = ?");
                $check_absence->execute([$_POST['id_enseignant'], $_POST['id_seance']]);
                if ($check_absence->rowCount() > 0) {
                    $message_absence = '<div class="alert-error">Absence déjà enregistrée!</div>';
                } else {
                    $date_absence = strtotime($_POST['date_absence']);
                    $sql = "INSERT INTO absence_enseignant (id_enseignant, id_seance, date_absence) VALUES (?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$_POST['id_enseignant'], $_POST['id_seance'], $date_absence]);
                    $message_absence = '<div class="alert-success">Absence enregistrée!</div>';
                }
            }
        } catch(PDOException $e) {
            $message_absence = '<div class="alert-error">Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    if ($_POST['action'] == 'supprimer_absence_enseignant' && isset($_POST['id_absence'])) {
        try {
            $pdo->prepare("DELETE FROM absence_enseignant WHERE id_absence = ?")->execute([$_POST['id_absence']]);
            $message_absence = '<div class="alert-success">Absence supprimée!</div>';
        } catch(PDOException $e) {
            $message_absence = '<div class="alert-error">Erreur : ' . $e->getMessage() . '</div>';
        }
    }
}

// Récupérer les données
$enseignants = [];
try {
    $stmt = $pdo->query("SELECT * FROM enseignant ORDER BY id_enseignant DESC");
    $enseignants = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

$seances = [];
try {
    $sql = "SELECT s.*, m.nom_matiere, g.nom_groupe 
            FROM seance s
            LEFT JOIN matieres m ON s.id_matiere = m.id_matiere
            LEFT JOIN groupe g ON s.id_groupe = g.id_groupe
            ORDER BY s.jour, s.heure_debut";
    $stmt = $pdo->query($sql);
    $seances = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

$absences_enseignant = [];
try {
    $sql = "SELECT a.*, e.nom as nom_enseignant, e.prenom as prenom_enseignant,
                   s.jour, s.heure_debut, s.heure_fin, m.nom_matiere, g.nom_groupe
            FROM absence_enseignant a
            LEFT JOIN enseignant e ON a.id_enseignant = e.id_enseignant
            LEFT JOIN seance s ON a.id_seance = s.id_seance
            LEFT JOIN matieres m ON s.id_matiere = m.id_matiere
            LEFT JOIN groupe g ON s.id_groupe = g.id_groupe
            ORDER BY a.date_absence DESC";
    $stmt = $pdo->query($sql);
    $absences_enseignant = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Gestion Enseignants | CPN</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap');
        
        body { background: #eff0f1; }
        header {
            background: linear-gradient(135deg, #ffffff 0%, #2f6d8c 40%, #29546d 70%, #0a3144 100%);
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo { width: 150px; }
        .back-btn { background: #0a3144; color: white; padding: 8px 20px; text-decoration: none; border-radius: 8px; }
        .container { padding: 30px; }
        .card { background: white; padding: 25px; border-radius: 16px; margin-bottom: 30px; }
        .header-actions { display: flex; justify-content: space-between; margin-bottom: 20px; flex-wrap: wrap; gap: 15px; }
        .btn-ajouter { background: #1e6f9f; color: white; border: none; padding: 12px 22px; border-radius: 10px; cursor: pointer; }
        .btn-success { background: #28a745; }
        .btn-danger { background: #dc3545; }
        .btn-modifier { background: #ffc107; color: #000; }
        .btn-supprimer { background: #dc3545; color: white; }
        .btn-action { padding: 5px 10px; margin: 0 2px; border: none; border-radius: 5px; cursor: pointer; }
        
        table { width: 100%; border-collapse: collapse; background: white; border-radius: 16px; overflow: hidden; }
        table th { background: #0a3144; color: white; padding: 12px; }
        table td { padding: 10px; text-align: center; border-bottom: 1px solid #eee; }
        
        .form-container { background: white; padding: 25px; border-radius: 16px; margin-bottom: 25px; display: none; border: 2px solid #6ab0e6; }
        .form-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; }
        .form-grid input, .form-grid select { padding: 10px; border: 2px solid #e9ecef; border-radius: 8px; width: 100%; }
        .full-width { grid-column: span 2; }
        .form-buttons { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
        
        .alert-success { background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 5px solid #28a745; }
        .alert-error { background: #f8d7da; color: #721c24; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 5px solid #dc3545; }
        
        .badge { padding: 5px 10px; border-radius: 20px; font-size: 12px; display: inline-block; }
        .tab-buttons { display: flex; gap: 10px; margin-bottom: 20px; }
        .tab-button { padding: 10px 20px; background: #f0f0f0; border: none; border-radius: 8px; cursor: pointer; }
        .tab-button.active { background: #1e6f9f; color: white; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        
        @media(max-width: 768px) { .form-grid { grid-template-columns: 1fr; } .full-width { grid-column: span 1; } }
    </style>
</head>
<body>
    <header>
        <img src="logo.png" alt="Logo" class="logo" onerror="this.style.display='none'">
        <h1>👨‍🏫 Gestion des Enseignants</h1>
        <a href="admin.php" class="back-btn">← Retour</a>
    </header>
    
    <div class="container">
        <?php echo $message; ?>
        <?php echo $message_absence; ?>
        
        <div class="card">
            <div class="header-actions">
                <h2>Gestion</h2>
                <div>
                    <button class="btn-ajouter" onclick="toggleFormulaire('enseignant')">+ Ajouter Enseignant</button>
                    <button class="btn-ajouter btn-success" onclick="toggleFormulaire('absence')">📋 Enregistrer Absence</button>
                </div>
            </div>
            
            <!-- Formulaire ajout enseignant -->
            <div id="formulaireEnseignant" class="form-container">
                <h3>Nouvel Enseignant</h3>
                <form method="POST">
                    <input type="hidden" name="action" value="ajouter_enseignant">
                    <div class="form-grid">
                        <input type="text" name="id_enseignant" placeholder="ID Enseignant" required>
                        <input type="text" name="nom" placeholder="Nom" required>
                        <input type="text" name="prenom" placeholder="Prénom" required>
                        <input type="tel" name="telephone" placeholder="Téléphone" required>
                        <input type="text" name="specialite" placeholder="Spécialité" class="full-width" required>
                    </div>
                    <div class="form-buttons">
                        <button type="submit" class="btn-ajouter btn-success">Enregistrer</button>
                        <button type="button" class="btn-ajouter btn-danger" onclick="toggleFormulaire('enseignant')">Annuler</button>
                    </div>
                </form>
            </div>
            
            <!-- Formulaire absence -->
            <div id="formulaireAbsence" class="form-container">
                <h3>Enregistrer une absence</h3>
                <form method="POST">
                    <input type="hidden" name="action" value="ajouter_absence_enseignant">
                    <div class="form-grid">
                        <select name="id_enseignant" required>
                            <option value="">Sélectionner enseignant</option>
                            <?php foreach ($enseignants as $ens): ?>
                                <option value="<?php echo $ens['id_enseignant']; ?>"><?php echo htmlspecialchars($ens['nom'] . ' ' . $ens['prenom']); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name="id_seance" required>
                            <option value="">Sélectionner séance</option>
                            <?php foreach ($seances as $seance): ?>
                                <option value="<?php echo $seance['id_seance']; ?>">
                                    <?php echo htmlspecialchars(($seance['nom_matiere'] ?? '?') . ' - ' . ($seance['jour'] ?? '') . ' ' . ($seance['heure_debut'] ?? '') . '-' . ($seance['heure_fin'] ?? '')); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <input type="date" name="date_absence" value="<?php echo date('Y-m-d'); ?>" class="full-width" required>
                    </div>
                    <div class="form-buttons">
                        <button type="submit" class="btn-ajouter btn-success">Enregistrer</button>
                        <button type="button" class="btn-ajouter btn-danger" onclick="toggleFormulaire('absence')">Annuler</button>
                    </div>
                </form>
            </div>
            
            <!-- Onglets -->
            <div class="tab-buttons">
                <button class="tab-button active" onclick="showTab('liste')">📋 Liste des enseignants</button>
                <button class="tab-button" onclick="showTab('absences')">📊 Historique des absences</button>
            </div>
            
            <!-- Liste enseignants -->
            <div id="tab-liste" class="tab-content active">
                <table>
                    <thead>
                        <tr><th>ID</th><th>Nom</th><th>Prénom</th><th>Téléphone</th><th>Spécialité</th><th>Absences</th><th>Actions</th>
                    </thead>
                    <tbody>
                        <?php foreach ($enseignants as $ens): 
                            $nb_abs = 0;
                            foreach ($absences_enseignant as $abs) if ($abs['id_enseignant'] == $ens['id_enseignant']) $nb_abs++;
                        ?>
                        <tr>
                            <td><?php echo htmlspecialchars($ens['id_enseignant']); ?></td>
                            <td><?php echo htmlspecialchars($ens['nom']); ?></td>
                            <td><?php echo htmlspecialchars($ens['prenom']); ?></td>
                            <td><?php echo htmlspecialchars($ens['telephone']); ?></td>
                            <td><?php echo htmlspecialchars($ens['specialite']); ?></td>
                            <td><?php echo $nb_abs; ?></td>
                            <td>
                                <button class="btn-action btn-modifier" onclick="ouvrirModal(<?php echo htmlspecialchars(json_encode($ens)); ?>)">✏️</button>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="action" value="supprimer_enseignant">
                                    <input type="hidden" name="id_enseignant" value="<?php echo $ens['id_enseignant']; ?>">
                                    <button type="submit" class="btn-action btn-supprimer" onclick="return confirm('Supprimer ?')">🗑️</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Liste absences -->
            <div id="tab-absences" class="tab-content">
                <table>
                    <thead>
                        <tr><th>Date</th><th>Enseignant</th><th>Matière</th><th>Groupe</th><th>Horaire</th><th>Action</th>
                    </thead>
                    <tbody>
                        <?php foreach ($absences_enseignant as $abs): ?>
                        <tr>
                            <td><?php echo date('d/m/Y', $abs['date_absence']); ?></td>
                            <td><?php echo htmlspecialchars(($abs['nom_enseignant'] ?? '') . ' ' . ($abs['prenom_enseignant'] ?? '')); ?></td>
                            <td><?php echo htmlspecialchars($abs['nom_matiere'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($abs['nom_groupe'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars(($abs['heure_debut'] ?? '') . '-' . ($abs['heure_fin'] ?? '')); ?></td>
                            <td>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="action" value="supprimer_absence_enseignant">
                                    <input type="hidden" name="id_absence" value="<?php echo $abs['id_absence']; ?>">
                                    <button type="submit" class="btn-action btn-supprimer" onclick="return confirm('Supprimer ?')">🗑️</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Modal modification -->
    <div id="modalEnseignant" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000;">
        <div style="background:white; width:90%; max-width:500px; margin:50px auto; padding:30px; border-radius:15px;">
            <h3>✏️ Modifier l'enseignant</h3>
            <form method="POST">
                <input type="hidden" name="action" value="modifier_enseignant">
                <input type="hidden" name="id_enseignant" id="edit_id">
                <input type="hidden" name="id_user" id="edit_id_user">
                <div class="form-grid">
                    <input type="text" name="nom" id="edit_nom" placeholder="Nom" required>
                    <input type="text" name="prenom" id="edit_prenom" placeholder="Prénom" required>
                    <input type="tel" name="telephone" id="edit_tel" placeholder="Téléphone" required>
                    <input type="text" name="specialite" id="edit_specialite" placeholder="Spécialité" class="full-width" required>
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn-ajouter btn-success">Enregistrer</button>
                    <button type="button" class="btn-ajouter btn-danger" onclick="fermerModal()">Annuler</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function toggleFormulaire(type) {
            let id = type === 'enseignant' ? 'formulaireEnseignant' : 'formulaireAbsence';
            let form = document.getElementById(id);
            if (form) form.style.display = form.style.display === 'none' ? 'block' : 'none';
        }
        
        function showTab(tab) {
            document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-button').forEach(b => b.classList.remove('active'));
            document.getElementById('tab-' + tab).classList.add('active');
            event.target.classList.add('active');
        }
        
        function ouvrirModal(e) {
            document.getElementById('edit_id').value = e.id_enseignant;
            document.getElementById('edit_id_user').value = e.id_user || '';
            document.getElementById('edit_nom').value = e.nom;
            document.getElementById('edit_prenom').value = e.prenom;
            document.getElementById('edit_tel').value = e.telephone;
            document.getElementById('edit_specialite').value = e.specialite;
            document.getElementById('modalEnseignant').style.display = 'block';
        }
        
        function fermerModal() {
            document.getElementById('modalEnseignant').style.display = 'none';
        }
        
        window.onclick = function(e) {
            if (e.target == document.getElementById('modalEnseignant')) fermerModal();
        }
    </script>
</body>
</html>