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

/*
  ======================================================
  ✅ التحقق من تسجيل دخول المدرّس
  ======================================================
*/
if (!isset($_SESSION['teacher_id'])) {
    header("Location: login.php");
    exit();
}

/*
  ======================================================
  ✅ بيانات المدرس من الجلسة (بدون ??)
  ======================================================
*/
$teacher_id      = isset($_SESSION['teacher_id']) ? (int)$_SESSION['teacher_id'] : 0;
$teacher_name    = isset($_SESSION['teacher_name']) ? $_SESSION['teacher_name'] : 'مدرّس';
$teacher_subject = isset($_SESSION['teacher_subject']) ? $_SESSION['teacher_subject'] : '';
$teacher_stages  = isset($_SESSION['teacher_stages']) ? $_SESSION['teacher_stages'] : '';
$teacher_classes = isset($_SESSION['teacher_classes']) ? $_SESSION['teacher_classes'] : '';

/*
  ======================================================
  ✅ الشعب الافتراضية
  ======================================================
*/
$DEFAULT_CLASSES = array('A','B','C','D','E','F');

/*
  ======================================================
  ✅ جلب الشعب الحقيقية من جدول الطلاب
  ======================================================
*/
function getClassesByStage($conn) {
    $map = array();
    $sql = "SELECT TRIM(stage) AS stage, TRIM(class) AS class
            FROM students
            WHERE TRIM(stage) <> '' AND TRIM(class) <> ''
            GROUP BY TRIM(stage), TRIM(class)
            ORDER BY TRIM(stage), TRIM(class)";
    $res = mysqli_query($conn, $sql);
    if ($res) {
        while ($r = mysqli_fetch_assoc($res)) {
            $st = $r['stage'];
            $cl = $r['class'];
            if (!isset($map[$st])) {
                $map[$st] = array();
            }
            if (!in_array($cl, $map[$st], true)) {
                $map[$st][] = $cl;
            }
        }
    }
    return $map;
}

// نحاول نطابق اسم المرحلة اللي بالسيشن مع اسم المرحلة في جدول الطلاب
function matchStageKey($stageMap, $teacherStage) {
    $teacherStage = trim($teacherStage);
    if ($teacherStage === '') return null;

    if (isset($stageMap[$teacherStage])) {
        return $teacherStage;
    }

    $norm = function($s) {
        $s = trim($s);
        $s = preg_replace('/\s+/', '', $s);
        $s = preg_replace('/^ال/u', '', $s);
        return $s;
    };
    $tNorm = $norm($teacherStage);

    foreach ($stageMap as $k => $v) {
        $kNorm = $norm($k);
        if (mb_stripos($kNorm, $tNorm) !== false || mb_stripos($tNorm, $kNorm) !== false) {
            return $k;
        }
    }
    return null;
}

function getStageClasses($stageMap, $teacherStage, $fallback) {
    $key = matchStageKey($stageMap, $teacherStage);
    if ($key !== null && isset($stageMap[$key]) && count($stageMap[$key]) > 0) {
        return $stageMap[$key];
    }
    return $fallback;
}

$stage_classes_map = getClassesByStage($conn);

/*
  ======================================================
  ✅ إنشاء الجداول (مرة وحدة)
  ======================================================
*/
mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `homeworks` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `teacher_id` INT(11) NOT NULL,
  `teacher_name` VARCHAR(150) NOT NULL,
  `subject` VARCHAR(150) DEFAULT NULL,
  `stage` VARCHAR(100) NOT NULL,
  `class` VARCHAR(100) NOT NULL,
  `homework` TEXT,
  `has_exam` TINYINT(1) DEFAULT 0,
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `idx_stage_class_date` (`stage`,`class`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `homework_daily_status` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `teacher_id` INT(11) NOT NULL,
  `teacher_name` VARCHAR(150) NOT NULL,
  `subject` VARCHAR(150) DEFAULT NULL,
  `hw_date` DATE NOT NULL,
  `sent_count` INT(11) NOT NULL DEFAULT 0,
  `exam_count` INT(11) NOT NULL DEFAULT 0,
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_teacher_day` (`teacher_id`,`hw_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

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) NOT NULL,
  `subject` VARCHAR(150) DEFAULT NULL,
  `note` VARCHAR(255) DEFAULT NULL,
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `idx_date` (`hw_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/*
  ======================================================
  ✅ تجهيز المراحل/الشعب من السيشن
  ======================================================
*/
$groups = array();

if ($teacher_classes != '') {
    $parts = explode(',', $teacher_classes);
    $last_stage = '';
    foreach ($parts as $p) {
        $p = trim($p);
        if ($p == '') continue;

        if (strpos($p, ':') !== false) {
            list($stg, $clsStr) = explode(':', $p, 2);
            $stg    = trim($stg);
            $clsStr = trim($clsStr);
            $last_stage = $stg;
            $clsStr = str_replace('،', ',', $clsStr);

            if ($clsStr == '' || $clsStr == 'جميع الشعب' || $clsStr == 'جميع الصفوف') {
                $groups[] = array('stage' => $stg, 'class' => 'جميع الشعب');
            } else {
                $clsList = explode(',', $clsStr);
                foreach ($clsList as $c) {
                    $c = trim($c);
                    if ($c == '') continue;
                    $groups[] = array('stage' => $stg, 'class' => $c);
                }
            }
        } else {
            if ($last_stage != '') {
                $groups[] = array('stage' => $last_stage, 'class' => $p);
            } else {
                $groups[] = array('stage' => $p, 'class' => 'جميع الشعب');
            }
        }
    }
} else {
    if ($teacher_stages != '') {
        $stgs = explode(',', $teacher_stages);
        foreach ($stgs as $st) {
            $st = trim($st);
            if ($st == '') continue;
            $groups[] = array('stage' => $st, 'class' => 'جميع الشعب');
        }
    }
}

if (count($groups) == 0) {
    $groups[] = array('stage' => 'غير محدد', 'class' => 'جميع الشعب');
}

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

    $today_esc = mysqli_real_escape_string($conn, $today_date);
    mysqli_query($conn, "DELETE FROM homework_missing_teachers WHERE hw_date = '".$today_esc."'");

    $sent_teachers = array();
    $rSent = mysqli_query($conn, "
        SELECT DISTINCT teacher_id
        FROM homeworks
        WHERE DATE(created_at) = '".$today_esc."'
    ");
    if ($rSent) {
        while ($row = mysqli_fetch_assoc($rSent)) {
            $sent_teachers[] = (int)$row['teacher_id'];
        }
    }

    foreach ($teachers as $t) {
        $tid   = $t['id'];
        $tname = mysqli_real_escape_string($conn, $t['name']);
        $tsub  = mysqli_real_escape_string($conn, $t['subject']);
        $hasSent = in_array($tid, $sent_teachers, true);

        if (!$hasSent) {
            mysqli_query($conn, "
                INSERT INTO homework_missing_teachers
                    (hw_date, teacher_id, teacher_name, subject, note, created_at)
                VALUES
                    ('".$today_esc."', ".($tid > 0 ? $tid : "NULL").", '".$tname."', '".$tsub."', 'لم يرسل الواجب حتى الآن', NOW())
            ");
        }
    }
}

/*
  ======================================================
  ✅ معالجة الإرسال
  ======================================================
*/
$message = '';
$error   = '';
$MAX_DAILY_EXAMS = 2;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['rows']) && is_array($_POST['rows'])) {
        $rows = $_POST['rows'];
        $blocked   = array();
        $validRows = array();
        $examChoiceMissing = false;

        foreach ($rows as $row) {
            $row_stage = isset($row['stage']) ? trim($row['stage']) : '';

            // حالة جميع الشعب
            if (isset($row['multi']) && is_array($row['multi'])) {
                foreach ($row['multi'] as $clsName => $sub) {
                    $clsName = trim($clsName);
                    $hw      = isset($sub['homework']) ? trim($sub['homework']) : '';
                    $exam    = isset($sub['exam']) ? trim($sub['exam']) : '';

                    // لو فاضي كله تجاهله
                    if ($hw === '' && $exam === '') {
                        continue;
                    }

                    // لو كتب واجب وما اختار امتحان
                    if ($hw !== '' && $exam === '') {
                        $examChoiceMissing = true;
                        // نكمل وما نضيف هذا السطر
                        continue;
                    }

                    // لو امتحان = نعم نتحقق من الحد الأقصى
                    if ($exam === 'نعم') {
                        $stg_esc = mysqli_real_escape_string($conn, $row_stage);
                        $cls_esc = mysqli_real_escape_string($conn, $clsName);
                        $today   = date('Y-m-d');

                        $q = "
                            SELECT teacher_name, subject, class
                            FROM homeworks
                            WHERE stage = '$stg_esc'
                              AND DATE(created_at) = '$today'
                              AND has_exam = 1
                              AND (class = '$cls_esc' OR class = 'جميع الشعب')
                        ";
                        $res = mysqli_query($conn, $q);
                        $currentCount = 0;
                        $prevTeachers = array();
                        if ($res) {
                            while ($r = mysqli_fetch_assoc($res)) {
                                $currentCount++;
                                $tName = isset($r['teacher_name']) ? $r['teacher_name'] : '';
                                $tSub  = isset($r['subject']) ? $r['subject'] : '';
                                $tCls  = isset($r['class']) ? $r['class'] : '';
                                if ($tName != '') {
                                    $label = $tName;
                                    if ($tSub != '') $label .= " ($tSub)";
                                    if ($tCls == 'جميع الشعب') $label .= " [جميع الشعب]";
                                    $prevTeachers[] = $label;
                                }
                            }
                        }

                        if ($currentCount >= $MAX_DAILY_EXAMS) {
                            $blocked[] = array(
                                'stage'    => $row_stage,
                                'class'    => $clsName,
                                'teachers' => $prevTeachers
                            );
                            // ما نضيفه
                            continue;
                        }
                    }

                    // هذا السطر صالح
                    $validRows[] = array(
                        'stage'    => $row_stage,
                        'class'    => $clsName,
                        'homework' => $hw,
                        'exam'     => $exam
                    );
                }
            } else {
                // شعبة محددة
                $stg   = $row_stage;
                $cls   = isset($row['class']) ? trim($row['class']) : '';
                $hw    = isset($row['homework']) ? trim($row['homework']) : '';
                $exam  = isset($row['exam']) ? trim($row['exam']) : '';

                if ($hw === '' && $exam === '') {
                    continue;
                }

                if ($hw !== '' && $exam === '') {
                    $examChoiceMissing = true;
                    continue;
                }

                if ($exam === 'نعم') {
                    $stg_esc = mysqli_real_escape_string($conn, $stg);
                    $cls_esc = mysqli_real_escape_string($conn, $cls);
                    $today   = date('Y-m-d');

                    $q = "
                        SELECT teacher_name, subject, class
                        FROM homeworks
                        WHERE stage = '$stg_esc'
                          AND DATE(created_at) = '$today'
                          AND has_exam = 1
                          AND (class = '$cls_esc' OR class = 'جميع الشعب')
                    ";
                    $res = mysqli_query($conn, $q);
                    $currentCount = 0;
                    $prevTeachers = array();
                    if ($res) {
                        while ($r = mysqli_fetch_assoc($res)) {
                            $currentCount++;
                            $tName = isset($r['teacher_name']) ? $r['teacher_name'] : '';
                            $tSub  = isset($r['subject']) ? $r['subject'] : '';
                            $tCls  = isset($r['class']) ? $r['class'] : '';
                            if ($tName != '') {
                                $label = $tName;
                                if ($tSub != '') $label .= " ($tSub)";
                                if ($tCls == 'جميع الشعب') $label .= " [جميع الشعب]";
                                $prevTeachers[] = $label;
                            }
                        }
                    }

                    if ($currentCount >= $MAX_DAILY_EXAMS) {
                        $blocked[] = array(
                            'stage'    => $stg,
                            'class'    => $cls,
                            'teachers' => $prevTeachers
                        );
                        continue;
                    }
                }

                $validRows[] = array(
                    'stage'   => $stg,
                    'class'   => $cls,
                    'homework'=> $hw,
                    'exam'    => $exam
                );
            }
        }

        // 🔴 هنا التعديل المهم:
        // لا نمسح $validRows حتى لو في صفوف ناقصة اختيار الامتحان
        if ($examChoiceMissing) {
            $error = "⚠️ تم تجاهل بعض الواجبات لأنك لم تختر (هل يوجد امتحان يومي؟) لها.";
        }

        // لو في شعب تجاوزت الحد الأقصى للامتحان
        if (count($blocked) > 0) {
            $txt = "❌ لا يمكن إضافة الامتحان اليومي لبعض الشعب لأن الحد الأقصى ($MAX_DAILY_EXAMS) تم بلوغه اليوم:<br>";
            foreach ($blocked as $b) {
                $txt .= "- " . htmlspecialchars($b['stage'], ENT_QUOTES, 'UTF-8') . " / " . htmlspecialchars($b['class'], ENT_QUOTES, 'UTF-8');
                if (count($b['teachers']) > 0) {
                    $txt .= " — سبق أن سجّل الامتحان: " . htmlspecialchars(implode("، ", $b['teachers']), ENT_QUOTES, 'UTF-8');
                }
                $txt .= "<br>";
            }
            $txt .= "<br>✅ أرسل الواجب بدون امتحان لهذه الشعب.";
            $error = ($error == '') ? $txt : $error . "<br><br>" . $txt;
        }

        // الآن نحفظ الأسطر السليمة فقط
        if (count($validRows) > 0) {
            foreach ($validRows as $vr) {
                $stg_esc = mysqli_real_escape_string($conn, $vr['stage']);
                $cls_esc = mysqli_real_escape_string($conn, $vr['class']);
                $hw_esc  = mysqli_real_escape_string($conn, $vr['homework']);
                $examVal = ($vr['exam'] === 'نعم') ? 1 : 0;

                $tname_esc = mysqli_real_escape_string($conn, $teacher_name);
                $tsubj_esc = mysqli_real_escape_string($conn, $teacher_subject);

                $ins = "
                    INSERT INTO homeworks
                        (teacher_id, teacher_name, subject, stage, class, homework, has_exam, created_at)
                    VALUES
                        ($teacher_id, '$tname_esc', '$tsubj_esc', '$stg_esc', '$cls_esc', '$hw_esc', $examVal, NOW())
                ";
                mysqli_query($conn, $ins);
            }

            // تحديث إحصائية هذا المدرس لليوم
            $today = date('Y-m-d');
            $resCount = mysqli_query($conn, "
                SELECT 
                    COUNT(*) AS total_hw,
                    SUM(CASE WHEN has_exam = 1 THEN 1 ELSE 0 END) AS total_exam
                FROM homeworks
                WHERE teacher_id = $teacher_id
                  AND DATE(created_at) = '$today'
            ");
            $total_hw = 0;
            $total_exam = 0;
            if ($resCount && mysqli_num_rows($resCount) > 0) {
                $rowC = mysqli_fetch_assoc($resCount);
                $total_hw   = isset($rowC['total_hw']) ? (int)$rowC['total_hw'] : 0;
                $total_exam = isset($rowC['total_exam']) ? (int)$rowC['total_exam'] : 0;
            }

            $tname_esc = mysqli_real_escape_string($conn, $teacher_name);
            $tsubj_esc = mysqli_real_escape_string($conn, $teacher_subject);

            mysqli_query($conn, "
                INSERT INTO homework_daily_status (teacher_id, teacher_name, subject, hw_date, sent_count, exam_count)
                VALUES ($teacher_id, '$tname_esc', '$tsubj_esc', '$today', $total_hw, $total_exam)
                ON DUPLICATE KEY UPDATE
                    teacher_name = VALUES(teacher_name),
                    subject = VALUES(subject),
                    sent_count = VALUES(sent_count),
                    exam_count = VALUES(exam_count)
            ");

            // نحدّث جدول اللي ما أرسلوا
            update_missing_teachers($conn, $today);

            if ($error == '') {
                $message = "✅ تم إرسال الواجبات بنجاح.";
            } else {
                $message = "✅ تم حفظ الواجبات المكتملة.";
            }
        } else {
            if ($error == '') {
                $error = "⚠️ لم يتم إرسال أي واجب.";
            }
        }

    } else {
        $error = "⚠️ البيانات غير مكتملة.";
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>الواجبات المدرسية | ثانوية الأوائل الأهلية للبنين</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-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.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;
  gap:10px;
  padding:16px 20px;
  background:rgba(255,255,255,0.06);
  border-bottom:1px solid rgba(255,255,255,0.1);
  backdrop-filter:blur(10px);
}
header .title-block{
  display:flex;
  align-items:center;
  gap:12px;
}
header img{height:46px;border-radius:12px;box-shadow:0 0 10px rgba(0,255,255,0.5);}
header h1{font-size:18px;margin:0}
header .school{font-size:12px;color:#00e6ff}
header .btn{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  color:#fff;
  padding:7px 14px;
  border-radius:10px;
  text-decoration:none;
  font-weight:600;
  transition:0.3s;
  white-space:nowrap;
}
header .btn:hover{transform:scale(1.05)}
.container{
  width:100%;
  max-width:1100px;
  margin:25px auto 60px;
  padding:0 15px;
}
.top-info{
  background:rgba(255,255,255,0.04);
  border:1px solid rgba(255,255,255,0.05);
  border-radius:16px;
  padding:15px 15px 10px;
  margin-bottom:20px;
  box-shadow:0 0 20px rgba(0,255,255,0.05);
}
.top-info h2{
  font-size:20px;
  margin-bottom:5px;
  color:#00e6ff;
}
.top-info p{font-size:14px;color:#ddd;margin-bottom:4px}
.alert{
  margin-bottom:15px;
  padding:10px 12px;
  border-radius:12px;
  font-size:13px;
  line-height:1.5;
}
.alert-success{background:rgba(0,255,135,0.08);border:1px solid rgba(0,255,135,0.4);}
.alert-danger{background:rgba(255,0,74,0.08);border:1px solid rgba(255,0,74,0.4);}

.hw-block{
  background:rgba(255,255,255,0.03);
  border:1px solid rgba(255,255,255,0.03);
  border-radius:16px;
  padding:14px 14px 12px;
  margin-bottom:16px;
  box-shadow:0 0 10px rgba(0,0,0,0.12);
}
.hw-head{
  display:flex;
  justify-content:space-between;
  align-items:flex-start;
  gap:14px;
  margin-bottom:8px;
  flex-wrap:wrap;
}
.hw-title{
  font-weight:600;
  font-size:14px;
}
.hw-small{
  font-size:12px;
  color:#aaa;
}
.hw-actions{
  display:flex;
  gap:6px;
  flex-wrap:wrap;
}
textarea{
  width:100%;
  min-height:80px;
  background:rgba(0,0,0,0.2);
  border:1px solid rgba(255,255,255,0.07);
  border-radius:10px;
  padding:8px;
  color:#fff;
  font-family:'Tajawal',sans-serif;
  margin-bottom:8px;
  font-size:13px;
}
select{
  width:180px;
  background:rgba(0,0,0,0.3);
  border:1px solid rgba(255,255,255,0.07);
  border-radius:10px;
  padding:6px 8px;
  color:#fff;
  font-family:'Tajawal',sans-serif;
  font-size:13px;
}
.send-btn{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  border:none;
  border-radius:14px;
  padding:11px 45px;
  color:#fff;
  font-weight:700;
  font-size:14px;
  cursor:pointer;
  margin-top:15px;
  transition:0.3s;
  display:inline-block;
}
.send-btn:hover{transform:translateY(-2px);box-shadow:0 0 20px rgba(0,255,255,0.25);}

.notes{
  margin-top:12px;
  background:rgba(0,0,0,0.25);
  border:1px solid rgba(255,255,255,0.03);
  border-radius:12px;
  padding:10px;
  font-size:12px;
  color:#ccc;
  line-height:1.5;
}

.multi-classes-grid{
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(160px,1fr));
  gap:10px;
  margin-top:8px;
}
.multi-class-card{
  background:rgba(0,0,0,0.18);
  border:1px solid rgba(255,255,255,0.03);
  border-radius:10px;
  padding:8px;
}
.multi-class-card-top{
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:6px;
  margin-bottom:4px;
}
.multi-class-card label{
  font-size:12px;
  color:#fff;
}
.multi-class-card textarea{
  min-height:60px;
  font-size:12px;
}
.multi-class-card select{
  width:100%;
  font-size:12px;
}

.paste-btn,
.copy-btn{
  background:linear-gradient(90deg,#00e6ff,#007bff);
  border:none;
  border-radius:10px;
  padding:4px 10px;
  color:#fff;
  font-weight:700;
  font-size:12px;
  cursor:pointer;
  opacity:0.95;
  transition:0.2s;
  box-shadow:0 4px 10px rgba(0,0,0,0.2);
}
.copy-btn:hover,
.paste-btn:hover{
  opacity:1;
  transform:translateY(-1px);
}

.copy-toast{
  display:none;
  position:fixed;
  bottom:20px;
  left:20px;
  background:linear-gradient(90deg,#00e6ff,#007bff);
  color:#fff;
  padding:8px 14px;
  border-radius:10px;
  font-size:13px;
  box-shadow:0 4px 16px rgba(0,0,0,0.25);
  z-index:9999;
}

footer{
  text-align:center;
  padding:12px;
  font-size:12px;
  color:#aaa;
  background:rgba(255,255,255,0.02);
}

@media(max-width:768px){
  header{flex-wrap:wrap}
  .hw-head{flex-direction:column;align-items:flex-start}
  select{width:100%}
  .multi-classes-grid{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));}
  .send-btn{width:100%;text-align:center}
}
@media(max-width:480px){
  header{align-items:flex-start}
  .multi-classes-grid{grid-template-columns:1fr;}
  .container{padding:0 10px;}
}
</style>
</head>
<body>

<header>
  <div class="title-block">
    <img src="logo.png" alt="logo">
    <div>
      <h1>ثانوية الأوائل الأهلية للبنين</h1>
      <div class="school">الواجبات المدرسية</div>
    </div>
  </div>
  <a href="dashboard_teacher.php" class="btn">↩ العودة للوحة</a>
</header>

<div class="container">
  <div class="top-info">
    <h2>
      <?php
        echo htmlspecialchars($teacher_name, ENT_QUOTES, 'UTF-8');
        if ($teacher_subject != '') {
            echo " (" . htmlspecialchars($teacher_subject, ENT_QUOTES, 'UTF-8') . ")";
        }
      ?>
    </h2>
    <p>من هذه الصفحة تستطيع إرسال الواجبات لكل مرحلة/شعبة مرتبطة باسمك.</p>
    <?php if ($teacher_stages != ''): ?>
      <p>المراحل: <?php echo htmlspecialchars($teacher_stages, ENT_QUOTES, 'UTF-8'); ?></p>
    <?php endif; ?>
    <?php if ($teacher_classes != ''): ?>
      <p>الشعب: <?php echo htmlspecialchars($teacher_classes, ENT_QUOTES, 'UTF-8'); ?></p>
    <?php endif; ?>
    <p style="font-size:11px;color:#ffdf9c;margin-top:5px">
      🔔 ملاحظة: أقصى عدد للامتحان اليومي لنفس المرحلة والشعبة في اليوم هو <?php echo $MAX_DAILY_EXAMS; ?>.
    </p>
  </div>

  <?php if ($message != ''): ?>
    <div class="alert alert-success"><?php echo $message; ?></div>
  <?php endif; ?>
  <?php if ($error != ''): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
  <?php endif; ?>

  <form id="hwForm" method="post">
    <?php
    $i = 0;
    foreach ($groups as $g):
      $stg = $g['stage'];
      $cls = $g['class'];
      $label = $stg . ' ' . ($cls == 'جميع الشعب' ? '' : $cls);
    ?>
    <div class="hw-block">
      <div class="hw-head">
        <div>
          <div class="hw-title"><?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?></div>
          <div class="hw-small">
            واجب مادة
            <?php
              if ($teacher_subject != '') {
                echo htmlspecialchars($teacher_subject, ENT_QUOTES, 'UTF-8');
              } else {
                echo "المادة";
              }
              if ($cls == 'جميع الشعب') {
                echo " (اختر الشعب بالأسفل)";
              } else {
                echo " للشعبة " . htmlspecialchars($cls, ENT_QUOTES, 'UTF-8');
              }
            ?>
          </div>
        </div>

        <?php if ($cls !== 'جميع الشعب'): ?>
          <div>
            <label style="font-size:12px;margin-bottom:3px;display:block;">📘 هل يوجد امتحان يومي؟</label>
            <select name="rows[<?php echo $i; ?>][exam]" class="exam-select" data-textarea="hw<?php echo $i; ?>">
              <option value="">اختر...</option>
              <option value="نعم">نعم</option>
              <option value="لا">لا</option>
            </select>
          </div>
        <?php else: ?>
          <div style="font-size:11px;color:#ccc;">اختر الشعب وحدّد الامتحان لكل شعبة</div>
        <?php endif; ?>

        <div class="hw-actions">
          <?php if ($cls !== 'جميع الشعب'): ?>
            <button type="button" class="paste-btn" data-target="hw<?php echo $i; ?>">لصق</button>
            <button type="button" class="copy-btn" data-target="hw<?php echo $i; ?>">نسخ</button>
          <?php endif; ?>
        </div>
      </div>

      <?php if ($cls !== 'جميع الشعب'): ?>
        <textarea id="hw<?php echo $i; ?>" name="rows[<?php echo $i; ?>][homework]" placeholder="اكتب الواجب هنا..."></textarea>
        <input type="hidden" name="rows[<?php echo $i; ?>][stage]" value="<?php echo htmlspecialchars($stg, ENT_QUOTES, 'UTF-8'); ?>">
        <input type="hidden" name="rows[<?php echo $i; ?>][class]" value="<?php echo htmlspecialchars($cls, ENT_QUOTES, 'UTF-8'); ?>">
      <?php else: ?>
        <input type="hidden" name="rows[<?php echo $i; ?>][stage]" value="<?php echo htmlspecialchars($stg, ENT_QUOTES, 'UTF-8'); ?>">

        <?php $available_classes = getStageClasses($stage_classes_map, $stg, $DEFAULT_CLASSES); ?>
        <div class="multi-classes-grid">
          <?php foreach ($available_classes as $dc): ?>
            <div class="multi-class-card">
              <div class="multi-class-card-top">
                <label>الشعبة <?php echo htmlspecialchars($dc, ENT_QUOTES, 'UTF-8'); ?></label>
                <div class="hw-actions">
                  <button type="button" class="paste-btn" data-target="hw<?php echo $i . '_' . $dc; ?>">لصق</button>
                  <button type="button" class="copy-btn" data-target="hw<?php echo $i . '_' . $dc; ?>">نسخ</button>
                </div>
              </div>
              <textarea id="hw<?php echo $i . '_' . $dc; ?>" name="rows[<?php echo $i; ?>][multi][<?php echo $dc; ?>][homework]" placeholder="واجب الشعبة <?php echo htmlspecialchars($dc, ENT_QUOTES, 'UTF-8'); ?>"></textarea>
              <select name="rows[<?php echo $i; ?>][multi][<?php echo $dc; ?>][exam]" class="exam-select" data-textarea="hw<?php echo $i . '_' . $dc; ?>">
                <option value="">امتحان يومي؟</option>
                <option value="نعم">نعم</option>
                <option value="لا">لا</option>
              </select>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
    <?php
      $i++;
    endforeach;
    ?>

    <button type="submit" class="send-btn">📩 إرسال الواجب</button>

    <div class="notes">
      <b>📌 ملاحظات:</b><br>
      - لو كتبت واجب لازم تختار (نعم/لا) للامتحان، وإلا راح يتجاهل هذا السطر فقط.<br>
      - تقدر تستخدم نسخ/لصق عالسريع بين الشعب.<br>
      - النظام يمنع أكثر من <?php echo $MAX_DAILY_EXAMS; ?> امتحان يومي لنفس الشعبة في اليوم.
    </div>
  </form>
</div>

<div id="toast" class="copy-toast">✅ تم نسخ النص</div>

<footer>
  © <?php echo date("Y"); ?> جميع الحقوق محفوظة — ثانوية الأوائل الأهلية للبنين
</footer>

<script>
// دالة النسخ
function copyById(id){
  var ta = document.getElementById(id);
  if (!ta) return;
  ta.select();
  ta.setSelectionRange(0, 99999);
  try {
    document.execCommand('copy');
  } catch(e) {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(ta.value);
    }
  }
  var t = document.getElementById('toast');
  t.innerHTML = '✅ تم نسخ النص';
  t.style.display = 'block';
  clearTimeout(window.__toastTimer);
  window.__toastTimer = setTimeout(function(){ t.style.display = 'none'; }, 1400);
}

// دالة اللصق
function pasteToId(id){
  var ta = document.getElementById(id);
  if (!ta) return;

  if (navigator.clipboard && navigator.clipboard.readText) {
    navigator.clipboard.readText().then(function(text){
      ta.value = text;
      var t = document.getElementById('toast');
      t.innerHTML = '✅ تم اللصق';
      t.style.display = 'block';
      clearTimeout(window.__toastTimer);
      window.__toastTimer = setTimeout(function(){ t.style.display = 'none'; }, 1400);
    }).catch(function(){
      var txt = prompt('📋 ألصق النص هنا:', '');
      if (txt !== null) {
        ta.value = txt;
      }
    });
  } else {
    var txt = prompt('📋 ألصق النص هنا:', '');
    if (txt !== null) {
      ta.value = txt;
    }
  }
}

// تطبيق النسخ/اللصق
document.addEventListener('click', function(e){
  var copyBtn = e.target.closest('.copy-btn');
  if (copyBtn && copyBtn.getAttribute('data-target')) {
    copyById(copyBtn.getAttribute('data-target'));
  }
  var pasteBtn = e.target.closest('.paste-btn');
  if (pasteBtn && pasteBtn.getAttribute('data-target')) {
    pasteToId(pasteBtn.getAttribute('data-target'));
  }
});

// ✅ منع الإرسال من الواجهة لو في واجب مكتوب بدون اختيار امتحان
document.getElementById('hwForm').addEventListener('submit', function(e){
  var valid = true;
  var msg = '';
  var textareas = this.querySelectorAll('textarea[id]');
  for (var i=0; i<textareas.length; i++) {
    var ta = textareas[i];
    var val = ta.value.trim();
    if (val !== '') {
      var sel = this.querySelector('select.exam-select[data-textarea="'+ta.id+'"]');
      if (sel && sel.value === '') {
        valid = false;
        msg = 'يجب اختيار (هل يوجد امتحان يومي؟) لكل واجب كتبته.';
        break;
      }
    }
  }
  if (!valid) {
    alert(msg);
    e.preventDefault();
  }
});
</script>

</body>
</html>
