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

mysqli_set_charset($conn, "utf8mb4");
date_default_timezone_set('Asia/Baghdad');

/* ===========================================================
   ✅ صلاحيات الدخول — super فقط
   =========================================================== */
if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}

$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;
}

if ($admin_role !== 'super') {
    header("Location: admin_dashboard.php");
    exit();
}

/* رسائل */
$success_msg = '';
$error_msg   = '';

/* ===========================================================
   ✅ دوال مطابقة الاستهداف
   =========================================================== */
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;
            $ids = explode(',', $target_ids_str);
            foreach ($ids 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);
    if ($cat == '') return 'عام';
    return $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 'موجّه لمدرّسين محدّدين بالاسم';
    }
}

/* ===========================================================
   ✅ جلب المدرّسين
   =========================================================== */
$all_teachers = array();
$qT = mysqli_query($conn, "SELECT id, name, subject, stages, classes FROM teachers ORDER BY name ASC");
if ($qT) {
    while ($row = mysqli_fetch_assoc($qT)) $all_teachers[] = $row;
}

/* ===========================================================
   ✅ حذف تبليغ + قراءاته
   =========================================================== */
if (isset($_GET['del'])) {
    $del_id = (int)$_GET['del'];
    if ($del_id > 0) {
        mysqli_query($conn, "DELETE FROM admin_notification_reads WHERE notification_id = ".$del_id);
        mysqli_query($conn, "DELETE FROM admin_notifications WHERE id = ".$del_id." LIMIT 1");
        header("Location: admin_notifications_manage.php?msg=deleted");
        exit();
    }
}

/* ===========================================================
   ✅ تعديل تبليغ (بدون تأكيد نهائيًا)
   =========================================================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $nid = isset($_POST['notif_id']) ? (int)$_POST['notif_id'] : 0;
    if ($nid > 0) {
        $title    = isset($_POST['title']) ? trim($_POST['title']) : '';
        $body     = isset($_POST['body']) ? trim($_POST['body']) : '';
        $category = isset($_POST['category']) ? trim($_POST['category']) : '';
        $priority = isset($_POST['priority']) ? trim($_POST['priority']) : 'normal';

        $valid_until_date = isset($_POST['valid_until']) ? trim($_POST['valid_until']) : '';
        $schedule_date    = isset($_POST['schedule_date']) ? trim($_POST['schedule_date']) : '';
        $schedule_time    = isset($_POST['schedule_time']) ? trim($_POST['schedule_time']) : '';

        if ($title === '' || $body === '') {
            $error_msg = "يجب إدخال عنوان التبليغ ونص التبليغ عند التعديل.";
        } else {
            $title_db = mysqli_real_escape_string($conn, $title);
            $body_db  = mysqli_real_escape_string($conn, $body);
            $cat_db   = mysqli_real_escape_string($conn, $category);
            $prio_db  = mysqli_real_escape_string($conn, $priority);

            $valid_until_db = ($valid_until_date!='') ? ("'".mysqli_real_escape_string($conn,$valid_until_date)."'") : "NULL";

            $is_scheduled    = 0;
            $scheduled_at_db = "NULL";
            if ($schedule_date != '' && $schedule_time != '') {
                $scheduled_at = $schedule_date . ' ' . $schedule_time . ':00';
                $is_scheduled = 1;
                $scheduled_at_db = "'" . mysqli_real_escape_string($conn, $scheduled_at) . "'";
            }

            // 🔴 إلغاء التأكيد بشكل دائم
            $sql_upd = "
                UPDATE admin_notifications
                SET
                    title           = '$title_db',
                    body            = '$body_db',
                    category        = '$cat_db',
                    priority        = '$prio_db',
                    require_confirm = 0,
                    valid_until     = $valid_until_db,
                    is_scheduled    = $is_scheduled,
                    scheduled_at    = $scheduled_at_db
                WHERE id = ".$nid."
                LIMIT 1
            ";

            if (mysqli_query($conn, $sql_upd)) {
                $success_msg = "✅ تم تعديل التبليغ بنجاح.";
            } else {
                $error_msg = "❌ خطأ أثناء تعديل التبليغ: " . mysqli_error($conn);
            }
        }
    }
}

/* ===========================================================
   ✅ عرض/تعديل
   =========================================================== */
$edit_id = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$view_id = isset($_GET['view']) ? (int)$_GET['view'] : 0;
$edit_row = null;
$view_notif = null;
$view_teachers = array();

/* ===========================================================
   ✅ جلب التبليغات (بدون عمود التأكيد) + حسابات دقيقة للقراء
   =========================================================== */
$notifications = array();

// نكتفي بجلب التبليغات، ثم نحسب target_count و reads_count بشكل دقيق يطابق الاستهداف
$sql_notifs = "
SELECT n.*
FROM admin_notifications n
ORDER BY n.created_at DESC
";
$qN = mysqli_query($conn, $sql_notifs);
if ($qN) {
    while ($row = mysqli_fetch_assoc($qN)) {

        // نجلب قرّاء هذا التبليغ (is_read=1) مرة واحدة
        $reads_ids = array();
        $qR = mysqli_query($conn, "
            SELECT DISTINCT teacher_id
            FROM admin_notification_reads
            WHERE notification_id = ".(int)$row['id']." AND is_read = 1
        ");
        if ($qR) {
            while ($r = mysqli_fetch_assoc($qR)) {
                $reads_ids[(int)$r['teacher_id']] = true;
            }
        }

        // نحسب المستهدفين فعليًا + القراء منهم فقط
        $target_count = 0;
        $reads_count  = 0;

        foreach ($all_teachers as $t) {
            $tid = isset($t['id']) ? (int)$t['id'] : 0;
            $sub = isset($t['subject']) ? $t['subject'] : '';
            $stg = isset($t['stages'])  ? $t['stages']  : '';
            $cls = isset($t['classes']) ? $t['classes'] : '';

            if (notification_matches_teacher($row, $tid, $sub, $stg, $cls)) {
                $target_count++;
                if (isset($reads_ids[$tid]) && $reads_ids[$tid] === true) {
                    $reads_count++;
                }
            }
        }

        $row['target_count'] = $target_count;
        $row['reads_count']  = $reads_count;

        $notifications[] = $row;
    }
}

// تجهيز بيانات التعديل
if ($edit_id > 0) {
    foreach ($notifications as $n) {
        if ((int)$n['id'] === $edit_id) { $edit_row = $n; break; }
    }
}

// تجهيز بيانات عرض حالة المدرّسين
if ($view_id > 0) {
    foreach ($notifications as $n) {
        if ((int)$n['id'] === $view_id) { $view_notif = $n; break; }
    }

    if ($view_notif) {
        // قراءات هذا التبليغ
        $reads_map = array();
        $qR = mysqli_query($conn, "
            SELECT teacher_id, is_read, read_at
            FROM admin_notification_reads
            WHERE notification_id = ".$view_id."
        ");
        if ($qR) {
            while ($rr = mysqli_fetch_assoc($qR)) {
                $reads_map[(int)$rr['teacher_id']] = $rr; // يحتوي is_read و read_at
            }
        }

        foreach ($all_teachers as $t) {
            $tid = isset($t['id']) ? (int)$t['id'] : 0;
            $sub = isset($t['subject']) ? $t['subject'] : '';
            $stg = isset($t['stages'])  ? $t['stages']  : '';
            $cls = isset($t['classes']) ? $t['classes'] : '';

            if (notification_matches_teacher($view_notif, $tid, $sub, $stg, $cls)) {
                $rr = isset($reads_map[$tid]) ? $reads_map[$tid] : null;
                $view_teachers[] = array(
                    'id'       => $tid,
                    'name'     => isset($t['name']) ? $t['name'] : '',
                    'subject'  => $sub,
                    'stages'   => $stg,
                    'classes'  => $cls,
                    'is_read'  => $rr ? (int)$rr['is_read'] : 0,
                    'read_at'  => $rr ? $rr['read_at'] : ''
                );
            }
        }
    }
}

$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:16px 22px;background:rgba(15,23,42,0.9);
  border-bottom:1px solid rgba(148,163,184,0.5);backdrop-filter:blur(12px);
}
.header-left{display:flex;align-items:center;gap:10px}
.logo-circle{
  width:38px;height:38px;border-radius:50%;
  background:radial-gradient(circle at 30% 20%,#e0f2fe,#38bdf8);
  display:flex;align-items:center;justify-content:center;font-size:20px;
  box-shadow:0 0 18px rgba(56,189,248,0.8);
}
.logo-text-main{font-size:16px;font-weight:700}
.logo-text-sub{font-size:12px;color:#cbd5f5}
.btn-header{
  background:linear-gradient(120deg,#00e6ff,#007bff);color:#fff;padding:7px 16px;border-radius:999px;
  text-decoration:none;font-size:13px;font-weight:600;box-shadow:0 0 14px rgba(59,130,246,0.7);transition:.25s;
}
.btn-header:hover{transform:translateY(-1px) scale(1.02);box-shadow:0 0 22px rgba(56,189,248,0.9);}

.main-wrap{width:100%;max-width:1150px;margin:22px auto 30px;padding:0 15px 25px;}

.alert{padding:9px 11px;border-radius:10px;margin-bottom:10px;font-size:13px;border:1px solid transparent;}
.alert.success{background:rgba(22,163,74,0.12);color:#bbf7d0;border-color:rgba(34,197,94,0.6);}
.alert.error{background:rgba(239,68,68,0.12);color:#fecaca;border-color:rgba(239,68,68,0.7);}

.card{
  background:rgba(15,23,42,0.9);border-radius:18px;padding:18px 16px 18px;
  border:1px solid rgba(148,163,184,0.5);
  box-shadow:0 24px 60px rgba(15,23,42,0.9),0 0 0 1px rgba(15,23,42,0.8);
  margin-bottom:18px;
}
.card-header{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;}
.card-header h2{font-size:18px;}
.card-header .sub{font-size:12px;color:#cbd5f5;}

.table-wrap{overflow-x:auto;margin-top:6px;}
table{width:100%;border-collapse:collapse;font-size:13px;}
th,td{padding:6px 8px;border-bottom:1px solid rgba(51,65,85,0.7);}
th{text-align:right;background:rgba(15,23,42,0.9);position:sticky;top:0;z-index:1;}
tr:nth-child(even){background:rgba(15,23,42,0.7);}
tr:nth-child(odd){background:rgba(15,23,42,0.85);}
.badge{display:inline-block;padding:2px 7px;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);}

.btn-sm{display:inline-block;padding:3px 8px;border-radius:999px;font-size:11px;text-decoration:none;border:none;cursor:pointer;margin:0 1px;}
.btn-view{background:rgba(59,130,246,0.15);color:#bfdbfe;border:1px solid rgba(59,130,246,0.7);}
.btn-edit{background:rgba(251,191,36,0.15);color:#fde68a;border:1px solid rgba(251,191,36,0.8);}
.btn-del{background:rgba(248,113,113,0.15);color:#fecaca;border:1px solid rgba(248,113,113,0.8);}

.section-title{font-size:15px;margin-bottom:8px;display:flex;align-items:center;gap:6px;}
.section-title::before{content:"";width:4px;height:18px;border-radius:999px;background:linear-gradient(180deg,#0ea5e9,#6366f1);}
.form-row{margin-bottom:10px;}
.form-row label{display:block;margin-bottom:3px;font-size:13px;}
input[type="text"],input[type="date"],input[type="time"],textarea,select{
  width:100%;padding:7px 9px;border-radius:10px;border:1px solid rgba(148,163,184,0.6);
  font-size:13px;background:rgba(15,23,42,0.85);color:#e5e7eb;outline:none;
}
textarea{min-height:90px;resize:vertical;}
input:focus,textarea:focus,select:focus{border-color:#38bdf8;box-shadow:0 0 0 1px rgba(56,189,248,0.6);}
.btn-save{padding:7px 18px;border-radius:999px;background:linear-gradient(120deg,#22c55e,#16a34a);border:none;color:#fff;font-size:13px;font-weight:600;cursor:pointer;box-shadow:0 0 16px rgba(34,197,94,0.8);}

.teacher-status-table{width:100%;border-collapse:collapse;font-size:12px;}
.teacher-status-table th,.teacher-status-table td{padding:5px 6px;border-bottom:1px solid rgba(55,65,81,0.8);}
.tag-read{background:rgba(56,189,248,0.15);color:#bfdbfe;border-radius:999px;padding:1px 6px;font-size:11px;}
.tag-notread{background:rgba(15,23,42,0.7);color:#fecaca;border-radius:999px;padding:1px 6px;font-size:11px;border:1px solid rgba(248,113,113,0.7);}

footer{text-align:center;padding:10px;font-size:12px;color:#aaa;background:rgba(15,23,42,0.9);border-top:1px solid rgba(148,163,184,0.4);}
footer span{color:#0ea5e9}
@media(max-width:800px){header{flex-direction:column;align-items:flex-start;gap:6px}.card-header{flex-direction:column;align-items:flex-start}}
</style>
</head>
<body>

<header>
  <div class="header-left">
    <div class="logo-circle">📢</div>
    <div>
      <div class="logo-text-main">إدارة تبليغات الإدارة للكادر التدريسي</div>
      <div class="logo-text-sub">عرض، متابعة، تعديل، وحذف جميع التبليغات</div>
    </div>
  </div>
  <a href="admin_dashboard.php" class="btn-header">↩ العودة للوحة التحكم</a>
</header>

<div class="main-wrap">

  <?php if (isset($_GET['msg']) && $_GET['msg'] === 'deleted'): ?>
    <div class="alert success">✅ تم حذف التبليغ وجميع سجلات قراءته بنجاح.</div>
  <?php endif; ?>

  <?php if ($success_msg != ''): ?>
    <div class="alert success"><?php echo htmlspecialchars($success_msg, ENT_QUOTES, 'UTF-8'); ?></div>
  <?php endif; ?>

  <?php if ($error_msg != ''): ?>
    <div class="alert error"><?php echo htmlspecialchars($error_msg, ENT_QUOTES, 'UTF-8'); ?></div>
  <?php endif; ?>

  <!-- كارت قائمة جميع التبليغات -->
  <div class="card">
    <div class="card-header">
      <div>
        <h2>📜 جميع التبليغات الإدارية</h2>
        <div class="sub">إجمالي التبليغات: <?php echo (int)$total_notifs; ?> تبليغ</div>
      </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 ($total_notifs == 0): ?>
          <tr>
            <td colspan="9" style="text-align:center;">لا توجد تبليغات مسجّلة حالياً.</td>
          </tr>
        <?php else: ?>
          <?php
          $i = 1;
          foreach ($notifications as $row):
              $prio_info   = get_priority_info(isset($row['priority']) ? $row['priority'] : 'normal');
              $cat_label   = get_category_label(isset($row['category']) ? $row['category'] : '');
              $target_txt  = get_target_label($row);
              $created_at  = (isset($row['created_at']) && $row['created_at']!='' && $row['created_at']!='0000-00-00 00:00:00') ? date('Y-m-d H:i', strtotime($row['created_at'])) : '';
              $scheduled_at= (isset($row['scheduled_at'])&& $row['scheduled_at']!=''&& $row['scheduled_at']!='0000-00-00 00:00:00') ? date('Y-m-d H:i', strtotime($row['scheduled_at'])) : '';
              $target_count= isset($row['target_count']) ? (int)$row['target_count'] : 0;
              $reads_count = isset($row['reads_count'])  ? (int)$row['reads_count']  : 0;
          ?>
          <tr>
            <td><?php echo $i++; ?></td>
            <td><?php echo htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($cat_label, ENT_QUOTES, 'UTF-8'); ?></td>
            <td><span class="badge <?php echo $prio_info['class']; ?>"><?php echo htmlspecialchars($prio_info['label'], ENT_QUOTES, 'UTF-8'); ?></span></td>
            <td style="font-size:11px;"><?php echo htmlspecialchars($target_txt, ENT_QUOTES, 'UTF-8'); ?></td>
            <td style="font-size:11px;">
              <?php if ($created_at != ''): ?><div>إنشاء: <?php echo htmlspecialchars($created_at, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
              <?php if ($scheduled_at != ''): ?><div>مجدول: <?php echo htmlspecialchars($scheduled_at, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            </td>
            <td><?php echo $target_count; ?></td>
            <td><?php echo $reads_count; ?></td>
            <td>
              <a class="btn-sm btn-view" href="admin_notifications_manage.php?view=<?php echo (int)$row['id']; ?>#viewBox">👁 حالة المدرّسين</a>
              <a class="btn-sm btn-edit" href="admin_notifications_manage.php?edit=<?php echo (int)$row['id']; ?>#editBox">✏ تعديل</a>
              <a class="btn-sm btn-del" href="admin_notifications_manage.php?del=<?php echo (int)$row['id']; ?>"
                 onclick="return confirm('هل أنت متأكد من حذف هذا التبليغ وجميع سجلات قراءته؟');">🗑 حذف</a>
            </td>
          </tr>
          <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- كارت تعديل تبليغ (بدون خيار التأكيد) -->
  <?php if ($edit_row): ?>
  <?php
    $edit_valid_until  = (isset($edit_row['valid_until'])  && $edit_row['valid_until']  != '' && $edit_row['valid_until']  != '0000-00-00') ? date('Y-m-d', strtotime($edit_row['valid_until'])) : '';
    $edit_schedule_date= (isset($edit_row['scheduled_at']) && $edit_row['scheduled_at'] != '' && $edit_row['scheduled_at'] != '0000-00-00 00:00:00') ? date('Y-m-d', strtotime($edit_row['scheduled_at'])) : '';
    $edit_schedule_time= (isset($edit_row['scheduled_at']) && $edit_row['scheduled_at'] != '' && $edit_row['scheduled_at'] != '0000-00-00 00:00:00') ? date('H:i',   strtotime($edit_row['scheduled_at'])) : '';
  ?>
  <div class="card" id="editBox">
    <div class="section-title">✏ تعديل التبليغ: <?php echo htmlspecialchars($edit_row['title'], ENT_QUOTES, 'UTF-8'); ?></div>
    <form method="post" action="admin_notifications_manage.php?edit=<?php echo (int)$edit_row['id']; ?>#editBox">
      <input type="hidden" name="action" value="update">
      <input type="hidden" name="notif_id" value="<?php echo (int)$edit_row['id']; ?>">

      <div class="form-row">
        <label>العنوان</label>
        <input type="text" name="title" value="<?php echo htmlspecialchars($edit_row['title'], ENT_QUOTES, 'UTF-8'); ?>">
      </div>

      <div class="form-row">
        <label>نص التبليغ</label>
        <textarea name="body"><?php echo htmlspecialchars($edit_row['body'], ENT_QUOTES, 'UTF-8'); ?></textarea>
      </div>

      <div class="form-row">
        <label>التصنيف</label>
        <input type="text" name="category" value="<?php echo htmlspecialchars($edit_row['category'], ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: امتحانات، الحضور، إداري ...">
      </div>

      <div class="form-row">
        <label>الأولوية</label>
        <select name="priority">
          <option value="normal"    <?php if($edit_row['priority']=='normal')    echo 'selected'; ?>>عادي</option>
          <option value="important" <?php if($edit_row['priority']=='important') echo 'selected'; ?>>مهم</option>
          <option value="urgent"    <?php if($edit_row['priority']=='urgent')    echo 'selected'; ?>>عاجل جداً</option>
        </select>
      </div>

      <!-- تمت إزالة خيار require_confirm نهائيًا -->

      <div class="form-row">
        <label>صلاحية التبليغ (تاريخ انتهاء اختياري)</label>
        <input type="date" name="valid_until" value="<?php echo htmlspecialchars($edit_valid_until, ENT_QUOTES, 'UTF-8'); ?>">
      </div>

      <div class="form-row">
        <label>وقت الإظهار المجدول (اختياري)</label>
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
          <div style="flex:1;min-width:130px;">
            <small>📅 التاريخ</small>
            <input type="date" name="schedule_date" value="<?php echo htmlspecialchars($edit_schedule_date, ENT_QUOTES, 'UTF-8'); ?>">
          </div>
          <div style="flex:1;min-width:110px;">
            <small>⏰ الوقت</small>
            <input type="time" name="schedule_time" value="<?php echo htmlspecialchars($edit_schedule_time, ENT_QUOTES, 'UTF-8'); ?>">
          </div>
        </div>
        <small>إذا تركته فارغاً سيُعامل التبليغ على أنه غير مجدول (يظهر حسب تاريخ الإنشاء).</small>
      </div>

      <button type="submit" class="btn-save">💾 حفظ التعديلات</button>
    </form>
  </div>
  <?php endif; ?>

  <!-- كارت حالة المدرّسين (بدون أي أعمدة للتأكيد) -->
  <?php if ($view_notif): ?>
  <div class="card" id="viewBox">
    <div class="section-title">
      👁 حالة المدرّسين للتبليغ:
      <span style="font-weight:600;"><?php echo htmlspecialchars($view_notif['title'], ENT_QUOTES, 'UTF-8'); ?></span>
    </div>
    <div class="table-wrap" style="margin-bottom:8px;font-size:13px;">
      <b>التصنيف:</b> <?php echo htmlspecialchars(get_category_label($view_notif['category']), ENT_QUOTES, 'UTF-8'); ?> |
      <b>الأولوية:</b> <?php $pi = get_priority_info($view_notif['priority']); echo htmlspecialchars($pi['label'], ENT_QUOTES, 'UTF-8'); ?> |
      <b>الاستهداف:</b> <?php echo htmlspecialchars(get_target_label($view_notif), ENT_QUOTES, 'UTF-8'); ?>
    </div>

    <div class="table-wrap">
      <table class="teacher-status-table">
        <thead>
          <tr>
            <th>م</th>
            <th>اسم المدرّس</th>
            <th>المادة</th>
            <th>المراحل / الشُعب</th>
            <th>الحالة</th>
            <th>وقت الاطلاع</th>
          </tr>
        </thead>
        <tbody>
        <?php if (count($view_teachers) == 0): ?>
          <tr>
            <td colspan="6" style="text-align:center;">لا يوجد مدرّسون مستهدفون لهذا التبليغ.</td>
          </tr>
        <?php else: ?>
          <?php
          $k = 1;
          foreach ($view_teachers as $t):
            $is_read = $t['is_read'];
            $read_at = ($t['read_at'] && $t['read_at']!='0000-00-00 00:00:00') ? date('Y-m-d H:i', strtotime($t['read_at'])) : '';
          ?>
          <tr>
            <td><?php echo $k++; ?></td>
            <td><?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($t['subject'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td style="font-size:11px;">
              <?php
                echo 'مراحل: ' . ($t['stages']  != '' ? htmlspecialchars($t['stages'], ENT_QUOTES, 'UTF-8')  : 'غير مضافة');
                echo ' — شُعب: ' . ($t['classes'] != '' ? htmlspecialchars($t['classes'], ENT_QUOTES, 'UTF-8') : 'غير مضافة');
              ?>
            </td>
            <td>
              <?php if ($is_read): ?>
                <span class="tag-read">تم الاطلاع</span>
              <?php else: ?>
                <span class="tag-notread">لم يطّلع بعد</span>
              <?php endif; ?>
            </td>
            <td><?php echo $read_at != '' ? htmlspecialchars($read_at, ENT_QUOTES, 'UTF-8') : '—'; ?></td>
          </tr>
          <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php endif; ?>

</div>

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

</body>
</html>
