<?php
session_start();
include 'db.php';

if (!isset($_SESSION['admin_id'])) { header("Location: admin_login.php"); exit(); }
$admin_username = isset($_SESSION['admin_username']) ? $_SESSION['admin_username'] : 'أدمن';
if ($admin_username === 'alawael0') { session_unset(); session_destroy(); header("Location: admin_login.php"); exit(); }

function h($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

mysqli_set_charset($conn, "utf8mb4");

$stage = isset($_GET['stage']) ? trim($_GET['stage']) : '';
$class = isset($_GET['class']) ? trim($_GET['class']) : '';
$from  = isset($_GET['from']) ? trim($_GET['from']) : date("Y-m-01");
$to    = isset($_GET['to']) ? trim($_GET['to']) : date("Y-m-d");

$stages = array();
$res = mysqli_query($conn, "SELECT DISTINCT stage FROM students ORDER BY stage ASC");
while ($r = mysqli_fetch_assoc($res)) { $stages[] = $r['stage']; }

$classes = array();
if ($stage !== '') {
  $st = mysqli_real_escape_string($conn, $stage);
  $res2 = mysqli_query($conn, "SELECT DISTINCT class FROM students WHERE stage='$st' ORDER BY class ASC");
  while ($r = mysqli_fetch_assoc($res2)) { $classes[] = $r['class']; }
}

$rows = array();
if ($stage !== '' && $class !== '') {
  $st = mysqli_real_escape_string($conn, $stage);
  $cl = mysqli_real_escape_string($conn, $class);
  $f  = mysqli_real_escape_string($conn, $from);
  $t  = mysqli_real_escape_string($conn, $to);

  $sql = "
    SELECT s.id, s.name,
      SUM(CASE WHEN a.status='absent' THEN 1 ELSE 0 END) AS absent_days,
      SUM(CASE WHEN a.status='late' THEN 1 ELSE 0 END) AS late_days,
      SUM(CASE WHEN a.status='present' THEN 1 ELSE 0 END) AS present_days,
      SUM(CASE WHEN a.status='excused' THEN 1 ELSE 0 END) AS excused_days
    FROM students s
    LEFT JOIN attendance_daily a
      ON a.student_id = s.id
     AND a.att_date BETWEEN '$f' AND '$t'
    WHERE s.stage='$st' AND s.class='$cl'
    GROUP BY s.id
    ORDER BY absent_days DESC, late_days DESC, s.name ASC
  ";
  $res3 = mysqli_query($conn, $sql);
  while ($r = mysqli_fetch_assoc($res3)) { $rows[] = $r; }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>📈 إحصائيات الغياب | ثانوية الأوائل الأهلية للبنين</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;600;700&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{
  font-family:'Tajawal',sans-serif;
  min-height:100vh;
  background:radial-gradient(circle at 20% 20%,#1a1f3b,#0b0d18 80%);
  color:#fff; overflow-x:hidden;
}
body::before{
  content:""; position:fixed; top:-50%; left:-50%; width:200%; height:200%;
  background:
    radial-gradient(circle at 30% 30%,rgba(0,255,255,0.2),transparent 70%),
    radial-gradient(circle at 70% 70%,rgba(255,215,0,0.2),transparent 80%),
    radial-gradient(circle at 50% 100%,rgba(138,43,226,0.15),transparent 60%);
  animation:nebula 25s linear infinite alternate; filter:blur(90px); z-index:-1;
}
@keyframes nebula{0%{transform:rotate(0deg) scale(1)}100%{transform:rotate(360deg) scale(1.2)}}
header{
  display:flex; align-items:center; justify-content:space-between;
  padding:18px 25px; background:rgba(255,255,255,0.07);
  border-bottom:1px solid rgba(255,255,255,0.12);
  backdrop-filter:blur(10px);
  box-shadow:0 2px 12px rgba(0,255,255,0.1);
  position:sticky; top:0; z-index:10;
}
header .left{display:flex;align-items:center;gap:12px}
header img{height:45px;border-radius:50%;box-shadow:0 0 10px rgba(0,255,255,0.3)}
header h1{font-size:18px;font-weight:700;margin:0}
header .user{font-size:13px;color:#0ff;opacity:0.85}
header .btn{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  color:#fff;padding:9px 18px;border-radius:10px;
  text-decoration:none;font-weight:bold;transition:0.3s; display:inline-block;
}
header .btn:hover{transform:scale(1.05);box-shadow:0 0 15px rgba(0,255,255,0.4)}
.container{max-width:1200px;margin:20px auto 60px;padding:0 20px}
.hero{text-align:center;margin:24px 0 12px}
.hero h2{font-size:26px;color:#00e6ff;text-shadow:0 0 15px rgba(0,255,255,0.4)}
.hero p{color:#ddd;margin-top:8px;line-height:1.7}
.panel{
  background:rgba(255,255,255,0.08);
  border:1px solid rgba(255,255,255,0.12);
  border-radius:22px; padding:16px; box-shadow:0 0 20px rgba(0,255,255,0.08);
}
.row{display:flex;gap:12px;flex-wrap:wrap;align-items:center}
.select, .input{
  background:rgba(0,0,0,0.25); color:#fff;
  border:1px solid rgba(255,255,255,0.18);
  border-radius:12px; padding:10px 12px; min-width:220px;
  outline:none;
}
.tableWrap{margin-top:14px;overflow:auto}
table{width:100%;border-collapse:separate;border-spacing:0 10px;min-width:900px}
td,th{padding:12px 12px;text-align:center}
th{color:#00e6ff}
tr{background:rgba(0,0,0,0.18);border:1px solid rgba(255,255,255,0.12)}
tr td:first-child, tr th:first-child{border-top-right-radius:14px;border-bottom-right-radius:14px}
tr td:last-child, tr th:last-child{border-top-left-radius:14px;border-bottom-left-radius:14px}
.badge{padding:6px 10px;border-radius:999px;font-size:12px;font-weight:900;border:1px solid rgba(255,255,255,0.15)}
.a{background:rgba(255,80,80,0.12);color:#ffb3b3}
.l{background:rgba(255,215,0,0.12);color:#ffe28a}
.p{background:rgba(0,255,120,0.12);color:#6fffb0}
.e{background:rgba(120,180,255,0.14);color:#b9dcff}
</style>
</head>
<body>

<header>
  <div class="left">
    <img src="logo.png" alt="logo">
    <div>
      <h1>إحصائيات الغياب</h1>
      <div class="user">مرحباً، <?php echo h($admin_username); ?></div>
    </div>
  </div>
  <div style="display:flex; gap:10px; flex-wrap:wrap;">
    <a href="admin_dashboard.php" class="btn">لوحة التحكم</a>
    <a href="admin_attendance_manage.php" class="btn">إدارة الحضور</a>
    <a href="admin_logout.php" class="btn">تسجيل خروج</a>
  </div>
</header>

<div class="container">
  <div class="hero">
    <h2>📈 عدد غياب كل طالب</h2>
    <p>اختر المرحلة والشعبة وحدد فترة زمنية، وسيظهر لك مجموع الغياب والتأخير والحضور.</p>
  </div>

  <div class="panel">
    <form method="get" class="row">
      <select name="stage" class="select" onchange="this.form.submit()">
        <option value="">اختر المرحلة</option>
        <?php foreach($stages as $stg): ?>
          <option value="<?php echo h($stg); ?>" <?php echo ($stage===$stg?'selected':''); ?>><?php echo h($stg); ?></option>
        <?php endforeach; ?>
      </select>

      <select name="class" class="select" <?php echo ($stage===''?'disabled':''); ?> onchange="this.form.submit()">
        <option value=""><?php echo ($stage===''?'اختر المرحلة أولاً':'اختر الشعبة'); ?></option>
        <?php foreach($classes as $cl): ?>
          <option value="<?php echo h($cl); ?>" <?php echo ($class===$cl?'selected':''); ?>><?php echo h($cl); ?></option>
        <?php endforeach; ?>
      </select>

      <input type="date" name="from" class="input" value="<?php echo h($from); ?>" onchange="this.form.submit()">
      <input type="date" name="to" class="input" value="<?php echo h($to); ?>" onchange="this.form.submit()">
    </form>

    <?php if($stage!=='' && $class!=='' && !empty($rows)): ?>
      <div class="tableWrap">
        <table>
          <thead>
            <tr>
              <th>الطالب</th>
              <th>غياب</th>
              <th>تأخير</th>
              <th>حضور</th>
              <th>بعذر</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($rows as $r): ?>
              <tr>
                <td><b><?php echo h($r['name']); ?></b> <div style="color:#aaa;font-size:12px;margin-top:4px;">ID: <?php echo (int)$r['id']; ?></div></td>
                <td><span class="badge a"><?php echo (int)$r['absent_days']; ?></span></td>
                <td><span class="badge l"><?php echo (int)$r['late_days']; ?></span></td>
                <td><span class="badge p"><?php echo (int)$r['present_days']; ?></span></td>
                <td><span class="badge e"><?php echo (int)$r['excused_days']; ?></span></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php else: ?>
      <div style="margin-top:14px;text-align:center;font-weight:800;color:#fff;">اختر المرحلة والشعبة لعرض الإحصائيات.</div>
    <?php endif; ?>
  </div>
</div>

</body>
</html>
