<?php 
/**
 * Sante-ENS | Ultimate Aesthetic Dashboard
 * التحديث: إضافة تصدير Excel + توحيد ألوان الجداول
 */

error_reporting(0);
ini_set('display_errors', 0);

if (session_status() == PHP_SESSION_NONE) { session_start(); }
include_once('../controller/config.php');

if(!isset($_SESSION["index_number"])){
    header('location:../index.php');
    exit;
}

function getStat($conn, $query) {
    $res = mysqli_query($conn, $query);
    return ($res) ? mysqli_fetch_row($res)[0] : 0;
}

// 1. الإحصائيات العلوية
$count_std   = getStat($conn, "SELECT COUNT(nins) FROM etudiants"); 
$count_male  = getStat($conn, "SELECT COUNT(*) FROM etudiants WHERE sexe = 'MASCULIN'");
$count_female = getStat($conn, "SELECT COUNT(*) FROM etudiants WHERE sexe = 'FEMININ'");
$count_app   = getStat($conn, "SELECT COUNT(*) FROM clinic_appointments WHERE app_date = CURDATE()");

// 2. استعلام الإحصائيات التفصيلية
$sql_stats = "SELECT speId, libelle_niveau, 
              SUM(CASE WHEN sexe = 'MASCULIN' THEN 1 ELSE 0 END) as nbr_h,
              SUM(CASE WHEN sexe = 'FEMININ' THEN 1 ELSE 0 END) as nbr_f,
              COUNT(*) as total 
              FROM etudiants 
              GROUP BY speId, libelle_niveau 
              ORDER BY total DESC";
$res_stats = mysqli_query($conn, $sql_stats);

// 3. سجل الطلاب الرئيسي
$sql_all = "SELECT * FROM etudiants ORDER BY nins DESC LIMIT 50";
$res_all = mysqli_query($conn, $sql_all);
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8">
    <title>Sante-ENS | Premium Dashboard</title>
    <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="../dist/css/AdminLTE.min.css">
    <link rel="stylesheet" href="../dist/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.bootstrap.min.css">
    
    <style>
        body { font-family: 'Segoe UI', sans-serif; }
        .content-wrapper { background: #f4f7f9 !important; }
        
        /* --- سكنر RFID بتصميم "Space Modern" --- */
        .rfid-hero {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 25px; padding: 45px; margin-bottom: 30px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.05);
            border-left: 8px solid #3c8dbc; position: relative; overflow: hidden;
        }
        .rfid-hero::after {
            content: "\f21b"; font-family: FontAwesome; position: absolute;
            right: -10px; bottom: -20px; font-size: 120px; color: rgba(60, 141, 188, 0.05);
        }
        .scanner-label { font-size: 18px; font-weight: bold; color: #3c8dbc; margin-bottom: 15px; display: block; letter-spacing: 1px; }
        .scanner-input {
            height: 85px !important; font-size: 38px !important; text-align: center; 
            border-radius: 50px !important; border: 3px solid #d2d6de !important;
            background: #fff !important; color: #2c3e50; transition: 0.4s;
            box-shadow: inset 0 2px 5px rgba(0,0,0,0.02);
        }
        .scanner-input:focus {
            border-color: #3c8dbc !important; transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(60, 141, 188, 0.15) !important;
        }

        /* الأزرار */
        .btn-card {
            background: #fff; border-radius: 15px; padding: 20px; display: block;
            text-align: center; border: 1px solid #eee; transition: 0.3s; color: #444; margin-bottom: 20px;
        }
        .btn-card:hover { transform: translateY(-5px); box-shadow: 0 8px 15px rgba(0,0,0,0.08); text-decoration: none; border-color: #3c8dbc; }
        .btn-card i { font-size: 28px; display: block; margin-bottom: 8px; }

        /* الجداول */
        .premium-box { background: #fff; border-radius: 20px; padding: 25px; box-shadow: 0 5px 15px rgba(0,0,0,0.03); margin-bottom: 30px; }
        /* توحيد ألوان العناوين */
        .table thead th { background-color: #f8f9fa; color: #3c8dbc; border-bottom: 2px solid #3c8dbc !important; }
        .tag-masculin { color: #1e88e5; background: #e3f2fd; padding: 4px 12px; border-radius: 20px; font-weight: bold; font-size: 13px; }
        .tag-feminin { color: #d81b60; background: #fce4ec; padding: 4px 12px; border-radius: 20px; font-weight: bold; font-size: 13px; }
        
        /* زر إكسل مخصص */
        .btn-excel-custom { background-color: #1d6f42 !important; color: white !important; border: none !important; border-radius: 5px !important; margin-bottom: 10px; font-weight: bold; }
        .btn-excel-custom:hover { background-color: #155231 !important; }
    </style>
</head>

<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
    <?php include_once('../clinic/header_med.php'); ?>
    <?php include_once('sidebar_med.php'); ?>

    <div class="content-wrapper">
        <section class="content">

            <div class="row">
                <div class="col-md-8">
                    <div class="rfid-hero">
                        <span class="scanner-label"><i class="fa fa-rss"></i> LECTEUR RFID ACTIF</span>
                        <form action="student_view.php" method="GET">
                            <input type="text" name="nins" id="ninsInput" class="form-control scanner-input" placeholder="Scanner Badge Étudiant..." autofocus autocomplete="off">
                        </form>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="row">
                        <div class="col-md-6 col-xs-6"><a href="new_consultation.php" class="btn-card"><i class="fa fa-plus text-blue"></i><b>Fiche</b></a></div>
                        <div class="col-md-6 col-xs-6"><a href="all_students.php" class="btn-card"><i class="fa fa-users text-green"></i><b>Liste</b></a></div>
                        <div class="col-md-6 col-xs-6"><a href="pharmacy.php" class="btn-card"><i class="fa fa-medkit text-red"></i><b>Pharm</b></a></div>
                        <div class="col-md-6 col-xs-6"><a href="reports.php" class="btn-card"><i class="fa fa-file-text text-orange"></i><b>Stats</b></a></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-3"><div class="info-box"><span class="info-box-icon bg-blue"><i class="fa fa-users"></i></span><div class="info-box-content"><span>Total Étudiants</span><span class="info-box-number"><?= $count_std ?></span></div></div></div>
                <div class="col-md-3"><div class="info-box"><span class="info-box-icon bg-aqua"><i class="fa fa-male"></i></span><div class="info-box-content"><span>MASCULIN</span><span class="info-box-number"><?= $count_male ?></span></div></div></div>
                <div class="col-md-3"><div class="info-box"><span class="info-box-icon bg-maroon"><i class="fa fa-female"></i></span><div class="info-box-content"><span>FEMININ</span><span class="info-box-number"><?= $count_female ?></span></div></div></div>
                <div class="col-md-3"><div class="info-box"><span class="info-box-icon bg-green"><i class="fa fa-calendar-check-o"></i></span><div class="info-box-content"><span>Aujourd'hui</span><span class="info-box-number"><?= $count_app ?></span></div></div></div>
            </div>

            <div class="row">
                <div class="col-md-12">
                    <div class="premium-box" style="border-top: 4px solid #3c8dbc;">
                        <h4 class="text-blue"><i class="fa fa-clock-o"></i> <b>Registre des Inscriptions Récentes</b></h4>
                        <hr>
                        <table id="mainRegisterTable" class="table table-hover">
                            <thead>
                                <tr>
                                    <th>NINS</th>
                                    <th>Nom & Prénom</th>
                                    <th>Spécialité</th>
                                    <th>Niveau</th>
                                    <th>Téléphone</th>
                                    <th>Adresse</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($row = mysqli_fetch_assoc($res_all)): ?>
                                <tr>
                                    <td><b><?= $row['nins'] ?></b></td>
                                    <td><?= $row['nom'] ?> <?= $row['prenom'] ?></td>
                                    <td><?= $row['speId'] ?></td>
                                    <td><span class="label label-primary"><?= $row['libelle_niveau'] ?></span></td>
                                    <td><?= $row['tel'] ?></td>
                                    <td><small class="text-muted"><?= $row['adr'] ?></small></td>
                                    <td><a href="student_view.php?nins=<?= $row['nins'] ?>" class="btn btn-xs btn-primary">Dossier</a></td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-12">
                    <div class="premium-box" style="border-top: 4px solid #f39c12;">
                        <h4 class="text-orange"><i class="fa fa-bar-chart"></i> <b>Répartition Analytique (MASCULIN / FEMININ)</b></h4>
                        <table id="statsTable" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Spécialité</th>
                                    <th>Niveau</th>
                                    <th class="text-center">👨 MASCULIN</th>
                                    <th class="text-center">👩 FEMININ</th>
                                    <th class="text-center" style="background:#eee">TOTAL</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($st = mysqli_fetch_assoc($res_stats)): ?>
                                <tr>
                                    <td><b><?= $st['speId'] ?></b></td>
                                    <td><?= $st['libelle_niveau'] ?></td>
                                    <td class="text-center"><span class="tag-masculin"><?= $st['nbr_h'] ?></span></td>
                                    <td class="text-center"><span class="tag-feminin"><?= $st['nbr_f'] ?></span></td>
                                    <td class="text-center" style="font-weight:bold"><?= $st['total'] ?></td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </section>
    </div>
</div>

<script src="../plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="../bootstrap/js/bootstrap.min.js"></script>

<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>

<script>
    $(document).ready(function() {
        $('#mainRegisterTable').DataTable({
            "pageLength": 10,
            "language": { "url": "//cdn.datatables.net/plug-ins/1.10.21/i18n/French.json" }
        });

        $('#statsTable').DataTable({
            "pageLength": 5,
            "dom": 'Bfrtip',
            "buttons": [
                {
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i> Exporter vers Excel',
                    className: 'btn-excel-custom',
                    title: 'Statistiques_Etudiants_Sante_ENS'
                }
            ],
            "language": {
                "search": "<b>Recherche Rapide:</b> ",
                "url": "//cdn.datatables.net/plug-ins/1.10.21/i18n/French.json"
            }
        });

        $('#ninsInput').focus();
        $('body').click(function() { $('#ninsInput').focus(); });
    });
</script>
</body>
</html>