<?php
/*
مختصر التعديلات:
- تسجيل "تم الاطلاع" تلقائياً عند ظهور الكارت (IntersectionObserver + action=mark_read).
- إبقاء زر "تم الاطلاع"/"تم التأكيد" كخيار إضافي؛ كلاهما يحدّث is_read=1.
- عدم الاعتماد على AUTO_INCREMENT: نستخدم MAX(id)+1 كما هو.
- LEFT JOIN يعرض حالة المدرّس (is_read/is_confirmed) إن وُجد سجل.
- إزالة صندوق "تبليغات تحتاج تأكيد صريح".
- زر ↩ العودة بجانب زر تسجيل الخروج داخل الهيدر.
*/

session_start();
include 'db.php';

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

mysqli_set_charset($conn, "utf8mb4");
date_default_timezone_set('Asia/Baghdad');
$now    = date('Y-m-d H:i:s');
$now_db = mysqli_real_escape_string($conn, $now);

// ✅ بيانات المدرّس من الجلسة/قاعدة البيانات
$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  = '';
$teacher_classes = '';

$qT = mysqli_query($conn, "SELECT name, subject, stages, classes FROM teachers WHERE id = '".$teacher_id."' LIMIT 1");
if ($qT && mysqli_num_rows($qT) > 0) {
    $rowT = mysqli_fetch_assoc($qT);

    if ($teacher_name == 'مدرّس' && !empty($rowT['name'])) {
        $teacher_name = $rowT['name'];
        $_SESSION['teacher_name'] = $teacher_name;
    }
    if ($teacher_subject == '' && !empty($rowT['subject'])) {
        $teacher_subject = $rowT['subject'];
        $_SESSION['teacher_subject'] = $teacher_subject;
    }

    $teacher_stages  = isset($rowT['stages'])  ? $rowT['stages']  : '';
    $teacher_classes = isset($rowT['classes']) ? $rowT['classes'] : '';
}

/* ============================================
   ✅ إنشاء جدول admin_notification_reads إن لم يوجد
   ============================================ */
mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `admin_notification_reads` (
  `id` int(11) NOT NULL,
  `notification_id` int(11) NOT NULL,
  `teacher_id` int(11) NOT NULL,
  `is_read` tinyint(1) NOT NULL DEFAULT 0,
  `read_at` datetime DEFAULT NULL,
  `is_confirmed` tinyint(1) NOT NULL DEFAULT 0,
  `confirmed_at` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* ============================================
   ✅ دوال فلترة المطابقة
   ============================================ */
function norm_stage($s) {
    $s = trim($s);
    $s = str_replace(array('الأ','ال',' '), array('ا','', ''), $s);
    return $s;
}
function teacher_has_stage($teacher_stages, $target_stage) {
    if ($target_stage == '' || $teacher_stages == '') return false;
    $target = norm_stage($target_stage);
    $parts = preg_split('/[,،\/\-]+/u', $teacher_stages);
    if (!$parts || count($parts) == 0) $parts = array($teacher_stages);
    foreach ($parts as $p) {
        $p = trim($p);
        if ($p === '') continue;
        if (norm_stage($p) === $target) return true;
    }
    if (strpos($teacher_stages, $target_stage) !== false) return true;
    return false;
}
function teacher_has_any_class($teacher_classes, $target_classes) {
    if ($target_classes == '' || $teacher_classes == '') return true;
    $list = explode(',', $target_classes);
    foreach ($list as $c) {
        $c = trim($c);
        if ($c === '') continue;
        if (strpos($teacher_classes, $c) !== false) return true;
    }
    return false;
}
function notification_matches_teacher($row, $teacher_id, $teacher_subject, $teacher_stages, $teacher_classes) {
    $target_type    = isset($row['target_type']) ? $row['target_type'] : 'all';
    $target_stage   = isset($row['target_stage']) ? $row['target_stage'] : '';
    $target_subject = isset($row['target_subject']) ? $row['target_subject'] : '';
    $target_classes = isset($row['target_classes']) ? $row['target_classes'] : '';
    $target_ids_str = isset($row['target_teacher_ids']) ? $row['target_teacher_ids'] : '';

    switch ($target_type) {
        case 'all': default: return true;
        case 'subject':
            if ($target_subject == '' || $teacher_subject == '') return false;
            return trim($target_subject) === trim($teacher_subject);
        case 'stage':
            return teacher_has_stage($teacher_stages, $target_stage);
        case 'stage_class':
            if (!teacher_has_stage($teacher_stages, $target_stage)) return false;
            return teacher_has_any_class($teacher_classes, $target_classes);
        case 'teachers':
            if ($target_ids_str == '') return false;
            foreach (explode(',', $target_ids_str) as $id) {
                if ((int)trim($id) === (int)$teacher_id) return true;
            }
            return false;
    }
}
function get_priority_info($priority) {
    $priority = $priority ? $priority : 'normal';
    $info = array('class' => 'prio-normal','label' => 'عادي');
    switch ($priority) {
        case 'important': $info['class']='prio-important'; $info['label']='مهم'; break;
        case 'urgent':    $info['class']='prio-urgent';    $info['label']='عاجل جداً'; break;
        default:          $info['class']='prio-normal';    $info['label']='عادي'; break;
    }
    return $info;
}
function get_category_label($cat) {
    $cat = trim($cat);
    return $cat==='' ? 'عام' : $cat;
}
function get_target_label($row) {
    $type=isset($row['target_type'])?$row['target_type']:'all';
    $stg =isset($row['target_stage'])?$row['target_stage']:'';
    $sub =isset($row['target_subject'])?$row['target_subject']:'';
    $cls =isset($row['target_classes'])?$row['target_classes']:'';
    switch ($type) {
        case 'all': default: return 'موجّه لجميع الكادر التدريسي';
        case 'stage': return 'موجّه لمدرّسي مرحلة: '.($stg!=''?$stg:'غير محددة');
        case 'subject': return 'موجّه لمدرّسي مادة: '.($sub!=''?$sub:'غير محددة');
        case 'stage_class':
            $txt='موجّه لمدرّسي '.($stg!=''?$stg:'مرحلة غير محددة');
            if ($cls!='') $txt.=' — الشُعب: '.$cls;
            return $txt;
        case 'teachers': return 'موجّه لمدرّسين محدّدين بالاسم';
    }
}

/* ============================================
   ✅ طلبات AJAX (mark_read / confirm_notification)
   ============================================ */
if (isset($_POST['action'])) {
    $act = $_POST['action'];
    $notif_id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

    if ($teacher_id > 0 && $notif_id > 0) {
        if ($act === 'mark_read') {
            $now = date('Y-m-d H:i:s');
            $qR = mysqli_query($conn, "SELECT id, is_read FROM admin_notification_reads WHERE notification_id=".$notif_id." AND teacher_id=".$teacher_id." LIMIT 1");
            if ($qR && mysqli_num_rows($qR)>0) {
                $rowR = mysqli_fetch_assoc($qR);
                $rid = (int)$rowR['id'];
                $sql = "
                    UPDATE admin_notification_reads
                    SET is_read = 1,
                        read_at = IF(read_at IS NULL OR read_at='0000-00-00 00:00:00', '$now', read_at)
                    WHERE id = ".$rid." LIMIT 1
                ";
                mysqli_query($conn, $sql);
                echo 'ok_read';
            } else {
                $max_id = 0;
                $qM = mysqli_query($conn, "SELECT MAX(id) AS m FROM admin_notification_reads");
                if ($qM && mysqli_num_rows($qM)>0) {
                    $rowM = mysqli_fetch_assoc($qM);
                    if ($rowM && $rowM['m'] !== null) $max_id = (int)$rowM['m'];
                }
                $new_id = $max_id + 1;
                $sql = "
                    INSERT INTO admin_notification_reads
                        (id, notification_id, teacher_id, is_read, read_at, is_confirmed, confirmed_at)
                    VALUES
                        ($new_id, $notif_id, $teacher_id, 1, '$now', 0, NULL)
                ";
                if (mysqli_query($conn, $sql)) echo 'ok_read'; else echo 'err:'.mysqli_error($conn);
            }
            exit();
        }

        if ($act === 'confirm_notification') {
            $qN = mysqli_query($conn, "SELECT require_confirm FROM admin_notifications WHERE id=".$notif_id." LIMIT 1");
            if ($qN && mysqli_num_rows($qN)>0) {
                $rowN = mysqli_fetch_assoc($qN);
                $req_conf = isset($rowN['require_confirm']) ? (int)$rowN['require_confirm'] : 0;
                $now = date('Y-m-d H:i:s');

                $qR = mysqli_query($conn, "SELECT id FROM admin_notification_reads WHERE notification_id=".$notif_id." AND teacher_id=".$teacher_id." LIMIT 1");
                if ($qR && mysqli_num_rows($qR)>0) {
                    $rowR = mysqli_fetch_assoc($qR);
                    $rid = (int)$rowR['id'];
                    if ($req_conf === 1) {
                        $sql = "
                            UPDATE admin_notification_reads
                            SET is_read = 1,
                                read_at = IF(read_at IS NULL OR read_at='0000-00-00 00:00:00', '$now', read_at),
                                is_confirmed = 1,
                                confirmed_at = '$now'
                            WHERE id = ".$rid." LIMIT 1
                        ";
                        mysqli_query($conn, $sql);
                        echo 'ok_confirm';
                    } else {
                        $sql = "
                            UPDATE admin_notification_reads
                            SET is_read = 1,
                                read_at = IF(read_at IS NULL OR read_at='0000-00-00 00:00:00', '$now', read_at)
                            WHERE id = ".$rid." LIMIT 1
                        ";
                        mysqli_query($conn, $sql);
                        echo 'ok_read';
                    }
                } else {
                    $max_id = 0;
                    $qM = mysqli_query($conn, "SELECT MAX(id) AS m FROM admin_notification_reads");
                    if ($qM && mysqli_num_rows($qM)>0) {
                        $rowM = mysqli_fetch_assoc($qM);
                        if ($rowM && $rowM['m'] !== null) $max_id = (int)$rowM['m'];
                    }
                    $new_id = $max_id + 1;

                    if ($req_conf === 1) {
                        $sql = "
                            INSERT INTO admin_notification_reads
                                (id, notification_id, teacher_id, is_read, read_at, is_confirmed, confirmed_at)
                            VALUES
                                ($new_id, $notif_id, $teacher_id, 1, '$now', 1, '$now')
                        ";
                        if (mysqli_query($conn, $sql)) echo 'ok_confirm'; else echo 'err:'.mysqli_error($conn);
                    } else {
                        $sql = "
                            INSERT INTO admin_notification_reads
                                (id, notification_id, teacher_id, is_read, read_at, is_confirmed, confirmed_at)
                            VALUES
                                ($new_id, $notif_id, $teacher_id, 1, '$now', 0, NULL)
                        ";
                        if (mysqli_query($conn, $sql)) echo 'ok_read'; else echo 'err:'.mysqli_error($conn);
                    }
                }
            } else {
                echo 'err';
            }
            exit();
        }
    }
}

/* ============================================
   ✅ جلب تبليغات المدرّس (مع حالة قراءته)
   ============================================ */
$notifications = array();

$sql_notifs = "
SELECT 
  n.*,
  r.is_read,
  r.is_confirmed,
  r.read_at,
  r.confirmed_at
FROM admin_notifications n
LEFT JOIN admin_notification_reads r
  ON n.id = r.notification_id
 AND r.teacher_id = ".$teacher_id."
WHERE 
  (n.valid_until IS NULL 
       OR n.valid_until = '0000-00-00' 
       OR n.valid_until >= CURDATE())
  AND (
       n.is_scheduled = 0
       OR (n.is_scheduled = 1 
           AND n.scheduled_at IS NOT NULL 
           AND n.scheduled_at <= '".$now_db."')
  )
ORDER BY n.created_at DESC
";

$qN = mysqli_query($conn, $sql_notifs);
if ($qN) {
    while ($row = mysqli_fetch_assoc($qN)) {
        if (notification_matches_teacher($row, $teacher_id, $teacher_subject, $teacher_stages, $teacher_classes)) {
            $notifications[] = $row;
        }
    }
}

$total_notifs = count($notifications);
?>
<!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.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:600; color:#fff; margin:0}
header .user{font-size:14px; color:#0ff; opacity:0.85}

/* أزرار الهيدر (يمين) */
header .actions{display:flex; align-items:center; gap:10px}
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; box-shadow:0 0 15px rgba(0,255,255,0.4);
}
header .btn:hover{transform:scale(1.05); box-shadow:0 0 20px rgba(0,255,255,0.7)}
/* خيار: تمييز زر الخروج بلون خفيف مختلف (اختياري) */
header .btn-logout{background:linear-gradient(90deg,#22c55e,#16a34a)} /* أخضر هادئ */
header .btn-back{background:linear-gradient(90deg,#00e6ff,#007bff)}  /* نفس الأزرق المعتمد */

/* ====== مقدمة ====== */
.intro{ text-align:center; margin:35px auto 10px; padding:10px 10px; max-width:900px; position:relative; z-index:2; opacity:0; animation:fadeIn 1s ease-in-out forwards;}
.intro h2{ font-size:24px; color:#00e6ff; text-shadow:0 0 15px rgba(0,255,255,0.4); margin-bottom:8px;}
.intro p{ color:#ddd; font-size:14px; line-height:1.7;}
.intro .sub{ color:#aaa; font-size:13px; margin-top:6px;}
@keyframes fadeIn{ from{opacity:0;transform:translateY(18px)} to{opacity:1;transform:translateY(0)} }

/* ====== الحاوية ====== */
.main-wrap{ width:100%; max-width:1100px; margin:10px auto 40px; padding:0 20px 30px;}

/* ====== الإحصائيات ====== */
.stats-bar{ display:flex; flex-wrap:wrap; gap:10px; margin-bottom:15px;}
.stat-box{ flex:1; min-width:180px; background:rgba(15,23,42,0.9); border-radius:14px; padding:10px 14px; border:1px solid rgba(148,163,184,0.6); box-shadow:0 10px 30px rgba(15,23,42,0.8); display:flex; justify-content:space-between; align-items:center; font-size:13px;}
.stat-box span.num{ font-size:18px; font-weight:700;}
.stat-total span.num{ color:#38bdf8;}

/* ====== قائمة التبليغات ====== */
.notif-list{ margin-top:10px; display:flex; flex-direction:column; gap:14px;}
.notif-card{
  background:rgba(15,23,42,0.94); border-radius:18px; padding:14px 16px 12px; border:1px solid rgba(148,163,184,0.5);
  box-shadow:0 18px 45px rgba(15,23,42,0.9), 0 0 0 1px rgba(56,189,248,0.1);
  position:relative; overflow:hidden;
}
.notif-card::before{ content:""; position:absolute; inset:-40%; background:radial-gradient(circle at 0 0,rgba(56,189,248,0.18),transparent 55%); opacity:0; transition:opacity .4s;}
.notif-card:hover::before{ opacity:1;}
.notif-card.urgent{ border-color:rgba(248,113,113,0.8); box-shadow:0 18px 45px rgba(127,29,29,0.8), 0 0 0 1px rgba(248,113,113,0.9);}
.notif-card.confirmed{ border-color:rgba(34,197,94,0.8); box-shadow:0 18px 45px rgba(6,95,70,0.8), 0 0 0 1px rgba(34,197,94,0.7);}
.notif-header{ display:flex; justify-content:space-between; gap:8px; margin-bottom:6px;}
.notif-title-wrap{ display:flex; flex-direction:column; gap:4px;}
.cat-pill{ display:inline-flex; align-items:center; gap:5px; padding:2px 9px; border-radius:999px; font-size:11px; background:rgba(15,23,42,0.9); border:1px solid rgba(148,163,184,0.8); color:#e5e7eb;}
.cat-pill span.icon{ font-size:13px;}
.notif-title{ font-size:15px; font-weight:600;}
.notif-meta{ text-align:left; font-size:11px; display:flex; flex-direction:column; gap:4px; align-items:flex-end;}
.date-pill{ padding:2px 8px; border-radius:999px; border:1px solid rgba(148,163,184,0.7); background:rgba(15,23,42,0.9); color:#e5e7eb;}
.prio-pill{ padding:2px 8px; border-radius:999px; font-size:11px;}
.prio-normal{ background:rgba(56,189,248,0.16); color:#bfdbfe; border:1px solid rgba(56,189,248,0.7);}
.prio-important{ background:rgba(251,191,36,0.16); color:#fde68a; border:1px solid rgba(251,191,36,0.8);}
.prio-urgent{ background:rgba(248,113,113,0.16); color:#fecaca; border:1px solid rgba(248,113,113,0.85);}
.notif-body{ margin:6px 0 8px; font-size:13px; line-height:1.8; color:#e5e7eb; white-space:pre-wrap;}
.notif-footer{ display:flex; justify-content:space-between; align-items:center; gap:8px; font-size:11px; color:#cbd5f5; border-top:1px solid rgba(148,163,184,0.35); padding-top:6px;}
.target-text{ opacity:0.9;}
.footer-actions{ display:flex; gap:6px; align-items:center;}
.btn-confirm{
  padding:4px 12px; border-radius:999px; border:none; cursor:pointer; font-size:11px; font-weight:600;
  background:linear-gradient(120deg,#22c55e,#16a34a); color:#fff; box-shadow:0 0 12px rgba(34,197,94,0.7); transition:.25s; display:flex; align-items:center; gap:4px;
}
.btn-confirm:hover{ transform:translateY(-1px) scale(1.03); box-shadow:0 0 18px rgba(34,197,94,0.9);}
.status-pill{ padding:3px 8px; border-radius:999px; border:1px solid rgba(148,163,184,0.6);}
.status-new{ background:rgba(56,189,248,0.16); color:#bfdbfe; border-color:rgba(56,189,248,0.8);}
.status-wait{ background:rgba(251,191,36,0.16); color:#fde68a; border-color:rgba(251,191,36,0.9);}
.status-ok{ background:rgba(34,197,94,0.18); color:#bbf7d0; border-color:rgba(34,197,94,0.9);}
.empty-box{ margin-top:25px; text-align:center; font-size:14px; color:#e5e7eb; background:rgba(15,23,42,0.9); padding:16px; border-radius:16px; border:1px dashed rgba(148,163,184,0.7);}
footer{ text-align:center; padding:12px; font-size:12px; color:#aaa; background:rgba(255,255,255,0.04); backdrop-filter:blur(8px); border-top:1px solid rgba(255,255,255,0.08);}
footer span{ color:#00e6ff}

@media (max-width:700px){
  header{flex-direction:column;gap:8px;text-align:center}
  header .left{flex-direction:column;gap:6px}
  header .actions{flex-direction:column}
  .main-wrap{padding:0 15px 25px}
}
</style>
</head>
<body>

<header>
  <div class="left">
    <img src="logo.png" alt="logo">
    <div>
      <h1>تبليغات الإدارة للمدرّس</h1>
      <div class="user">
        مرحباً، <?php echo htmlspecialchars($teacher_name, ENT_QUOTES, 'UTF-8'); ?>
        <?php if ($teacher_subject != '') echo " — " . htmlspecialchars($teacher_subject, ENT_QUOTES, 'UTF-8'); ?>
      </div>
    </div>
  </div>
  <div class="actions">
    <a href="dashboard_teacher.php" class="btn btn-back">↩ العودة للوحة التحكم</a>
    <a href="logout.php" class="btn btn-logout">تسجيل خروج</a>
  </div>
</header>

<section class="intro">
  <h2>📢 لوحة تبليغات الإدارة</h2>
  <p>في هذه الصفحة ستجد جميع التبليغات الإدارية المرسلة لك، سواء كانت عامة، أو موجهة حسب المادة، أو المرحلة، أو الشُعب، أو موجهة لك بالاسم.</p>
  <p class="sub">
    <?php
      echo "مراحل عملك: " . ($teacher_stages != '' ? htmlspecialchars($teacher_stages, ENT_QUOTES, 'UTF-8') : 'غير مضافة');
      echo " — الشعب: " . ($teacher_classes != '' ? htmlspecialchars($teacher_classes, ENT_QUOTES, 'UTF-8') : 'غير مضافة');
    ?>
  </p>
</section>

<div class="main-wrap">

  <!-- شريط الإحصائيات (صندوق واحد فقط) -->
  <div class="stats-bar">
    <div class="stat-box stat-total">
      <div>إجمالي التبليغات الظاهرة لك</div>
      <span class="num"><?php echo (int)$total_notifs; ?></span>
    </div>
  </div>

  <?php if ($total_notifs == 0): ?>
    <div class="empty-box">لا توجد تبليغات موجهة لك حالياً من الإدارة.</div>
  <?php else: ?>
    <div class="notif-list">
      <?php foreach ($notifications as $row): ?>
        <?php
          $prio_info        = get_priority_info(isset($row['priority']) ? $row['priority'] : 'normal');
          $cat_label        = get_category_label(isset($row['category']) ? $row['category'] : '');
          $target_text      = get_target_label($row);
          $created_at       = (!empty($row['created_at']) && $row['created_at']!='0000-00-00 00:00:00') ? date('Y-m-d H:i', strtotime($row['created_at'])) : '';
          $valid_until_str  = (!empty($row['valid_until']) && $row['valid_until']!='0000-00-00') ? date('Y-m-d', strtotime($row['valid_until'])) : '';

          $require_confirm  = isset($row['require_confirm']) ? (int)$row['require_confirm'] : 0;
          $is_read          = isset($row['is_read']) ? (int)$row['is_read'] : 0;
          $is_confirmed     = isset($row['is_confirmed']) ? (int)$row['is_confirmed'] : 0;

          $status_text  = 'تبليغ جديد';
          $status_class = 'status-new';
          $show_confirm_btn = false;
          $btn_label = '✔ تم الاطلاع';
          $btn_mode  = 'read';

          if ($require_confirm === 1) {
              if ($is_confirmed === 1) {
                  $status_text  = 'تم تأكيد الاطلاع';
                  $status_class = 'status-ok';
              } else {
                  $status_text  = 'بانتظار تأكيدك';
                  $status_class = 'status-wait';
                  $show_confirm_btn = true;
                  $btn_label = '✔ تم التأكيد';
                  $btn_mode  = 'confirm';
              }
          } else if ($is_read === 1) {
              $status_text  = 'تم الاطلاع';
              $status_class = 'status-ok';
          } else {
              $show_confirm_btn = true;
          }

          $card_classes = 'notif-card';
          if (isset($row['priority']) && $row['priority'] === 'urgent') $card_classes .= ' urgent';
          if ($is_confirmed === 1) $card_classes .= ' confirmed';
        ?>
        <div class="<?php echo $card_classes; ?>"
             data-id="<?php echo (int)$row['id']; ?>"
             data-read="<?php echo (int)$is_read; ?>">
          <div class="notif-header">
            <div class="notif-title-wrap">
              <div class="cat-pill"><span class="icon">🏷</span><span><?php echo htmlspecialchars($cat_label, ENT_QUOTES, 'UTF-8'); ?></span></div>
              <div class="notif-title"><?php echo htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div class="notif-meta">
              <?php if ($created_at != ''): ?>
                <div class="date-pill">تاريخ الإرسال: <?php echo htmlspecialchars($created_at, ENT_QUOTES, 'UTF-8'); ?></div>
              <?php endif; ?>
              <?php if ($valid_until_str != ''): ?>
                <div class="date-pill">صالح لغاية: <?php echo htmlspecialchars($valid_until_str, ENT_QUOTES, 'UTF-8'); ?></div>
              <?php endif; ?>
              <div class="prio-pill <?php echo $prio_info['class']; ?>">
                أولوية: <?php echo htmlspecialchars($prio_info['label'], ENT_QUOTES, 'UTF-8'); ?>
              </div>
            </div>
          </div>

          <div class="notif-body">
            <?php echo nl2br(htmlspecialchars($row['body'], ENT_QUOTES, 'UTF-8')); ?>
          </div>

          <div class="notif-footer">
            <div class="target-text"><?php echo htmlspecialchars($target_text, ENT_QUOTES, 'UTF-8'); ?></div>
            <div class="footer-actions">
              <span class="status-pill <?php echo $status_class; ?>"><?php echo htmlspecialchars($status_text, ENT_QUOTES, 'UTF-8'); ?></span>
              <?php if ($show_confirm_btn): ?>
                <button type="button"
                        class="btn-confirm"
                        data-mode="<?php echo htmlspecialchars($btn_mode, ENT_QUOTES, 'UTF-8'); ?>"
                        onclick="confirmNotif(<?php echo (int)$row['id']; ?>, this)">
                  <span>✅</span>
                  <span><?php echo htmlspecialchars($btn_label, ENT_QUOTES, 'UTF-8'); ?></span>
                </button>
              <?php endif; ?>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

</div>

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

<script>
// ✅ تسجيل الاطلاع تلقائياً عند ظهور الكارت
const cards = document.querySelectorAll('.notif-card');
const io = new IntersectionObserver((entries)=>{
  entries.forEach(e=>{
    if(e.isIntersecting){
      const card = e.target;
      if(card.dataset.read === '0' && !card.dataset.marking){
        card.dataset.marking = '1';
        const id = card.dataset.id;
        fetch('teacher_notifications.php', {
          method:'POST',
          headers:{'Content-Type':'application/x-www-form-urlencoded'},
          credentials:'same-origin',
          body:'action=mark_read&id='+encodeURIComponent(id)
        }).then(r=>r.text()).then(t=>{
          t = t.trim();
          if(t === 'ok_read'){
            card.dataset.read = '1';
            const status = card.querySelector('.status-pill');
            if(status){
              status.textContent = 'تم الاطلاع';
              status.classList.remove('status-new','status-wait');
              status.classList.add('status-ok');
            }
            const btn = card.querySelector('.btn-confirm[data-mode="read"]');
            if(btn){
              btn.disabled = true;
              btn.innerHTML = '✅ <span>تم الاطلاع</span>';
              setTimeout(()=>{ btn.style.display='none'; }, 600);
            }
          }
          delete card.dataset.marking;
        }).catch(()=>{ delete card.dataset.marking; });
      }
    }
  });
},{threshold:0.4});
cards.forEach(c=>io.observe(c));

// ✅ زر تم الاطلاع / تم التأكيد
function confirmNotif(id, btn){
  const mode = btn.getAttribute('data-mode') || 'read';
  fetch('teacher_notifications.php', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'},
    credentials: 'same-origin',
    body: 'action=confirm_notification&id=' + encodeURIComponent(id)
  }).then(res=>res.text())
    .then(txt=>{
      txt = txt.trim();
      const card = btn.closest('.notif-card');
      const status = card ? card.querySelector('.status-pill') : null;
      if(txt === 'ok_confirm' || txt === 'ok_read'){
        btn.disabled = true;
        if(mode === 'confirm'){
          btn.innerHTML = '✅ <span>تم التأكيد</span>';
          if(status){
            status.textContent = 'تم تأكيد الاطلاع';
            status.classList.remove('status-new','status-wait');
            status.classList.add('status-ok');
          }
          if(card){ card.classList.add('confirmed'); }
        }else{
          btn.innerHTML = '✅ <span>تم الاطلاع</span>';
          if(status){
            status.textContent = 'تم الاطلاع';
            status.classList.remove('status-new','status-wait');
            status.classList.add('status-ok');
          }
          setTimeout(()=>{ btn.style.display='none'; }, 600);
        }
        if(card) card.dataset.read = '1';
      }else{
        alert('حدث خطأ أثناء الحفظ:\n' + txt);
      }
    })
    .catch(()=> alert('تعذّر الاتصال بالخادم، حاول مجدداً.'));
}
</script>

</body>
</html>
