<?php
require_once "includes/dbconn.php";
include "includes/header.php";

// Infos de l’école
$school_name = "ECOLE SINE SALOUM SANTE (E3S)";
$school_phone = "+221 33 941 00 08";
$school_email = "giesinesaloum@gmail.com";
$school_logo = "images/logo.png";

// Fonction pour calculer les mois à payer non réglés (inchangée)
function get_months_to_pay($start_date, $paid_months) {
    $months = [];
    $start = new DateTime($start_date);
    $now = new DateTime();

    while ($start <= $now) {
        $month_str = $start->format('m/Y');
        if (!in_array($month_str, $paid_months)) {
            $months[] = $month_str;
        }
        $start->modify('+1 month');
    }
    return $months;
}

// Requête SQL inchangée
$sql = "
SELECT e.id, e.noms, e.prenom, e.matricule, e.phone, e.date_creation, c.nom AS classe,
    (
        PERIOD_DIFF(DATE_FORMAT(NOW(), '%Y%m'), DATE_FORMAT(e.date_creation, '%Y%m')) + 1
        - IFNULL(COUNT(m.id), 0)
    ) AS mois_impayes
FROM etudiants e
JOIN classes c ON e.classe_id = c.id
LEFT JOIN mensualites m ON m.etudiant_id = e.id
GROUP BY e.id
HAVING mois_impayes > 0
ORDER BY mois_impayes DESC
";
$res = $conn->query($sql);
?>

<style>
    .bg-primary-teal {
        background-color: #008080 !important;
    }
    .bg-secondary-teal {
        background-color: #20B2AA !important;
    }
    .text-teal {
        color: #008080 !important;
    }
    .btn-teal {
        background-color: #008080;
        color: white;
        border-color: #008080;
    }
    .btn-teal:hover {
        background-color: #006666;
        border-color: #006666;
    }
    .btn-outline-teal {
        color: #008080;
        border-color: #008080;
    }
    .btn-outline-teal:hover {
        background-color: #008080;
        color: white;
    }
    .badge-teal {
        background-color: #20B2AA;
        color: white;
    }
    .table-teal thead th {
        background-color: #008080;
        color: white;
    }
    .border-teal {
        border-color: #008080 !important;
    }
</style>

<div class="container-fluid mt-4">
    <div class="card border-teal">
        <div class="card-header bg-primary-teal text-white">
            <div class="d-flex justify-content-between align-items-center">
                <h3 class="mb-0"><i class="bi bi-exclamation-triangle-fill"></i> Étudiants avec des mois impayés</h3>
                <div class="input-group" style="width: 300px;">
                    <input type="text" id="searchInput" class="form-control" placeholder="Filtrer...">
                    <button class="btn btn-light" type="button" id="clearSearch">
                        <i class="bi bi-x-lg"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0 table-teal" id="studentsTable">
                    <thead>
                        <tr>
                            <th class="text-nowrap">Matricule</th>
                            <th class="text-nowrap">Nom complet</th>
                            <th class="text-nowrap">Téléphone</th>
                            <th class="text-nowrap">Classe</th>
                            <th class="text-nowrap">Date d'inscription</th>
                            <th class="text-nowrap">Mois impayés</th>
                            <th class="text-nowrap">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php while ($row = $res->fetch_assoc()):
                        $etudiant_id = $row['id'];
                        // Obtenir les mois payés (inchangé)
                        $paid = [];
                        $res_m = $conn->query("SELECT mois, date_paiement FROM mensualites WHERE etudiant_id = $etudiant_id");
                        while ($m = $res_m->fetch_assoc()) {
                            $paid[] = sprintf("%02d/%d", $m['mois'], $m['date_paiement']);
                        }
                        $mois_restants = get_months_to_pay($row['date_creation'], $paid);
                        $text_mois = implode(', ', $mois_restants);
                        $full_name = $row['noms'] . ' ' . $row['prenom'];
                        $objet = "Mise en demeure pour non-paiement de frais";

                        // Message WhatsApp pré-rempli (inchangé)
                        $msg = "Bonjour $full_name,\n\nNous constatons un retard dans le paiement de vos frais pour les mois suivants : $text_mois.\nMerci de régulariser votre situation rapidement auprès de l'administration de $school_name.\n\nContact : $school_phone.";
                        $phone_clean = preg_replace('/\D/', '', $row['phone']);
                        $wa_link = "https://wa.me/$phone_clean?text=" . urlencode($msg);
                    ?>
                        <tr data-search="<?= strtolower(htmlspecialchars($row['matricule'] . ' ' . $full_name . ' ' . $row['classe'])) ?>">
                            <td><?= htmlspecialchars($row['matricule']) ?></td>
                            <td><?= htmlspecialchars($full_name) ?></td>
                            <td><?= htmlspecialchars($row['phone']) ?></td>
                            <td><?= htmlspecialchars($row['classe']) ?></td>
                            <td><?= date('d/m/Y', strtotime($row['date_creation'])) ?></td>
                            <td>
                                <span class="badge rounded-pill badge-teal">
                                    <?= $row['mois_impayes'] ?> mois
                                </span>
                            </td>
                            <td class="text-nowrap">
                                <button class="btn btn-sm btn-outline-teal" data-bs-toggle="modal" data-bs-target="#modal<?= $etudiant_id ?>">
                                    <i class="bi bi-envelope-exclamation"></i> Mise en demeure
                                </button>
                            </td>
                        </tr>

                        <!-- Modal (inchangé) -->
                        <div class="modal fade" id="modal<?= $etudiant_id ?>" tabindex="-1" aria-hidden="true">
                          <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                              <div class="modal-header bg-primary-teal text-white">
                                <h5 class="modal-title"><?= htmlspecialchars($objet) ?></h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
                              </div>
                              <div class="modal-body" id="modalContent<?= $etudiant_id ?>">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <div>
                                       <img src="assetss/logo.jpeg" alt="Logo" width="100" />
                                        <h5 class="text-teal"><?= htmlspecialchars($school_name) ?></h5>
                                        <p>Email : <?= htmlspecialchars($school_email) ?><br>Tél : <?= htmlspecialchars($school_phone) ?></p>
                                    </div>
                                </div>
                                <hr>
                                <h6 class="text-teal">À : <?= htmlspecialchars($full_name) ?></h6>
                                <p>Matricule : <?= htmlspecialchars($row['matricule']) ?><br>Classe : <?= htmlspecialchars($row['classe']) ?></p>
                                <p>Objet : <strong class="text-teal"><?= htmlspecialchars($objet) ?></strong></p>
                                <p>
                                    Cher étudiant(e),<br>
                                    Nous vous informons que vous avez un retard de paiement pour les mois suivants : <strong class="text-teal"><?= htmlspecialchars($text_mois) ?></strong>.<br>
                                    Conformément au règlement intérieur, nous vous prions de bien vouloir régulariser votre situation au plus vite.<br>
                                    Pour tout renseignement, contactez l'administration.
                                </p>
                                <p>Cordialement,<br>L'administration <?= htmlspecialchars($school_name) ?>.</p>
                              </div>
                              <div class="modal-footer">
                                <a href="<?= $wa_link ?>" target="_blank" class="btn btn-success">
                                    <i class="bi bi-whatsapp"></i> WhatsApp
                                </a>
                                <button class="btn btn-secondary" onclick="printModal('modalContent<?= $etudiant_id ?>')">
                                    <i class="bi bi-printer"></i> Imprimer
                                </button>
                                <button type="button" class="btn btn-outline-teal" data-bs-dismiss="modal">Fermer</button>
                              </div>
                            </div>
                          </div>
                        </div>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="card-footer bg-light">
            <small class="text-muted"><?= date('d/m/Y H:i') ?> - <?= $res->num_rows ?> étudiants en retard</small>
        </div>
    </div>
</div>

<script>
// Fonction d'impression inchangée
function printModal(divId) {
    const content = document.getElementById(divId).innerHTML;
    const myWindow = window.open('', 'PRINT', 'width=800,height=600');
    myWindow.document.write(`
      <html>
      <head>
        <title>Mise en demeure</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
          body { padding: 20px; font-family: Arial, sans-serif; }
          .text-teal { color: #008080; }
        </style>
      </head>
      <body>${content}</body>
      </html>
    `);
    myWindow.document.close();
    myWindow.focus();
    myWindow.print();
    myWindow.close();
}

// Filtrage côté client
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    const clearSearch = document.getElementById('clearSearch');
    const rows = document.querySelectorAll('#studentsTable tbody tr');
    
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        
        rows.forEach(row => {
            const searchData = row.getAttribute('data-search');
            if (searchData.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    });
    
    clearSearch.addEventListener('click', function() {
        searchInput.value = '';
        rows.forEach(row => row.style.display = '');
    });
});
</script>

<?php include "includes/footer.php"; ?>