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

// ✅ التحقق من تسجيل دخول الأدمن
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;

// ✅ لو ماكو role (جلسة قديمة) نحدده من اسم المستخدم
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 + eval_stats_grades
if (!in_array($admin_role, array('super','homework_exam_stats','eval_stats_grades'), true)) {
    header("Location: admin_dashboard.php");
    exit();
}

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

// التاريخ المختار
$sel_date = isset($_GET['d']) ? trim($_GET['d']) : $today;
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $sel_date)) {
    $sel_date = $today;
}

/*
  ======================================================
  ✅ جداول الإحصائية الدائمة
  ======================================================
*/
mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `teacher_exam_counter` (
  `teacher_id` INT(11) NOT NULL,
  `teacher_name` VARCHAR(150) NOT NULL,
  `subject` VARCHAR(150) DEFAULT NULL,
  `total_exams` INT(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`teacher_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `teacher_exam_log` (
  `homework_id` INT(11) NOT NULL,
  `teacher_id` INT(11) NOT NULL,
  `exam_date` DATE NOT NULL,
  PRIMARY KEY (`homework_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/*
  ======================================================
  ✅ جدول المدرسين الذين لم يرسلوا (نضيف stages, classes)
  ======================================================
*/
mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `homework_missing_teachers` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `hw_date` DATE NOT NULL,
  `teacher_id` INT(11) DEFAULT NULL,
  `teacher_name` VARCHAR(150) DEFAULT NULL,
  `subject` VARCHAR(150) DEFAULT NULL,
  `stages` VARCHAR(255) DEFAULT NULL,
  `classes` TEXT,
  `note` VARCHAR(255) DEFAULT NULL,
  `created_at` DATETIME DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_date` (`hw_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/*
  ======================================================
  ✅ جدول تخزين "تم النسخ"
  ======================================================
*/
mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `homework_copied` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `hw_id` INT(11) NOT NULL,
  `hw_date` DATE NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_hw` (`hw_id`,`hw_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/*
  ======================================================
  ✅ دالة تحديث جدول المدرسين الذين لم يرسلوا
  ======================================================
*/
function update_missing_teachers($conn, $day)
{
    // كل المدرسين (نجيب المراحل والشعب أيضاً)
    $teachers = [];
    $rT = mysqli_query($conn, "SELECT id, name, subject, stages, classes FROM teachers ORDER BY name ASC");
    if ($rT) {
        while ($row = mysqli_fetch_assoc($rT)) {
            $teachers[] = [
                'id'      => (int)$row['id'],
                'name'    => $row['name'],
                'subject' => $row['subject'],
                'stages'  => $row['stages'],
                'classes' => $row['classes'],
            ];
        }
    }

    $day_esc = mysqli_real_escape_string($conn, $day);

    // نحذف بيانات اليوم
    mysqli_query($conn, "DELETE FROM homework_missing_teachers WHERE hw_date = '$day_esc'");

    // المدرسين اللي أرسلوا
    $sent_ids = [];
    $rS = mysqli_query($conn, "SELECT DISTINCT teacher_id FROM homeworks WHERE DATE(created_at) = '$day_esc'");
    if ($rS) {
        while ($row = mysqli_fetch_assoc($rS)) {
            $sent_ids[] = (int)$row['teacher_id'];
        }
    }

    // نضيف اللي ما أرسل
    foreach ($teachers as $t) {
        if (!in_array($t['id'], $sent_ids, true)) {
            $tname = mysqli_real_escape_string($conn, $t['name']);
            $tsubj = mysqli_real_escape_string($conn, $t['subject']);
            $tstg  = mysqli_real_escape_string($conn, $t['stages']);
            $tcls  = mysqli_real_escape_string($conn, $t['classes']);
            mysqli_query($conn, "
                INSERT INTO homework_missing_teachers
                    (hw_date, teacher_id, teacher_name, subject, stages, classes, note, created_at)
                VALUES
                    ('$day_esc', ".($t['id'] ?: "NULL").", '$tname', '$tsubj', '$tstg', '$tcls', 'لم يرسل الواجب حتى الآن', NOW())
            ");
        }
    }
}

/*
  ======================================================
  ✅ استقبال AJAX لتعليم واجب بأنه "تم نسخه"
  ======================================================
*/
if (isset($_POST['action']) && $_POST['action'] === 'mark_copied') {
    $hw_id = isset($_POST['hw_id']) ? intval($_POST['hw_id']) : 0;
    $d     = isset($_POST['d']) ? $_POST['d'] : date('Y-m-d');
    if ($hw_id > 0 && preg_match("/^\d{4}-\d{2}-\d{2}$/", $d)) {
        $d_esc = mysqli_real_escape_string($conn, $d);
        mysqli_query($conn, "
            INSERT INTO homework_copied (hw_id, hw_date)
            VALUES ($hw_id, '$d_esc')
            ON DUPLICATE KEY UPDATE hw_id = VALUES(hw_id)
        ");
        echo 'ok';
    } else {
        echo 'err';
    }
    exit();
}

/*
  ======================================================
  ✅ مسح كل واجبات اليوم المحدد
  ======================================================
*/
if (isset($_GET['clear_all']) && $_GET['clear_all'] == '1') {
    $d_esc = mysqli_real_escape_string($conn, $sel_date);
    // نحذف الواجبات لليوم
    mysqli_query($conn, "DELETE FROM homeworks WHERE DATE(created_at) = '$d_esc'");
    // نحذف العلامات المنسوخة لليوم
    mysqli_query($conn, "DELETE FROM homework_copied WHERE hw_date = '$d_esc'");
    // نعيد بناء جدول اللي ما أرسلوا
    update_missing_teachers($conn, $sel_date);
    header("Location: homework_report.php?d=".$sel_date);
    exit();
}

/*
  ======================================================
  ✅ حذف واجب + تثبيت الامتحان قبل الحذف
  ======================================================
*/
if (isset($_GET['del'])) {
    $del_id = intval($_GET['del']);
    if ($del_id > 0) {
        $old = mysqli_query($conn, "SELECT * FROM homeworks WHERE id = $del_id LIMIT 1");
        $rowOld = $old ? mysqli_fetch_assoc($old) : null;

        // لو كان بيه امتحان، خزّنه بالإحصائية
        if ($rowOld && (int)$rowOld['has_exam'] === 1) {
            $hw_id = (int)$rowOld['id'];
            $tid   = (int)$rowOld['teacher_id'];
            $tname = mysqli_real_escape_string($conn, $rowOld['teacher_name']);
            $tsubj = mysqli_real_escape_string($conn, $rowOld['subject']);
            $cdate = substr($rowOld['created_at'], 0, 10);

            // لو مو مسجل باللوق، سجّله وزيد العداد
            $chk = mysqli_query($conn, "SELECT 1 FROM teacher_exam_log WHERE homework_id = $hw_id LIMIT 1");
            if (!$chk || mysqli_num_rows($chk) == 0) {
                mysqli_query($conn, "
                    INSERT INTO teacher_exam_log (homework_id, teacher_id, exam_date)
                    VALUES ($hw_id, $tid, '$cdate')
                ");

                mysqli_query($conn, "
                    INSERT INTO teacher_exam_counter (teacher_id, teacher_name, subject, total_exams)
                    VALUES ($tid, '$tname', '$tsubj', 1)
                    ON DUPLICATE KEY UPDATE
                        teacher_name = VALUES(teacher_name),
                        subject = VALUES(subject),
                        total_exams = total_exams + 1
                ");
            }
        }

        // نحذف الواجب
        mysqli_query($conn, "DELETE FROM homeworks WHERE id = $del_id LIMIT 1");
        // نحذف علامة النسخ لو موجودة
        mysqli_query($conn, "DELETE FROM homework_copied WHERE hw_id = $del_id AND hw_date = '".$sel_date."'");

        // نعيد بناء جدول اللي ما أرسلوا
        update_missing_teachers($conn, $sel_date);

        header("Location: homework_report.php?d=".$sel_date);
        exit();
    }
}

/*
  ======================================================
  ✅ مزامنة كل الامتحانات الموجودة فعليًا مرة وحدة
  ======================================================
*/
$qExamSync = mysqli_query($conn, "SELECT id, teacher_id, teacher_name, subject, DATE(created_at) AS cdate FROM homeworks WHERE has_exam = 1");
if ($qExamSync) {
    while ($rowE = mysqli_fetch_assoc($qExamSync)) {
        $hw_id = (int)$rowE['id'];
        $tid   = (int)$rowE['teacher_id'];
        $tname = mysqli_real_escape_string($conn, $rowE['teacher_name']);
        $tsubj = mysqli_real_escape_string($conn, $rowE['subject']);
        $cdate = $rowE['cdate'];

        $chk = mysqli_query($conn, "SELECT 1 FROM teacher_exam_log WHERE homework_id = $hw_id LIMIT 1");
        if (!$chk || mysqli_num_rows($chk) == 0) {
            // سجل الامتحان
            mysqli_query($conn, "
                INSERT INTO teacher_exam_log (homework_id, teacher_id, exam_date)
                VALUES ($hw_id, $tid, '$cdate')
            ");
            // زيد عداد المدرس
            mysqli_query($conn, "
                INSERT INTO teacher_exam_counter (teacher_id, teacher_name, subject, total_exams)
                VALUES ($tid, '$tname', '$tsubj', 1)
                ON DUPLICATE KEY UPDATE
                    teacher_name = VALUES(teacher_name),
                    subject = VALUES(subject),
                    total_exams = total_exams + 1
            ");
        }
    }
}

/*
  ======================================================
  ✅ واجبات اليوم
  ======================================================
*/
$homeworks_raw = [];
$q = "
    SELECT *
    FROM homeworks
    WHERE DATE(created_at) = '".$sel_date."'
    ORDER BY 
      FIELD(stage,
        'أول','أول ابتدائي','أول متوسط','أول ثانوي',
        'ثاني','ثاني ابتدائي','ثاني متوسط','ثاني ثانوي',
        'ثالث','ثالث ابتدائي','ثالث متوسط','ثالث ثانوي',
        'رابع','رابع ابتدائي','رابع علمي','رابع إعدادي',
        'خامس','خامس ابتدائي','خامس علمي','خامس إعدادي',
        'سادس','سادس ابتدائي','سادس علمي','سادس إعدادي'
      ),
      class,
      created_at DESC,
      id DESC
";
$r = mysqli_query($conn, $q);
if ($r) {
    while ($row = mysqli_fetch_assoc($r)) {
        $homeworks_raw[] = $row;
    }
}

// حذف التكرار
$homeworks = [];
$seen = [];
foreach ($homeworks_raw as $hw) {
    $key = $hw['teacher_name'].'|'.$hw['subject'].'|'.$hw['stage'].'|'.$hw['class'].'|'.$hw['homework'].'|'.substr($hw['created_at'],0,10);
    if (!isset($seen[$key])) {
        $seen[$key] = true;
        $homeworks[] = $hw;
    }
}

/*
  ======================================================
  ✅ واجبات اليوم المنسوخة (حتى نلوّن الصفوف)
  ======================================================
*/
$copied_ids = [];
$rcp = mysqli_query($conn, "SELECT hw_id FROM homework_copied WHERE hw_date = '".$sel_date."'");
if ($rcp) {
    while ($row = mysqli_fetch_assoc($rcp)) {
        $copied_ids[] = (int)$row['hw_id'];
    }
}

/*
  ======================================================
  ✅ المدرسون الذين لم يرسلوا
  ======================================================
*/
$missing = [];
$rm = mysqli_query($conn, "
    SELECT m.*, t.stages AS t_stages, t.classes AS t_classes
    FROM homework_missing_teachers m
    LEFT JOIN teachers t ON m.teacher_id = t.id
    WHERE m.hw_date = '".$sel_date."'
    ORDER BY m.teacher_name ASC
");
if ($rm) {
    while ($row = mysqli_fetch_assoc($rm)) {
        $row['stages'] = $row['stages'] != '' ? $row['stages'] : $row['t_stages'];
        $row['classes'] = $row['classes'] != '' ? $row['classes'] : $row['t_classes'];
        $missing[] = $row;
    }
}
$missing_count = count($missing);

/*
  ======================================================
  ✅ إحصائية الامتحان اليومي
  ======================================================
*/
$exam_stats = [];
$qs = mysqli_query($conn, "
    SELECT 
      c.teacher_id,
      c.teacher_name,
      c.subject,
      c.total_exams,
      GROUP_CONCAT(DISTINCT h.stage ORDER BY h.stage SEPARATOR '، ') AS stages,
      GROUP_CONCAT(DISTINCT h.class ORDER BY h.class SEPARATOR '، ') AS classes
    FROM teacher_exam_counter c
    LEFT JOIN teacher_exam_log l ON c.teacher_id = l.teacher_id
    LEFT JOIN homeworks h ON l.homework_id = h.id
    GROUP BY c.teacher_id, c.teacher_name, c.subject, c.total_exams
    ORDER BY c.total_exams DESC, c.teacher_name ASC
");
if ($qs) {
    while ($row = mysqli_fetch_assoc($qs)) {
        $exam_stats[] = $row;
    }
}

/*
  ======================================================
  ✅ دالة لون المرحلة
  ======================================================
*/
function get_stage_main($stage_text) {
    $stage_text = trim($stage_text);
    $parts = preg_split('/\s+/u', $stage_text);
    return $parts[0]; // أول كلمة
}

$STAGE_COLORS = [
    'أول'   => '#0ea5e9',
    'ثاني'  => '#22c55e',
    'ثالث'  => '#eab308',
    'رابع'  => '#8b5cf6',
    'خامس'  => '#f97316',
    'سادس'  => '#ef4444',
];
?>
<!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;
  display:flex;
  flex-direction:column;
  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.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;
  align-items:center;
  justify-content:space-between;
  padding:16px 20px;
  background:rgba(255,255,255,0.06);
  border-bottom:1px solid rgba(255,255,255,0.08);
  backdrop-filter:blur(10px);
}
h1{font-size:18px}
header .btn{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  color:#fff;
  padding:7px 14px;
  border-radius:10px;
  text-decoration:none;
  font-weight:600;
  transition:.3s;
}
header .btn:hover{transform:scale(1.03)}
.container{
  width:100%;
  max-width:1200px;
  margin:25px auto 50px;
  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;
  justify-content:space-between;
  align-items:center;
  gap:10px;
  margin-bottom:15px;
}
.filter-box form{display:flex;gap:10px;align-items:center}
.filter-box input[type="date"]{
  background:rgba(0,0,0,0.25);
  border:1px solid rgba(255,255,255,0.04);
  border-radius:8px;
  padding:5px 10px;
  color:#fff;
}
.filter-box button{
  background:#00e6ff;
  border:none;
  padding:6px 12px;
  border-radius:8px;
  cursor:pointer;
  font-weight:600;
}
.btn-row{display:flex;gap:8px;flex-wrap:wrap}
.table-wrap{
  background:rgba(255,255,255,0.02);
  border:1px solid rgba(255,255,255,0.02);
  border-radius:14px;
  overflow:hidden;
}
table{width:100%;border-collapse:collapse}
thead{background:rgba(0,0,0,0.25);}
th,td{
  padding:10px 8px;
  font-size:13px;
  border-bottom:1px solid rgba(255,255,255,0.03);
  vertical-align:top;
}
th{white-space:nowrap;text-align:right}
.badge{
  display:inline-block;
  padding:2px 8px;
  border-radius:12px;
  font-size:11px;
}
.badge-green{background:rgba(0,255,135,0.1);border:1px solid rgba(0,255,135,0.4);}
.badge-red{background:rgba(255,0,74,0.1);border:1px solid rgba(255,0,74,0.4);}
.stage-badge{
  display:inline-block;
  padding:3px 10px;
  border-radius:9999px;
  font-size:12px;
  font-weight:600;
  color:#fff;
}
.actions button, .actions a{
  background:rgba(255,255,255,0.05);
  border:1px solid rgba(255,255,255,0.08);
  border-radius:8px;
  padding:5px 9px;
  color:#fff;
  cursor:pointer;
  font-size:11px;
  text-decoration:none;
  margin-bottom:3px;
  display:inline-block;
}
.actions button:hover, .actions a:hover{
  background:rgba(0,230,255,0.2);
}
#missingBox, #examsBox{
  margin-top:20px;
  background:rgba(0,0,0,0.25);
  border:1px solid rgba(255,255,255,0.03);
  border-radius:12px;
  display:none;
}
#missingBox table td, #missingBox table th,
#examsBox table td,  #examsBox table th{
  font-size:12px;
}
.toggle-missing, .toggle-exams{
  background:rgba(255,255,255,0.04);
  border:1px solid rgba(255,255,255,0.08);
  border-radius:10px;
  padding:7px 14px;
  color:#fff;
  cursor:pointer;
  font-size:13px;
  white-space:nowrap;
}

/* ✅ الصف المنسوخ */
tr.copied {
  background: rgba(34, 197, 94, 0.13) !important;
}
tr.copied td {
  border-bottom-color: rgba(34, 197, 94, 0.25);
}

@media(max-width:700px){
  .filter-box{flex-direction:column;align-items:flex-start}
  .filter-box form{flex-wrap:wrap}
  .btn-row{flex-wrap:wrap}
  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="d" value="<?php echo htmlspecialchars($sel_date, ENT_QUOTES, 'UTF-8'); ?>">
      <button type="submit">عرض</button>
    </form>
    <div class="btn-row">
      <button type="button" class="toggle-missing" onclick="toggleMissing()">
        📋 المدرسون الذين لم يرسلوا واجب لهذا اليوم (<?php echo $missing_count; ?>)
      </button>
      <button type="button" class="toggle-exams" onclick="toggleExams()">
        📑 إحصائية الامتحان اليومي
      </button>
      <!-- ✅ زر مسح كل واجبات اليوم -->
      <a href="homework_report.php?d=<?php echo $sel_date; ?>&clear_all=1" onclick="return confirm('هل أنت متأكد من مسح جميع الواجبات لهذا اليوم؟');" class="toggle-exams" style="background:rgba(255,0,74,0.15);border-color:rgba(255,0,74,0.35);">
        🧹 مسح كل واجبات هذا اليوم
      </a>
    </div>
  </div>

  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>الوقت</th>
          <th>المرحلة</th>
          <th>الشعبة</th>
          <th>اسم المدرس</th>
          <th>المادة</th>
          <th>الواجب</th>
          <th>امتحان؟</th>
          <th>عمليات</th>
        </tr>
      </thead>
      <tbody>
      <?php if (count($homeworks) == 0): ?>
        <tr>
          <td colspan="9" style="text-align:center;color:#bbb;padding:25px 0;">لا توجد واجبات مرسلة في هذا التاريخ.</td>
        </tr>
      <?php else: ?>
        <?php $i=1; foreach ($homeworks as $hw): ?>
          <?php
            $stage_main = get_stage_main($hw['stage']);
            $color = isset($STAGE_COLORS[$stage_main]) ? $STAGE_COLORS[$stage_main] : '#6366f1';
            $is_copied = in_array((int)$hw['id'], $copied_ids, true);
          ?>
          <tr data-hwid="<?php echo (int)$hw['id']; ?>" class="<?php echo $is_copied ? 'copied' : ''; ?>">
            <td><?php echo $i++; ?></td>
            <td><?php echo htmlspecialchars($hw['created_at'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
              <span class="stage-badge" style="background: <?php echo $color; ?>;">
                <?php echo htmlspecialchars($hw['stage'], ENT_QUOTES, 'UTF-8'); ?>
              </span>
            </td>
            <td><?php echo htmlspecialchars($hw['class'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($hw['teacher_name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($hw['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td style="max-width:260px;white-space:pre-wrap;"><?php echo nl2br(htmlspecialchars($hw['homework'], ENT_QUOTES, 'UTF-8')); ?></td>
            <td>
              <?php if ($hw['has_exam'] == 1): ?>
                <span class="badge badge-green">نعم</span>
              <?php else: ?>
                <span class="badge badge-red">لا</span>
              <?php endif; ?>
            </td>
            <td class="actions">
              <button type="button" onclick="copyHw(<?php echo (int)$hw['id']; ?>, `<?php echo str_replace('`','\`', htmlspecialchars($hw['homework'], ENT_QUOTES, 'UTF-8')); ?>`)">📋 نسخ</button>
              <a href="homework_report.php?d=<?php echo $sel_date; ?>&del=<?php echo $hw['id']; ?>" onclick="return confirm('هل تريد حذف هذا الواجب؟');">🗑 حذف</a>
            </td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- صندوق المدرسين الذين لم يرسلوا -->
  <div id="missingBox">
    <table style="width:100%;border-collapse:collapse;">
      <thead>
        <tr>
          <th>#</th>
          <th>اسم المدرس</th>
          <th>المادة</th>
          <th>الصفوف / المراحل</th>
          <th>ملاحظة</th>
        </tr>
      </thead>
      <tbody>
      <?php if ($missing_count == 0): ?>
        <tr>
          <td colspan="5" style="text-align:center;color:#ddd;padding:10px 0;">لا توجد بيانات في هذا اليوم.</td>
        </tr>
      <?php else: ?>
        <?php $j=1; foreach ($missing as $m): ?>
          <tr>
            <td><?php echo $j++; ?></td>
            <td><?php echo htmlspecialchars($m['teacher_name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($m['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
              <?php
                $stg = isset($m['stages']) ? trim($m['stages']) : '';
                $cls = isset($m['classes']) ? trim($m['classes']) : '';
                if ($stg == '' && $cls == '') {
                    echo '—';
                } else {
                    if ($stg != '') echo htmlspecialchars($stg, ENT_QUOTES, 'UTF-8');
                    if ($stg != '' && $cls != '') echo ' — ';
                    if ($cls != '') echo htmlspecialchars($cls, ENT_QUOTES, 'UTF-8');
                }
              ?>
            </td>
            <td><?php echo htmlspecialchars($m['note'], ENT_QUOTES, 'UTF-8'); ?></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- صندوق إحصائية الامتحان -->
  <div id="examsBox">
    <table style="width:100%;border-collapse:collapse;">
      <thead>
        <tr>
          <th>#</th>
          <th>اسم المدرس</th>
          <th>المادة</th>
          <th>المرحلة (كل المراحل التي امتحنها)</th>
          <th>الشعبة (كل الشعب التي امتحنها)</th>
          <th>عدد الامتحانات اليومية (طوال العام)</th>
        </tr>
      </thead>
      <tbody>
      <?php if (count($exam_stats) == 0): ?>
        <tr>
          <td colspan="6" style="text-align:center;color:#ddd;padding:10px 0;">لا توجد بيانات محفوظة بعد.</td>
        </tr>
      <?php else: ?>
        <?php $k=1; foreach ($exam_stats as $ex): ?>
          <tr>
            <td><?php echo $k++; ?></td>
            <td><?php echo htmlspecialchars($ex['teacher_name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($ex['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo $ex['stages'] ? htmlspecialchars($ex['stages'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
            <td><?php echo $ex['classes'] ? htmlspecialchars($ex['classes'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
            <td><?php echo (int)$ex['total_exams']; ?></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

</div>

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

<script>
function copyHw(id, text){
  // أولاً: نسخ النص
  const doMark = function() {
    // ثانياً: نعلّم بالسيرفر إنه تم النسخ
    fetch('homework_report.php?d=<?php echo $sel_date; ?>', {
      method: 'POST',
      headers: {'Content-Type':'application/x-www-form-urlencoded'},
      body: 'action=mark_copied&hw_id=' + encodeURIComponent(id) + '&d=<?php echo $sel_date; ?>'
    }).then(r => r.text()).then(function(res){
      if(res.trim() === 'ok'){
        // نغير لون الصف
        var row = document.querySelector('tr[data-hwid="'+id+'"]');
        if(row){
          row.classList.add('copied');
        }
      }
    });
  };

  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(function(){
      alert('✅ تم نسخ الواجب.');
      doMark();
    }, function(){
      alert('⚠️ لم يتم النسخ، انسخه يدويًا.');
      doMark();
    });
  } else {
    var ta = document.createElement('textarea');
    ta.value = text;
    document.body.appendChild(ta);
    ta.select();
    document.execCommand('copy');
    document.body.removeChild(ta);
    alert('✅ تم نسخ الواجب.');
    doMark();
  }
}
function toggleMissing(){
  var box = document.getElementById('missingBox');
  box.style.display = (box.style.display === 'none' || box.style.display === '') ? 'block' : 'none';
}
function toggleExams(){
  var box = document.getElementById('examsBox');
  box.style.display = (box.style.display === 'none' || box.style.display === '') ? 'block' : 'none';
}
</script>

</body>
</html>
