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

/* ===========================================================
   ✅ صلاحيات الدخول
   - super              → awael / alawael (إدارة كاملة)
   - homework_exam_stats → alawael1 (واجبات + إحصائيات الامتحان)
   - eval_stats_grades   → alawael2 (تقييمات + درجات)
   - questions_only      → alawael0 (صفحة الأسئلة فقط)
   هذه الصفحة خاصة بـ:
   super + homework_exam_stats فقط
   =========================================================== */

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}

mysqli_set_charset($conn, "utf8mb4");

$admin_username = isset($_SESSION['admin_username']) ? $_SESSION['admin_username'] : '';
$admin_role     = isset($_SESSION['admin_role']) ? $_SESSION['admin_role'] : null;

if ($admin_role === null) {
    switch ($admin_username) {
        case 'alawael0':
            $admin_role = 'questions_only';
            break;
        case 'alawael1':
            $admin_role = 'homework_exam_stats';
            break;
        case 'alawael2':
            $admin_role = 'eval_stats_grades';
            break;
        case 'awael':
        case 'alawael':
        default:
            $admin_role = 'super';
            break;
    }
    $_SESSION['admin_role'] = $admin_role;
}

// ✅ منع أي حساب غير super أو homework_exam_stats من الدخول
if (!in_array($admin_role, array('super', 'homework_exam_stats'), true)) {
    header("Location: admin_dashboard.php");
    exit();
}

// اليوم
$today = date('Y-m-d');

// افتراضي: آخر 7 أيام
$default_from = date('Y-m-d', strtotime('-7 days'));
$default_to   = $today;

$from_date = isset($_GET['from']) ? trim($_GET['from']) : $default_from;
$to_date   = isset($_GET['to'])   ? trim($_GET['to'])   : $default_to;

// حماية الشكل
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $from_date)) $from_date = $default_from;
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $to_date))   $to_date   = $default_to;

// نتأكد from <= to
if ($from_date > $to_date) {
    $tmp = $from_date;
    $from_date = $to_date;
    $to_date = $tmp;
}

// نهربهم
$from_esc = mysqli_real_escape_string($conn, $from_date);
$to_esc   = mysqli_real_escape_string($conn, $to_date);

/*
  =============================================
  1) عدد الذين لم يرسلوا لكل يوم
  =============================================
*/
$daily_missing = [];
$q1 = mysqli_query($conn, "
    SELECT hw_date, COUNT(*) AS missing_count
    FROM homework_missing_teachers
    WHERE hw_date BETWEEN '$from_esc' AND '$to_esc'
    GROUP BY hw_date
    ORDER BY hw_date DESC
");
if ($q1) {
    while ($row = mysqli_fetch_assoc($q1)) {
        $daily_missing[] = $row;
    }
}

/*
  =============================================
  2) أكثر المدرسين تكرارًا في (لم يرسل)
  =============================================
*/
$top_missing = [];
$q2 = mysqli_query($conn, "
    SELECT 
        COALESCE(teacher_id, 0) AS teacher_id,
        teacher_name,
        subject,
        COUNT(*) AS miss_days
    FROM homework_missing_teachers
    WHERE hw_date BETWEEN '$from_esc' AND '$to_esc'
    GROUP BY COALESCE(teacher_id, 0), teacher_name, subject
    HAVING teacher_name IS NOT NULL AND teacher_name <> ''
    ORDER BY miss_days DESC, teacher_name ASC
    LIMIT 50
");
if ($q2) {
    while ($row = mysqli_fetch_assoc($q2)) {
        $top_missing[] = $row;
    }
}

/*
  =============================================
  3) المدرسون الأكثر امتحانات يومية (طوال العام)
     من جدول teacher_exam_counter
  =============================================
*/
$top_exams = [];
$q3 = mysqli_query($conn, "
    SELECT teacher_id, teacher_name, subject, total_exams
    FROM teacher_exam_counter
    ORDER BY total_exams DESC, teacher_name ASC
    LIMIT 50
");
if ($q3) {
    while ($row = mysqli_fetch_assoc($q3)) {
        $top_exams[] = $row;
    }
}

/*
  =============================================
  4) المدرسون الأقل امتحانات (اللي عدادهم 0 أو قليل)
     هنا راح نجيب من جدول teachers ونسوي LEFT JOIN
     على teacher_exam_counter حتى نطلع اللي ما مسوي شي
  =============================================
*/
$low_exams = [];
$q4 = mysqli_query($conn, "
    SELECT 
        t.id AS teacher_id,
        t.name AS teacher_name,
        t.subject AS subject,
        COALESCE(c.total_exams, 0) AS total_exams
    FROM teachers t
    LEFT JOIN teacher_exam_counter c ON t.id = c.teacher_id
    ORDER BY total_exams ASC, t.name ASC
    LIMIT 50
");
if ($q4) {
    while ($row = mysqli_fetch_assoc($q4)) {
        $low_exams[] = $row;
    }
}

// حساب إجمالي الأيام وعدد الأيام اللي بيها نقص
$total_days = 1 + (strtotime($to_date) - strtotime($from_date)) / 86400;
$days_with_missing = count($daily_missing);

?>
<!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;
}
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.15),transparent 70%),
    radial-gradient(circle at 70% 70%,rgba(255,215,0,0.15),transparent 80%),
    radial-gradient(circle at 50% 100%,rgba(138,43,226,0.1),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;
  justify-content:space-between;
  align-items:center;
  padding:16px 20px;
  background:rgba(255,255,255,0.05);
  border-bottom:1px solid rgba(255,255,255,0.05);
}
header .btn{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  color:#fff;
  padding:7px 14px;
  border-radius:10px;
  text-decoration:none;
  font-weight:600;
}
.container{
  width:100%;
  max-width:1250px;
  margin:25px auto 45px;
  padding:0 15px;
}
.filter-box{
  background:rgba(255,255,255,0.03);
  border:1px solid rgba(255,255,255,0.03);
  border-radius:14px;
  padding:12px 14px;
  display:flex;
  gap:10px;
  align-items:center;
  justify-content:space-between;
  margin-bottom:20px;
}
.filter-box form{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.filter-box input[type="date"]{
  background:rgba(0,0,0,0.25);
  border:1px solid rgba(255,255,255,0.05);
  border-radius:8px;
  padding:5px 10px;
  color:#fff;
}
.filter-box button{
  background:#00e6ff;
  border:none;
  padding:6px 12px;
  border-radius:8px;
  font-weight:600;
  cursor:pointer;
}
.cards{
  display:grid;
  grid-template-columns:repeat(auto-fit, minmax(180px,1fr));
  gap:14px;
  margin-bottom:22px;
}
.card{
  background:rgba(255,255,255,0.025);
  border:1px solid rgba(255,255,255,0.02);
  border-radius:14px;
  padding:12px 14px;
}
.card h3{font-size:13px;margin-bottom:5px;color:#ddd}
.card .num{font-size:22px;font-weight:700}
.section{
  margin-bottom:25px;
  background:rgba(255,255,255,0.02);
  border:1px solid rgba(255,255,255,0.02);
  border-radius:14px;
  overflow:hidden;
}
.section h2{
  font-size:14px;
  padding:10px 12px;
  background:rgba(0,0,0,0.2);
  border-bottom:1px solid rgba(255,255,255,0.02);
}
table{width:100%;border-collapse:collapse}
th,td{
  padding:8px 8px;
  font-size:13px;
  border-bottom:1px solid rgba(255,255,255,0.02);
}
th{text-align:right;background:rgba(255,255,255,0.01);white-space:nowrap}
tr:nth-child(even){background:rgba(0,0,0,0.12)}
.badge{display:inline-block;padding:2px 8px;border-radius:9px;font-size:11px}
.badge-red{background:rgba(255,0,74,0.12);border:1px solid rgba(255,0,74,0.4);}
.badge-green{background:rgba(0,255,135,0.12);border:1px solid rgba(0,255,135,0.35);}
@media(max-width:720px){
  .filter-box{flex-direction:column;align-items:flex-start}
  table{display:block;overflow-x:auto}
}
</style>
</head>
<body>

<header>
  <h1>📊 إحصائيات الواجبات المدرسية</h1>
  <a href="admin_dashboard.php" class="btn">↩ العودة للوحة</a>
</header>

<div class="container">

  <div class="filter-box">
    <form method="get">
      <label>من:</label>
      <input type="date" name="from" value="<?php echo htmlspecialchars($from_date, ENT_QUOTES, 'UTF-8'); ?>">
      <label>إلى:</label>
      <input type="date" name="to" value="<?php echo htmlspecialchars($to_date, ENT_QUOTES, 'UTF-8'); ?>">
      <button type="submit">تطبيق</button>
    </form>
    <div style="color:#aaa;font-size:12px;">
      المدة: <?php echo htmlspecialchars($from_date); ?> → <?php echo htmlspecialchars($to_date); ?>
    </div>
  </div>

  <div class="cards">
    <div class="card">
      <h3>عدد الأيام في المدة</h3>
      <div class="num"><?php echo (int)$total_days; ?></div>
    </div>
    <div class="card">
      <h3>أيام ظهر فيها "لم يرسل"</h3>
      <div class="num"><?php echo (int)$days_with_missing; ?></div>
    </div>
    <div class="card">
      <h3>إجمالي حالات "لم يرسل"</h3>
      <div class="num">
        <?php
        $sum_missing = 0;
        foreach ($daily_missing as $d) $sum_missing += (int)$d['missing_count'];
        echo (int)$sum_missing;
        ?>
      </div>
    </div>
    <div class="card">
      <h3>أعلى يوم بدون واجب</h3>
      <div class="num">
        <?php
        if (count($daily_missing) > 0) {
            $max = 0; $maxd = '';
            foreach ($daily_missing as $d) {
                if ((int)$d['missing_count'] > $max) {
                    $max = (int)$d['missing_count'];
                    $maxd = $d['hw_date'];
                }
            }
            echo $max.' معلّم';
            echo "<div style='font-size:11px;color:#bbb;'>($maxd)</div>";
        } else {
            echo '0';
        }
        ?>
      </div>
    </div>
  </div>

  <!-- 1) جدول الأيام -->
  <div class="section">
    <h2>📅 عدد المدرسين الذين لم يرسلوا في كل يوم</h2>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>اليوم</th>
          <th>عدد المدرسين الذين لم يرسلوا</th>
        </tr>
      </thead>
      <tbody>
      <?php if (count($daily_missing) == 0): ?>
        <tr><td colspan="3" style="text-align:center;color:#aaa;">لا توجد بيانات في هذه المدة.</td></tr>
      <?php else: ?>
        <?php $i=1; foreach ($daily_missing as $d): ?>
          <tr>
            <td><?php echo $i++; ?></td>
            <td><?php echo htmlspecialchars($d['hw_date'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><span class="badge badge-red"><?php echo (int)$d['missing_count']; ?></span></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- 2) أكثر المدرسين تكراراً -->
  <div class="section">
    <h2>🙋‍♂️ أكثر المدرسين الذين لم يرسلوا واجبات (حسب المدة)</h2>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>اسم المدرس</th>
          <th>المادة</th>
          <th>عدد الأيام التي لم يرسل فيها</th>
        </tr>
      </thead>
      <tbody>
      <?php if (count($top_missing) == 0): ?>
        <tr><td colspan="4" style="text-align:center;color:#aaa;">لا توجد بيانات.</td></tr>
      <?php else: ?>
        <?php $i=1; foreach ($top_missing as $tm): ?>
        <tr>
          <td><?php echo $i++; ?></td>
          <td><?php echo htmlspecialchars($tm['teacher_name'], ENT_QUOTES, 'UTF-8'); ?></td>
          <td><?php echo htmlspecialchars($tm['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
          <td><span class="badge badge-red"><?php echo (int)$tm['miss_days']; ?></span></td>
        </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- 3) الأكثر امتحانات -->
  <div class="section">
    <h2>📝 المدرسون الأكثر امتحانات يومية (طوال العام)</h2>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>اسم المدرس</th>
          <th>المادة</th>
          <th>عدد الامتحانات المسجّلة</th>
        </tr>
      </thead>
      <tbody>
      <?php if (count($top_exams) == 0): ?>
        <tr><td colspan="4" style="text-align:center;color:#aaa;">لا توجد بيانات.</td></tr>
      <?php else: ?>
        <?php $i=1; foreach ($top_exams as $te): ?>
        <tr>
          <td><?php echo $i++; ?></td>
          <td><?php echo htmlspecialchars($te['teacher_name'], ENT_QUOTES, 'UTF-8'); ?></td>
          <td><?php echo htmlspecialchars($te['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
          <td><span class="badge badge-green"><?php echo (int)$te['total_exams']; ?></span></td>
        </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- 4) الأقل امتحانات -->
  <div class="section">
    <h2>⚠️ المدرسون الأقل نشاطاً بالامتحانات اليومية</h2>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>اسم المدرس</th>
          <th>المادة</th>
          <th>عدد الامتحانات المسجّلة</th>
        </tr>
      </thead>
      <tbody>
      <?php if (count($low_exams) == 0): ?>
        <tr><td colspan="4" style="text-align:center;color:#aaa;">لا توجد بيانات.</td></tr>
      <?php else: ?>
        <?php $i=1; foreach ($low_exams as $le): ?>
        <tr>
          <td><?php echo $i++; ?></td>
          <td><?php echo htmlspecialchars($le['teacher_name'], ENT_QUOTES, 'UTF-8'); ?></td>
          <td><?php echo htmlspecialchars($le['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
          <td><?php echo (int)$le['total_exams']; ?></td>
        </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

</div>

<footer style="text-align:center;padding:12px;color:#aaa;font-size:12px;">
  © <?php echo date("Y"); ?> ثانوية الأوائل الأهلية للبنين
</footer>

</body>
</html>
