<?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']) : '';
$date  = isset($_GET['date']) ? trim($_GET['date']) : date("Y-m-d");
$msg   = isset($_GET['msg']) ? trim($_GET['msg']) : '';

/* ==== إجراءات POST (تثبيت الغياب / تغيير الحالة) ==== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
  $action = $_POST['action'];

  if ($action === 'close_day') {
    $stage = isset($_POST['stage']) ? trim($_POST['stage']) : '';
    $class = isset($_POST['class']) ? trim($_POST['class']) : '';
    $date  = isset($_POST['date']) ? trim($_POST['date']) : date("Y-m-d");

    if ($stage !== '' && $class !== '') {
      $st = mysqli_real_escape_string($conn, $stage);
      $cl = mysqli_real_escape_string($conn, $class);
      $dt = mysqli_real_escape_string($conn, $date);

      $sql = "
        INSERT INTO attendance_daily (student_id, att_date, status, method, device_name, notes)
        SELECT s.id, '$dt', 'absent', 'system', 'system', 'Auto-closed day'
        FROM students s
        LEFT JOIN attendance_daily a
          ON a.student_id = s.id AND a.att_date = '$dt'
        WHERE s.stage='$st' AND s.class='$cl'
          AND a.id IS NULL
      ";
      mysqli_query($conn, $sql);
      header("Location: admin_attendance_manage.php?stage=".urlencode($stage)."&class=".urlencode($class)."&date=".urlencode($date)."&msg=".urlencode("✅ تم تثبيت الغياب لغير الحاضرين"));
      exit();
    }
  }

  if ($action === 'set_status') {
    $student_id = isset($_POST['student_id']) ? (int)$_POST['student_id'] : 0;
    $new_status = isset($_POST['new_status']) ? trim($_POST['new_status']) : '';
    $stage = isset($_POST['stage']) ? trim($_POST['stage']) : '';
    $class = isset($_POST['class']) ? trim($_POST['class']) : '';
    $date  = isset($_POST['date']) ? trim($_POST['date']) : date("Y-m-d");

    if ($student_id > 0 && in_array($new_status, array('present','late','absent','excused'), true)) {
      $dt = mysqli_real_escape_string($conn, $date);

      // هل يوجد سجل اليوم؟
      $row_id = 0;
      $stmt = mysqli_prepare($conn, "SELECT id FROM attendance_daily WHERE student_id=? AND att_date=? LIMIT 1");
      mysqli_stmt_bind_param($stmt, "is", $student_id, $date);
      mysqli_stmt_execute($stmt);
      mysqli_stmt_bind_result($stmt, $row_id);
      $has = mysqli_stmt_fetch($stmt);
      mysqli_stmt_close($stmt);

      if ($has) {
        $stmt = mysqli_prepare($conn, "UPDATE attendance_daily SET status=?, method='manual', device_name='Admin' WHERE id=?");
        mysqli_stmt_bind_param($stmt, "si", $new_status, $row_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
      } else {
        $stmt = mysqli_prepare($conn, "INSERT INTO attendance_daily (student_id, att_date, status, method, device_name, notes) VALUES (?,?,?, 'manual','Admin','Manual set')");
        mysqli_stmt_bind_param($stmt, "iss", $student_id, $date, $new_status);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
      }

      header("Location: admin_attendance_manage.php?stage=".urlencode($stage)."&class=".urlencode($class)."&date=".urlencode($date)."&msg=".urlencode("✅ تم تحديث الحالة"));
      exit();
    }
  }
}

/* ==== قوائم المرحلة/الشعبة ==== */
$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();
$summary = array("total"=>0,"present"=>0,"late"=>0,"absent"=>0,"excused"=>0,"checkout"=>0);

if ($stage !== '' && $class !== '') {
  $st = mysqli_real_escape_string($conn, $stage);
  $cl = mysqli_real_escape_string($conn, $class);
  $dt = mysqli_real_escape_string($conn, $date);

  $sql = "
    SELECT s.id, s.name,
           a.checkin_at, a.checkout_at, a.status
    FROM students s
    LEFT JOIN attendance_daily a
      ON a.student_id = s.id AND a.att_date = '$dt'
    WHERE s.stage='$st' AND s.class='$cl'
    ORDER BY s.name ASC
  ";
  $res3 = mysqli_query($conn, $sql);
  while ($r = mysqli_fetch_assoc($res3)) {
    $status = $r['status'];
    // إذا ماكو سجل، اعتبره "غير مثبت" (نحسبه غائب مؤقتاً للعرض)
    $display_status = $status ? $status : 'absent';
    $rows[] = array(
      "id" => (int)$r['id'],
      "name" => $r['name'],
      "checkin_at" => $r['checkin_at'],
      "checkout_at" => $r['checkout_at'],
      "status" => $display_status,
      "has_record" => ($status ? 1 : 0)
    );

    $summary["total"]++;
    if ($display_status === 'present') $summary["present"]++;
    if ($display_status === 'late') $summary["late"]++;
    if ($display_status === 'absent') $summary["absent"]++;
    if ($display_status === 'excused') $summary["excused"]++;
    if (!empty($r['checkout_at'])) $summary["checkout"]++;
  }
}
?>
<!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;
}
.btn2{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  border:none; color:#fff; padding:10px 14px;
  border-radius:12px; font-weight:700; cursor:pointer; transition:.2s;
}
.btn2:hover{transform:scale(1.03);box-shadow:0 0 15px rgba(0,255,255,0.35)}
.btnGhost{
  background:rgba(255,255,255,0.10);
  border:1px solid rgba(255,255,255,0.15);
  color:#fff; padding:10px 14px; border-radius:12px; font-weight:700; cursor:pointer;
}
.msg{margin:14px 0;text-align:center;font-weight:800;color:#fff}
.cards{
  margin-top:14px;
  display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
  gap:12px;
}
.kpi{
  background:rgba(255,255,255,0.08);
  border:1px solid rgba(255,255,255,0.12);
  border-radius:18px; padding:12px 14px;
}
.kpi .n{font-size:22px;font-weight:900;color:#00e6ff}
.kpi .t{color:#ccc;font-size:13px;margin-top:6px}
.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)}
.b-present{background:rgba(0,255,120,0.12);color:#6fffb0}
.b-late{background:rgba(255,215,0,0.10);color:#ffe28a}
.b-absent{background:rgba(255,80,80,0.10);color:#ffb3b3}
.b-excused{background:rgba(120,180,255,0.12);color:#b9dcff}
.actions form{display:inline-block;margin:2px}
.small{
  padding:8px 10px;border-radius:12px;font-weight:900;cursor:pointer;border:none
}
.small.p{background:rgba(0,255,120,0.14);color:#6fffb0;border:1px solid rgba(0,255,120,0.25)}
.small.l{background:rgba(255,215,0,0.12);color:#ffe28a;border:1px solid rgba(255,215,0,0.25)}
.small.a{background:rgba(255,80,80,0.12);color:#ffb3b3;border:1px solid rgba(255,80,80,0.25)}
.small.e{background:rgba(120,180,255,0.14);color:#b9dcff;border:1px solid rgba(120,180,255,0.25)}
</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_gate.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="date" class="input" value="<?php echo h($date); ?>" onchange="this.form.submit()">
      <a class="btnGhost" href="admin_attendance_stats.php">إحصائيات الغياب</a>
      <a class="btnGhost" href="admin_face_enroll.php">تسجيل بصمة الوجه</a>
    </form>

    <?php if($msg!==''): ?><div class="msg"><?php echo h($msg); ?></div><?php endif; ?>

    <?php if($stage!=='' && $class!=='' && $summary["total"]>0): ?>
      <div class="cards">
        <div class="kpi"><div class="n"><?php echo (int)$summary["total"]; ?></div><div class="t">عدد الطلبة</div></div>
        <div class="kpi"><div class="n"><?php echo (int)$summary["present"]; ?></div><div class="t">حاضر</div></div>
        <div class="kpi"><div class="n"><?php echo (int)$summary["late"]; ?></div><div class="t">متأخر</div></div>
        <div class="kpi"><div class="n"><?php echo (int)$summary["absent"]; ?></div><div class="t">غائب (عرض)</div></div>
        <div class="kpi"><div class="n"><?php echo (int)$summary["excused"]; ?></div><div class="t">بعذر</div></div>
        <div class="kpi"><div class="n"><?php echo (int)$summary["checkout"]; ?></div><div class="t">سجّل مغادرة</div></div>
      </div>

      <div style="margin-top:14px; display:flex; gap:10px; flex-wrap:wrap;">
        <form method="post" onsubmit="return confirm('تثبيت الغياب سيضيف سجلات غياب لمن لم يسجل حضور. هل أنت متأكد؟');">
          <input type="hidden" name="action" value="close_day">
          <input type="hidden" name="stage" value="<?php echo h($stage); ?>">
          <input type="hidden" name="class" value="<?php echo h($class); ?>">
          <input type="hidden" name="date" value="<?php echo h($date); ?>">
          <button class="btn2" type="submit">✅ تثبيت الغياب (إغلاق اليوم)</button>
        </form>
      </div>

      <div class="tableWrap">
        <table>
          <thead>
            <tr>
              <th>الطالب</th>
              <th>الحضور</th>
              <th>المغادرة</th>
              <th>الحالة</th>
              <th>تغيير سريع</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($rows as $r): ?>
              <?php
                $st = $r['status'];
                $badge = 'b-absent'; $txt = 'غائب';
                if ($st==='present'){ $badge='b-present'; $txt='حاضر'; }
                if ($st==='late'){ $badge='b-late'; $txt='متأخر'; }
                if ($st==='excused'){ $badge='b-excused'; $txt='بعذر'; }
              ?>
              <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><?php echo $r['checkin_at'] ? h($r['checkin_at']) : '—'; ?></td>
                <td><?php echo $r['checkout_at'] ? h($r['checkout_at']) : '—'; ?></td>
                <td><span class="badge <?php echo $badge; ?>"><?php echo $txt; ?></span></td>
                <td class="actions">
                  <?php
                    $sid = (int)$r['id'];
                    $baseHidden = '
                      <input type="hidden" name="action" value="set_status">
                      <input type="hidden" name="student_id" value="'.$sid.'">
                      <input type="hidden" name="stage" value="'.h($stage).'">
                      <input type="hidden" name="class" value="'.h($class).'">
                      <input type="hidden" name="date" value="'.h($date).'">
                    ';
                  ?>
                  <form method="post"><?php echo $baseHidden; ?><input type="hidden" name="new_status" value="present"><button class="small p" type="submit">حاضر</button></form>
                  <form method="post"><?php echo $baseHidden; ?><input type="hidden" name="new_status" value="late"><button class="small l" type="submit">متأخر</button></form>
                  <form method="post"><?php echo $baseHidden; ?><input type="hidden" name="new_status" value="absent"><button class="small a" type="submit">غائب</button></form>
                  <form method="post"><?php echo $baseHidden; ?><input type="hidden" name="new_status" value="excused"><button class="small e" type="submit">بعذر</button></form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php else: ?>
      <div class="msg">اختر المرحلة والشعبة لعرض بيانات الحضور.</div>
    <?php endif; ?>
  </div>
</div>

</body>
</html>
