<?php
/* ======================================================
   ✅ admin_behavior_manage.php
   ✅ إدارة سجل السلوك الإداري (إضافة + قائمة الطلاب + تفاصيل + حذف داخل التفاصيل)
   ✅ متوافق مع PHP القديم (بدون ??)
   ====================================================== */

if (session_id() === '') { session_start(); }
include 'db.php';

/* ✅ تقييد الصفحة على الأدمن فقط */
if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}

/* ✅ ضبط الترميز */
if (function_exists('mysqli_set_charset')) {
    mysqli_set_charset($conn, "utf8mb4");
}

/* ✅ توقيت بغداد */
date_default_timezone_set('Asia/Baghdad');

/* ✅ دوال مساعدة */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function q($conn, $s){ return mysqli_real_escape_string($conn, (string)$s); }

/* ✅ خيارات الفصل/الفترة الدراسية */
$TERM_OPTIONS = array('الفصل الأول','نصف السنة','الفصل الثاني','آخر السنة');

/* ======================================================
   ✅ إنشاء الجدول إن لم يكن موجود (احتياطي)
   ====================================================== */
mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS admin_behavior (
  id INT AUTO_INCREMENT PRIMARY KEY,
  student_id INT NOT NULL,
  school_term VARCHAR(30) NULL,
  problem_type VARCHAR(190) NOT NULL,
  problem_note TEXT NULL,
  problem_date DATE NOT NULL,
  problem_count INT NOT NULL DEFAULT 1,
  admin_name VARCHAR(190) NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX (student_id),
  INDEX (problem_date),
  INDEX (problem_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* ======================================================
   ✅ فلاتر بسيطة فقط: المرحلة + الشعبة
   ====================================================== */
$filter_stage  = isset($_GET['stage']) ? trim($_GET['stage']) : '';
$filter_class  = isset($_GET['class']) ? trim($_GET['class']) : '';

$filter_term   = isset($_GET['term']) ? trim($_GET['term']) : '';

// ✅ حماية: لا نقبل إلا القيم المعروفة
if ($filter_term !== '' && $filter_term !== 'غير محدد' && !in_array($filter_term, $TERM_OPTIONS, true)) {
    $filter_term = '';
}
$view    = isset($_GET['view']) ? trim($_GET['view']) : '';     // student
$view_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$edit_mode = (isset($_GET['edit']) && $_GET['edit'] === '1') ? true : false;
$edit_behavior_id = isset($_GET['behavior_id']) ? (int)$_GET['behavior_id'] : 0;

/* ======================================================
   ✅ AJAX: بحث الطلاب (Autocomplete)
   ====================================================== */
if (isset($_GET['ajax']) && $_GET['ajax'] === 'student_search') {
    header('Content-Type: application/json; charset=UTF-8');

    $term  = isset($_GET['term']) ? trim($_GET['term']) : '';
    $stage = isset($_GET['stage']) ? trim($_GET['stage']) : '';
    $class = isset($_GET['class']) ? trim($_GET['class']) : '';

    $out = array();

    $len = function_exists('mb_strlen') ? mb_strlen($term, 'UTF-8') : strlen($term);
    if ($len < 1) {
        echo json_encode($out);
        exit();
    }

    $where = "1=1";
    if ($stage !== '') $where .= " AND stage='" . q($conn, $stage) . "'";
    if ($class !== '') $where .= " AND class='" . q($conn, $class) . "'";
    $where .= " AND name LIKE '%" . q($conn, $term) . "%'";

    $sql = "SELECT id, name, stage, class
            FROM students
            WHERE $where
            ORDER BY name ASC
            LIMIT 20";

    $res = mysqli_query($conn, $sql);
    if ($res) {
        while ($r = mysqli_fetch_assoc($res)) {
            $out[] = array(
                'id'    => (int)$r['id'],
                'name'  => $r['name'],
                'stage' => $r['stage'],
                'class' => $r['class']
            );
        }
    }
    echo json_encode($out);
    exit();
}

/* ======================================================
   ✅ رسائل
   ====================================================== */
$msg = '';
$err = '';

/* ======================================================
   ✅ POST (إضافة مخالفة / تعديل / حذف مخالفة داخل التفاصيل)
   ====================================================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';

    /* ✅ إضافة مخالفة */
    if ($action === 'add_behavior') {
        $student_id   = isset($_POST['student_id']) ? (int)$_POST['student_id'] : 0;
        $problem_type = isset($_POST['problem_type']) ? trim($_POST['problem_type']) : '';
        $problem_note = isset($_POST['problem_note']) ? trim($_POST['problem_note']) : '';
        $problem_date = isset($_POST['problem_date']) ? trim($_POST['problem_date']) : '';
        $school_term  = isset($_POST['school_term']) ? trim($_POST['school_term']) : '';
        $admin_name   = isset($_SESSION['admin_username']) ? trim($_SESSION['admin_username']) : 'الإدارة';

        if ($student_id <= 0) {
            $err = "⚠️ يرجى اختيار الطالب من البحث.";
        } elseif ($problem_type === '') {
            $err = "⚠️ يرجى كتابة نوع المخالفة.";
        } elseif ($problem_date === '') {
            $err = "⚠️ يرجى اختيار تاريخ المخالفة.";
        } elseif (!in_array($school_term, $TERM_OPTIONS, true)) {
            $err = "⚠️ يرجى اختيار الفصل / الفترة الدراسية.";
        } else {
            $chk = mysqli_query($conn, "SELECT id FROM students WHERE id=".$student_id." LIMIT 1");
            if (!$chk || mysqli_num_rows($chk) === 0) {
                $err = "❌ الطالب غير موجود.";
            } else {
                $type_esc = q($conn, $problem_type);
                $date_esc = q($conn, $problem_date);
                $term_esc = q($conn, $school_term);

                $last_count = 0;
                $qr = mysqli_query($conn,
                    "SELECT problem_count
                     FROM admin_behavior
                     WHERE student_id=".$student_id."
                       AND problem_type='".$type_esc."'
                       AND problem_date='".$date_esc."'
                       AND (school_term='".$term_esc."' OR (school_term IS NULL AND '".$term_esc."'=''))
                     ORDER BY id DESC
                     LIMIT 1"
                );
                if ($qr && mysqli_num_rows($qr) > 0) {
                    $r = mysqli_fetch_assoc($qr);
                    $last_count = (int)$r['problem_count'];
                }
                $new_count = ($last_count > 0) ? ($last_count + 1) : 1;

                $stmt = mysqli_prepare($conn,
                    "INSERT INTO admin_behavior (student_id, school_term, problem_type, problem_note, problem_date, problem_count, admin_name)
                     VALUES (?,?,?,?,?,?,?)"
                );

                if ($stmt) {
                    $note_to_save = ($problem_note !== '') ? $problem_note : null;
                    mysqli_stmt_bind_param($stmt, "issssis",
                        $student_id,
                        $school_term,
                        $problem_type,
                        $note_to_save,
                        $problem_date,
                        $new_count,
                        $admin_name
                    );
                    $ok = mysqli_stmt_execute($stmt);
                    mysqli_stmt_close($stmt);

                    if ($ok) {
                        $msg = "✅ تم تسجيل المخالفة بنجاح.";
                    } else {
                        $err = "❌ فشل الحفظ: ".mysqli_error($conn);
                    }
                } else {
                    $err = "❌ خطأ تجهيز الاستعلام: ".mysqli_error($conn);
                }
            }
        }
    }


    /* ✅ تعديل مخالفة (داخل التفاصيل) مع باسورد 0100 */
    if ($action === 'update_behavior') {
        $edit_id    = isset($_POST['behavior_id']) ? (int)$_POST['behavior_id'] : 0;
        $student_id = isset($_POST['student_id']) ? (int)$_POST['student_id'] : 0;

        $problem_type = isset($_POST['problem_type']) ? trim($_POST['problem_type']) : '';
        $problem_note = isset($_POST['problem_note']) ? trim($_POST['problem_note']) : '';
        $problem_date = isset($_POST['problem_date']) ? trim($_POST['problem_date']) : '';
        $school_term  = isset($_POST['school_term']) ? trim($_POST['school_term']) : '';

        // ✅ باسورد التعديل
        $input_pass  = isset($_POST['update_password']) ? trim($_POST['update_password']) : '';

        if ($input_pass !== '0100') {
            $err = "❌ كلمة المرور الخاصة بالتعديل غير صحيحة، لم يتم حفظ التعديل.";
        } elseif ($edit_id <= 0 || $student_id <= 0) {
            $err = "⚠️ بيانات التعديل غير صحيحة.";
        } elseif ($problem_type === '') {
            $err = "⚠️ يرجى كتابة نوع المخالفة.";
        } elseif ($problem_date === '') {
            $err = "⚠️ يرجى اختيار تاريخ المخالفة.";
        } elseif (!in_array($school_term, $TERM_OPTIONS, true)) {
            $err = "⚠️ يرجى اختيار الفصل / الفترة الدراسية.";
        } else {
            // تأكد أن السجل يعود لنفس الطالب
            $ck = mysqli_query($conn, "SELECT id FROM admin_behavior WHERE id=".$edit_id." AND student_id=".$student_id." LIMIT 1");
            if (!$ck || mysqli_num_rows($ck) === 0) {
                $err = "❌ سجل المخالفة غير موجود.";
            } else {
                $stmt = mysqli_prepare($conn,
                    "UPDATE admin_behavior
                     SET school_term=?, problem_type=?, problem_note=?, problem_date=?
                     WHERE id=? AND student_id=?
                     LIMIT 1"
                );

                if ($stmt) {
                    $note_to_save = ($problem_note !== '') ? $problem_note : null;
                    mysqli_stmt_bind_param($stmt, "ssssii",
                        $school_term,
                        $problem_type,
                        $note_to_save,
                        $problem_date,
                        $edit_id,
                        $student_id
                    );
                    $ok = mysqli_stmt_execute($stmt);
                    mysqli_stmt_close($stmt);

                    if ($ok) {
                        // رجوع للتفاصيل بدون وضع التعديل
                        $qs = array('view'=>'student','id'=>$student_id);
                        if ($filter_stage !== '') $qs['stage'] = $filter_stage;
                        if ($filter_class !== '') $qs['class'] = $filter_class;
                        if ($filter_term !== '')  $qs['term']  = $filter_term;
                        header("Location: admin_behavior_manage.php?".http_build_query($qs));
                        exit();
                    } else {
                        $err = "❌ فشل التعديل: ".mysqli_error($conn);
                    }
                } else {
                    $err = "❌ خطأ تجهيز الاستعلام: ".mysqli_error($conn);
                }
            }
        }
    }

    /* ✅ حذف مخالفة (داخل التفاصيل فقط) مع باسورد 0100 */
    if ($action === 'delete_behavior') {
        $del_id      = isset($_POST['behavior_id']) ? (int)$_POST['behavior_id'] : 0;
        $student_id  = isset($_POST['student_id']) ? (int)$_POST['student_id'] : 0;
        $input_pass  = isset($_POST['delete_password']) ? trim($_POST['delete_password']) : '';

        if ($input_pass !== '0100') {
            $err = "❌ كلمة المرور الخاصة بالحذف غير صحيحة، لم يتم حذف المشكلة.";
        } elseif ($del_id > 0) {
            $d = mysqli_query($conn, "DELETE FROM admin_behavior WHERE id=".$del_id." LIMIT 1");
            if ($d) {
                $msg = "🗑️ تم حذف المشكلة بنجاح.";
            } else {
                $err = "❌ تعذر الحذف: ".mysqli_error($conn);
            }
        } else {
            $err = "⚠️ رقم السجل غير صحيح.";
        }

        // في حالة نجاح الحذف فقط نرجع لصفحة التفاصيل
        if ($student_id > 0 && $err === '') {
            $qs = array('view'=>'student','id'=>$student_id);
            if ($filter_stage !== '') $qs['stage'] = $filter_stage;
            if ($filter_class !== '') $qs['class'] = $filter_class;
            if ($filter_term !== '') $qs['term'] = $filter_term;
            header("Location: admin_behavior_manage.php?".http_build_query($qs));
            exit();
        }
    }
}

/* ======================================================
   ✅ جلب المراحل
   ====================================================== */
$stages = array();
$stq = mysqli_query($conn, "SELECT DISTINCT stage FROM students ORDER BY stage ASC");
if ($stq) {
    while ($r = mysqli_fetch_assoc($stq)) {
        if (isset($r['stage']) && trim($r['stage']) !== '') $stages[] = $r['stage'];
    }
}
$classes = array('A','B','C','D','E','F');

$today = date('Y-m-d');

/* ======================================================
   ✅ تفاصيل طالب
   ====================================================== */
$student_info = null;
$student_behaviors = array();
$edit_behavior = null;

if ($view === 'student' && $view_id > 0) {
    $si = mysqli_query($conn, "SELECT id, name, stage, class FROM students WHERE id=".$view_id." LIMIT 1");
    if ($si && mysqli_num_rows($si) > 0) {
        $student_info = mysqli_fetch_assoc($si);

        $lq = mysqli_query($conn,
            "SELECT *
             FROM admin_behavior
             WHERE student_id=".$view_id."
             ORDER BY problem_date DESC, id DESC"
        );
        if ($lq) {
            while ($r = mysqli_fetch_assoc($lq)) $student_behaviors[] = $r;
        }

        /* ✅ جلب السجل المراد تعديله (إن وجد) */
        if ($edit_mode && $edit_behavior_id > 0) {
            $eq = mysqli_query($conn, "SELECT * FROM admin_behavior WHERE id=".$edit_behavior_id." AND student_id=".$view_id." LIMIT 1");
            if ($eq && mysqli_num_rows($eq) > 0) {
                $edit_behavior = mysqli_fetch_assoc($eq);
            } else {
                $edit_behavior = null;
            }
        }
    }
}

/* ======================================================
   ✅ قائمة الطلاب (مرة واحدة)
   ====================================================== */
$students_list = array();
$where = "1=1";
if ($filter_stage !== '') $where .= " AND s.stage='".q($conn, $filter_stage)."'";
if ($filter_class !== '') $where .= " AND s.class='".q($conn, $filter_class)."'";


// ✅ فلترة حسب الفصل/الفترة (للقائمة)
if ($filter_term !== '') {
    if ($filter_term === 'غير محدد') {
        $where .= " AND (b.school_term IS NULL OR b.school_term='')";
    } else {
        $where .= " AND b.school_term='".q($conn, $filter_term)."'";
    }
}
$list_sql =
"SELECT
    s.id AS student_id,
    s.name,
    s.stage,
    s.class,
    COUNT(b.id) AS issues_count,
    MAX(b.problem_date) AS last_problem_date,
    GROUP_CONCAT(
        DISTINCT IFNULL(b.school_term,'غير محدد')
        ORDER BY FIELD(IFNULL(b.school_term,'غير محدد'),'الفصل الأول','نصف السنة','الفصل الثاني','آخر السنة','غير محدد')
        SEPARATOR ' | '
    ) AS terms_list
 FROM admin_behavior b
 INNER JOIN students s ON s.id = b.student_id
 WHERE $where
 GROUP BY s.id
 ORDER BY last_problem_date DESC, issues_count DESC
 LIMIT 2000";

$lres = mysqli_query($conn, $list_sql);
if ($lres) {
    while ($r = mysqli_fetch_assoc($lres)) $students_list[] = $r;
}

/* ======================================================
   ✅ رجوع
   ====================================================== */
function build_back_url($filter_stage, $filter_class, $filter_term){
    $qs = array();
    if ($filter_stage !== '') $qs['stage'] = $filter_stage;
    if ($filter_class !== '') $qs['class'] = $filter_class;

    if ($filter_term !== '')  $qs['term']  = $filter_term;
    $url = "admin_behavior_manage.php";
    if (count($qs) > 0) $url .= "?".http_build_query($qs);
    return $url;
}
$back_url = build_back_url($filter_stage, $filter_class, $filter_term);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>إدارة سجل السلوك الإداري</title>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;font-family:'Cairo',sans-serif}
:root{
  --blue-900:#0b1220;
  --blue-800:#0b2447;
  --blue-600:#1d4ed8;
  --cyan-500:#06b6d4;
  --amber-500:#f59e0b;
  --amber-300:#fcd34d;
  --danger:#ef4444;
  --ink:#0f172a;
  --card:rgba(255,255,255,0.86);
  --card2:rgba(255,255,255,0.92);
  --border:rgba(29,78,216,0.18);
  --border2:rgba(245,158,11,0.20);
}

body{
  margin:0;
  color:var(--ink);
  /* ✅ خلفية فاتحة + تدرج أزرق/أصفر + لمسات تحذير */
  background:
    radial-gradient(900px 520px at 12% 15%, rgba(29,78,216,0.18), transparent 60%),
    radial-gradient(820px 520px at 90% 18%, rgba(245,158,11,0.18), transparent 62%),
    radial-gradient(900px 560px at 55% 115%, rgba(6,182,212,0.12), transparent 55%),
    linear-gradient(180deg, #f8fbff 0%, #fff8e8 35%, #f7fbff 70%, #ffffff 100%);
  overflow-x:hidden;
  position:relative;
}

/* ✅ طبقات متحركة (فقاعات/وهج) */
.bg-anim{
  position:fixed;
  inset:0;
  pointer-events:none;
  z-index:0;
}
.bg-anim .blob{
  position:absolute;
  width:520px;height:520px;
  border-radius:50%;
  filter:blur(45px);
  opacity:0.65;
  mix-blend-mode:multiply;
  animation:floatBlob 18s ease-in-out infinite;
}
.bg-anim .b1{
  right:-180px; top:-160px;
  background:radial-gradient(circle at 30% 30%, rgba(245,158,11,0.50), rgba(245,158,11,0.05) 70%);
  animation-duration:20s;
}
.bg-anim .b2{
  left:-220px; top:140px;
  background:radial-gradient(circle at 35% 30%, rgba(29,78,216,0.46), rgba(29,78,216,0.04) 70%);
  animation-duration:22s;
}
.bg-anim .b3{
  left:20%; bottom:-260px;
  background:radial-gradient(circle at 40% 35%, rgba(6,182,212,0.38), rgba(6,182,212,0.04) 70%);
  animation-duration:24s;
}
@keyframes floatBlob{
  0%   { transform:translate(0,0) scale(1) rotate(0deg); }
  50%  { transform:translate(40px, -25px) scale(1.06) rotate(6deg); }
  100% { transform:translate(0,0) scale(1) rotate(0deg); }
}

/* ✅ خطوط تحذير خفيفة متحركة */
.bg-anim .stripes{
  position:absolute; inset:-40px;
  background:
    repeating-linear-gradient(
      135deg,
      rgba(245,158,11,0.06) 0px,
      rgba(245,158,11,0.06) 10px,
      rgba(29,78,216,0.03) 10px,
      rgba(29,78,216,0.03) 22px
    );
  mask-image: radial-gradient(circle at 50% 35%, rgba(0,0,0,0.65), transparent 70%);
  opacity:0.55;
  animation:moveStripes 14s linear infinite;
}
@keyframes moveStripes{
  0%{ transform:translate3d(0,0,0); }
  100%{ transform:translate3d(120px, -120px,0); }
}

/* ✅ watermark أيقونات تحذير خفيفة */
.bg-anim .marks{
  position:absolute; inset:0;
  opacity:0.15;
  font-weight:900;
  color:rgba(245,158,11,0.55);
  font-size:28px;
  letter-spacing:18px;
  filter:blur(0.2px);
  animation:driftMarks 26s ease-in-out infinite;
  display:flex;
  align-items:center;
  justify-content:center;
}
.bg-anim .marks::before{
  content:"⚠️   🚫   ⚠️   🚨   ⚠️   🚫   ⚠️   🚨   ⚠️   🚫   ⚠️   🚨";
}
@keyframes driftMarks{
  0%{ transform:translateY(0) rotate(-2deg); }
  50%{ transform:translateY(18px) rotate(2deg); }
  100%{ transform:translateY(0) rotate(-2deg); }
}

/* ===== Layout ===== */
.container{max-width:1200px;margin:26px auto;padding:0 14px; position:relative; z-index:2;}

header{
  display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;
  padding:14px 16px;border-radius:18px;
  background:var(--card2);
  border:1px solid rgba(29,78,216,0.18);
  box-shadow:0 18px 55px rgba(29,78,216,0.10), 0 10px 30px rgba(245,158,11,0.08);
  backdrop-filter: blur(10px);
  position:relative;
  overflow:hidden;
}
header::after{
  content:"";
  position:absolute; inset:-2px;
  background:linear-gradient(90deg, rgba(29,78,216,0.14), rgba(245,158,11,0.14), rgba(6,182,212,0.12));
  opacity:0.7;
  filter:blur(18px);
  z-index:0;
  animation:headerGlow 10s ease-in-out infinite;
}
@keyframes headerGlow{
  0%{ transform:translateX(-18px); }
  50%{ transform:translateX(18px); }
  100%{ transform:translateX(-18px); }
}
header > *{ position:relative; z-index:1; }

h1{margin:0;font-size:20px;font-weight:900;color:var(--blue-800)}
.subtitle{margin:10px 2px 16px;color:#475569;font-size:13px}

.header-actions{display:flex;gap:10px;flex-wrap:wrap}
.btn{
  display:inline-flex;align-items:center;gap:8px;
  padding:10px 12px;border-radius:12px;text-decoration:none;
  color:var(--ink);
  background:rgba(255,255,255,0.95);
  border:1px solid rgba(29,78,216,0.18);
  transition:transform .18s ease, box-shadow .18s ease;
}
.btn:hover{transform:translateY(-1px); box-shadow:0 10px 22px rgba(29,78,216,0.10)}
.btn.blue{border-color:rgba(29,78,216,0.28)}
.btn.red{border-color:rgba(239,68,68,0.28)}

.box{
  background:var(--card);
  border:1px solid rgba(29,78,216,0.16);
  border-radius:18px;
  padding:14px;
  box-shadow:0 14px 40px rgba(2,6,23,0.08);
  margin-bottom:14px;
  backdrop-filter: blur(10px);
}

.row{display:flex;gap:12px;flex-wrap:wrap;align-items:end}
.field{flex:1 1 220px;min-width:220px}

label{display:block;font-size:12px;color:#475569;margin:0 0 6px}

input,select,textarea{
  width:100%;
  padding:10px 12px;
  border-radius:12px;
  border:1px solid rgba(29,78,216,0.16);
  background:#ffffff;
  color:var(--ink);
  outline:none;
  transition:box-shadow .18s ease, border-color .18s ease, transform .18s ease;
}
input:focus,select:focus,textarea:focus{
  border-color:rgba(245,158,11,0.40);
  box-shadow:0 0 0 4px rgba(245,158,11,0.14);
  transform:translateY(-1px);
}
textarea{min-height:42px;resize:vertical}

button{
  padding:10px 14px;border-radius:12px;border:none;cursor:pointer;
  background:linear-gradient(90deg, rgba(29,78,216,0.96), rgba(245,158,11,0.92));
  color:#fff;font-weight:900;
  transition:transform .18s ease, box-shadow .18s ease, opacity .18s ease;
  box-shadow:0 14px 26px rgba(29,78,216,0.15), 0 12px 24px rgba(245,158,11,0.12);
}
button:hover{opacity:0.97; transform:translateY(-1px)}
button.danger{
  background:linear-gradient(90deg, rgba(239,68,68,0.98), rgba(245,158,11,0.90));
}

.alert{padding:10px 12px;border-radius:14px;margin:10px 0;font-weight:900}
.alert.ok{
  background:rgba(34,197,94,0.12);
  border:1px solid rgba(34,197,94,0.25);
  color:#065f46;
}
.alert.err{
  background:rgba(239,68,68,0.10);
  border:1px solid rgba(239,68,68,0.22);
  color:#7f1d1d;
}

.table-wrap{
  overflow:auto;
  border-radius:14px;
  border:1px solid rgba(29,78,216,0.14);
  box-shadow:0 12px 26px rgba(2,6,23,0.06) inset;
}
table{width:100%;border-collapse:collapse;min-width:950px;background:rgba(255,255,255,0.98)}
th,td{
  border:1px solid rgba(29,78,216,0.10);
  padding:8px;text-align:center;white-space:nowrap;font-size:12px
}
th{
  background:linear-gradient(90deg, rgba(219,234,254,0.75), rgba(254,243,199,0.75));
  font-weight:900;color:var(--blue-800);
}
td.note{text-align:right;white-space:normal;min-width:280px}

.badge{
  display:inline-block;padding:4px 8px;border-radius:999px;font-size:11px;font-weight:900;
  border:1px solid rgba(245,158,11,0.22);
  background:rgba(254,243,199,0.62);
  color:#92400e;
}
.badge.warn{
  border-color:rgba(239,68,68,0.20);
  background:rgba(239,68,68,0.08);
  color:#7f1d1d;
}

/* ====== Autocomplete UI ====== */
.autocomplete-wrap{position:relative}
.suggest-box{
  position:absolute;top:100%;right:0;left:0;
  background:rgba(255,255,255,0.98);
  border:1px solid rgba(29,78,216,0.16);
  border-radius:14px;
  margin-top:6px;
  max-height:280px;
  overflow:auto;
  z-index:9999;
  display:none;
  box-shadow:0 18px 40px rgba(29,78,216,0.10), 0 16px 36px rgba(245,158,11,0.08);
}
.suggest-item{
  padding:10px 12px;
  border-bottom:1px solid rgba(29,78,216,0.08);
  cursor:pointer;
  text-align:right;
  transition:background .15s ease;
}
.suggest-item:hover{
  background:linear-gradient(90deg, rgba(219,234,254,0.55), rgba(254,243,199,0.55));
}
.suggest-item small{display:block;color:#475569;font-size:11px;margin-top:3px}
.selected-chip{
  margin-top:8px;
  display:none;
  padding:8px 10px;
  border-radius:12px;
  background:linear-gradient(90deg, rgba(219,234,254,0.75), rgba(254,243,199,0.75));
  border:1px solid rgba(29,78,216,0.14);
  color:var(--blue-800);
  font-weight:900;
}

/* تفاصيل */
.details-head{
  display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;
  margin-bottom:10px
}

/* حركة لطيفة للـ box عند الظهور */
.box{
  animation:popIn .45s.ease both;
}
@keyframes popIn{
  from{ opacity:0; transform:translateY(10px); }
  to{ opacity:1; transform:translateY(0); }
}
</style>
</head>

<body>

<!-- ✅ طبقات الخلفية المتحركة -->
<div class="bg-anim">
  <div class="stripes"></div>
  <div class="marks"></div>
  <div class="blob b1"></div>
  <div class="blob b2"></div>
  <div class="blob b3"></div>
</div>

<div class="container">
  <header>
    <div>
      <h1>🚨 إدارة سجل السلوك الإداري (الطلبة المشاكسين)</h1>
      <div class="subtitle">إضافة مخالفة للطالب + مشاهدة جميع مخالفاته بالتفاصيل + حذف كل مخالفة لوحدها.</div>
    </div>
    <div class="header-actions">
      <a class="btn" href="admin_dashboard.php">↩ العودة للوحة التحكم</a>
    </div>
  </header>

  <?php if ($msg !== ''): ?><div class="alert ok"><?php echo esc($msg); ?></div><?php endif; ?>
  <?php if ($err !== ''): ?><div class="alert err"><?php echo esc($err); ?></div><?php endif; ?>

  <!-- ✅ إضافة مخالفة (مرحلة + شعبة فوق وبنفس مستوى البحث) -->
  <div class="box">
    <form method="get" class="row" style="margin-bottom:12px">
      <div class="field">
        <label>المرحلة</label>
        <select name="stage" id="flt_stage" onchange="this.form.submit()">
          <option value="">جميع المراحل</option>
          <?php foreach ($stages as $st): ?>
            <option value="<?php echo esc($st); ?>" <?php echo ($st === $filter_stage) ? 'selected' : ''; ?>>
              <?php echo esc($st); ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="field">
        <label>الشعبة</label>
        <select name="class" id="flt_class" onchange="this.form.submit()">
          <option value="">جميع الشعب</option>
          <?php foreach ($classes as $c): ?>
            <option value="<?php echo esc($c); ?>" <?php echo ($c === $filter_class) ? 'selected' : ''; ?>>
              <?php echo esc($c); ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <?php if ($view !== 'student'): ?>
        <div class="field">
          <label>الفصل / الفترة</label>
          <select name="term" id="flt_term" onchange="this.form.submit()">
            <option value="">جميع الفصول</option>
            <?php foreach ($TERM_OPTIONS as $t): ?>
              <option value="<?php echo esc($t); ?>" <?php echo ($t === $filter_term) ? 'selected' : ''; ?>>
                <?php echo esc($t); ?>
              </option>
            <?php endforeach; ?>
            <option value="غير محدد" <?php echo ($filter_term === 'غير محدد') ? 'selected' : ''; ?>>غير محدد</option>
          </select>
        </div>
      <?php else: ?>
        <?php if ($filter_term !== ''): ?>
          <input type="hidden" name="term" value="<?php echo esc($filter_term); ?>">
        <?php endif; ?>
      <?php endif; ?>

      <?php if ($view === 'student' && $view_id > 0): ?>
        <input type="hidden" name="view" value="student">
        <input type="hidden" name="id" value="<?php echo (int)$view_id; ?>">
      <?php endif; ?>
    </form>

    <form method="post" class="row" id="addForm">
      <input type="hidden" name="action" value="add_behavior">
      <input type="hidden" name="student_id" id="student_id" value="">

      <div class="field autocomplete-wrap" style="flex:1 1 360px;min-width:320px">
        <label>بحث واختيار الطالب</label>
        <input type="text" id="student_search" placeholder="اكتب اسم الطالب..." autocomplete="off">
        <div class="suggest-box" id="suggestBox"></div>
        <div class="selected-chip" id="selectedChip"></div>
      </div>

      <div class="field">
        <label>نوع المخالفة</label>
        <input type="text" name="problem_type" placeholder="مثال: سوء سلوك / غش / تأخير ..." required>
      </div>

      <div class="field">
        <label>تاريخ المخالفة</label>
        <input type="date" name="problem_date" value="<?php echo esc($today); ?>" required>
      </div>

      <div class="field">
        <label>الفصل / الفترة</label>
        <?php $selected_term = (isset($_POST['school_term']) && in_array($_POST['school_term'], $TERM_OPTIONS, true)) ? $_POST['school_term'] : 'الفصل الأول'; ?>
        <select name="school_term" required>
          <?php foreach ($TERM_OPTIONS as $t): ?>
            <option value="<?php echo esc($t); ?>" <?php echo ($selected_term === $t) ? 'selected' : ''; ?>>
              <?php echo esc($t); ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="field" style="flex:1 1 420px;min-width:320px">
        <label>ملاحظة (اختياري)</label>
        <textarea name="problem_note" placeholder="اكتب تفاصيل المخالفة..."></textarea>
      </div>

      <button type="submit">➕ تسجيل المخالفة</button>
    </form>
  </div>

  <?php if ($view === 'student' && $student_info): ?>
    <!-- ✅ تفاصيل طالب واحد -->
    <div class="box">
      <div class="details-head">
        <div>
          <b>🧾 تفاصيل الطالب:</b>
          <span class="badge"><?php echo esc($student_info['name']); ?></span>
          <span class="badge"><?php echo esc($student_info['stage']); ?> / <?php echo esc($student_info['class']); ?></span>
          <span class="badge.warn"><?php echo count($student_behaviors); ?> مشكلة</span>
        </div>
        <a class="btn blue" href="<?php echo esc($back_url); ?>">↩ رجوع للقائمة</a>
      </div>

      <?php if ($edit_mode && $edit_behavior): ?>
        <?php
          $cqs = array('view'=>'student','id'=>(int)$student_info['id']);
          if ($filter_stage !== '') $cqs['stage'] = $filter_stage;
          if ($filter_class !== '') $cqs['class'] = $filter_class;
          if ($filter_term !== '') $cqs['term'] = $filter_term;
          $cancel_edit_url = "admin_behavior_manage.php?".http_build_query($cqs);
        ?>
        <div class="box" style="border-color:rgba(245,158,11,0.35);background:rgba(255,255,255,0.94)">
          <div style="font-weight:900;color:var(--blue-800);margin-bottom:10px">✏️ تعديل المخالفة</div>
          <!-- ✅ فورم التعديل مع باسورد -->
          <form method="post" class="row" onsubmit="return confirmEdit(this);">
            <input type="hidden" name="action" value="update_behavior">
            <input type="hidden" name="behavior_id" value="<?php echo (int)$edit_behavior['id']; ?>">
            <input type="hidden" name="student_id" value="<?php echo (int)$student_info['id']; ?>">
            <input type="hidden" name="update_password" value="">

            <div class="field">
              <label>الفصل / الفترة</label>
              <select name="school_term" required>
                <?php foreach ($TERM_OPTIONS as $t): ?>
                  <option value="<?php echo esc($t); ?>" <?php echo (isset($edit_behavior['school_term']) && $edit_behavior['school_term'] === $t) ? 'selected' : ''; ?>>
                    <?php echo esc($t); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="field">
              <label>نوع المخالفة</label>
              <input type="text" name="problem_type" value="<?php echo esc($edit_behavior['problem_type']); ?>" required>
            </div>

            <div class="field">
              <label>تاريخ المخالفة</label>
              <input type="date" name="problem_date" value="<?php echo esc($edit_behavior['problem_date']); ?>" required>
            </div>

            <div class="field" style="flex:1 1 420px;min-width:320px">
              <label>ملاحظة (اختياري)</label>
              <textarea name="problem_note" placeholder="اكتب تفاصيل المخالفة..."><?php echo (isset($edit_behavior['problem_note']) && $edit_behavior['problem_note'] !== null) ? esc($edit_behavior['problem_note']) : ''; ?></textarea>
            </div>

            <button type="submit">💾 حفظ التعديل</button>
            <a class="btn red" href="<?php echo esc($cancel_edit_url); ?>">إلغاء</a>
          </form>
        </div>
      <?php endif; ?>

      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>نوع المخالفة</th>
              <th>التاريخ</th>
              <th>الفصل</th>
              <th>التكرار</th>
              <th>الملاحظة</th>
              <th>وقت الإدخال</th>
              <th>إجراء</th>
            </tr>
          </thead>
          <tbody>
          <?php if (count($student_behaviors) === 0): ?>
            <tr><td colspan="8" style="color:#7f1d1d;font-weight:900">لا توجد مشاكل لهذا الطالب.</td></tr>
          <?php else: ?>
            <?php $i=1; foreach ($student_behaviors as $r): ?>
              <tr>
                <td><?php echo $i++; ?></td>
                <td><span class="badge"><?php echo esc($r['problem_type']); ?></span></td>
                <td><?php echo esc($r['problem_date']); ?></td>
                <td><?php echo (isset($r['school_term']) && trim($r['school_term']) !== '') ? '<span class="badge">'.esc($r['school_term']).'</span>' : '<span class="badge.warn">غير محدد</span>'; ?></td>
                <td>
                  <?php
                    $pc = isset($r['problem_count']) ? (int)$r['problem_count'] : 1;
                    if ($pc > 1) echo '<span class="badge.warn">× '.$pc.'</span>';
                    else echo '<span class="badge">1</span>';
                  ?>
                </td>
                <td class="note"><?php echo ($r['problem_note'] !== null && trim($r['problem_note']) !== '') ? nl2br(esc($r['problem_note'])) : '—'; ?></td>
                <td><?php echo esc($r['created_at']); ?></td>
                <td>
                  <div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap">
                    <?php
                      $eqs = array('view'=>'student','id'=>(int)$student_info['id'],'edit'=>'1','behavior_id'=>(int)$r['id']);
                      if ($filter_stage !== '') $eqs['stage'] = $filter_stage;
                      if ($filter_class !== '') $eqs['class'] = $filter_class;
                      if ($filter_term !== '') $eqs['term'] = $filter_term;
                      $edit_url = "admin_behavior_manage.php?".http_build_query($eqs);
                    ?>
                    <a class="btn blue" href="<?php echo esc($edit_url); ?>">✏️ تعديل</a>

                    <!-- ✅ فورم الحذف مع طلب باسورد -->
                    <form method="post" onsubmit="return confirmDelete(this);">
                      <input type="hidden" name="action" value="delete_behavior">
                      <input type="hidden" name="behavior_id" value="<?php echo (int)$r['id']; ?>">
                      <input type="hidden" name="student_id" value="<?php echo (int)$student_info['id']; ?>">
                      <input type="hidden" name="delete_password" value="">
                      <button class="danger" type="submit">🗑️ حذف</button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>

  <!-- ✅ قائمة الطلاب -->
  <div class="box">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:10px">
      <div><b>📋 قائمة الطلبة الذين لديهم مشاكل</b> <span class="badge"><?php echo count($students_list); ?> طالب</span></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>
          </tr>
        </thead>
        <tbody>
        <?php if (count($students_list) === 0): ?>
          <tr><td colspan="8" style="color:#7f1d1d;font-weight:900">لا توجد بيانات.</td></tr>
        <?php else: ?>
          <?php $i=1; foreach ($students_list as $r): ?>
            <tr>
              <td><?php echo $i++; ?></td>
              <td style="text-align:right;font-weight:900"><?php echo esc($r['name']); ?></td>
              <td><?php echo esc($r['stage']); ?></td>
              <td><?php echo esc($r['class']); ?></td>
              <td><span class="badge.warn"><?php echo (int)$r['issues_count']; ?></span></td>
              <td>
                <?php
                  $terms = array();
                  if (isset($r['terms_list']) && trim($r['terms_list']) !== '') {
                      $terms = explode(' | ', $r['terms_list']);
                  }
                  if (count($terms) === 0) {
                      echo '—';
                  } else {
                      for ($ti=0;$ti<count($terms);$ti++) {
                          $t = trim($terms[$ti]);
                          if ($t === '') continue;
                          echo '<span class="badge">'.esc($t).'</span> ';
                      }
                  }
                ?>
              </td>
              <td><?php echo esc($r['last_problem_date']); ?></td>
              <td>
                <?php
                  $qs = array('view' => 'student', 'id' => (int)$r['student_id']);
                  if ($filter_stage !== '') $qs['stage'] = $filter_stage;
                  if ($filter_class !== '') $qs['class'] = $filter_class;
                  if ($filter_term !== '') $qs['term'] = $filter_term;
                  $details_url = "admin_behavior_manage.php?" . http_build_query($qs);
                ?>
                <a class="btn blue" href="<?php echo esc($details_url); ?>">🔎 التفاصيل</a>
              </td>
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>

<script>
/* ✅ دالة تأكيد الحذف مع طلب كلمة مرور 0100 (بدون إظهار الرقم في الرسالة) */
function confirmDelete(form){
  var pass = prompt("لمنع الحذف بالخطأ، أدخل كلمة المرور الخاصة بالحذف:");
  if (pass === null) {
    // تم إلغاء الـ prompt
    return false;
  }
  pass = pass.trim();
  if (pass !== "0100") {
    alert("❌ كلمة المرور غير صحيحة، لم يتم الحذف.");
    return false;
  }

  // وضع كلمة المرور في الحقل المخفي داخل نفس الفورم
  var hidden = form.querySelector('input[name="delete_password"]');
  if (hidden) {
    hidden.value = pass;
  }

  return confirm("هل أنت متأكد من حذف هذه المشكلة؟");
}

/* ✅ دالة تأكيد التعديل مع طلب كلمة مرور 0100 (بدون إظهار الرقم في الرسالة) */
function confirmEdit(form){
  var pass = prompt("لمنع التعديل بالخطأ، أدخل كلمة المرور الخاصة بالتعديل:");
  if (pass === null) {
    // تم إلغاء الـ prompt
    return false;
  }
  pass = pass.trim();
  if (pass !== "0100") {
    alert("❌ كلمة المرور غير صحيحة، لم يتم حفظ التعديل.");
    return false;
  }

  // وضع كلمة المرور في الحقل المخفي داخل نفس الفورم
  var hidden = form.querySelector('input[name="update_password"]');
  if (hidden) {
    hidden.value = pass;
  }

  return confirm("هل أنت متأكد من حفظ هذا التعديل؟");
}

(function(){
  var input   = document.getElementById('student_search');
  var box     = document.getElementById('suggestBox');
  var hid     = document.getElementById('student_id');
  var chip    = document.getElementById('selectedChip');

  var stageSel = document.getElementById('flt_stage');
  var classSel = document.getElementById('flt_class');

  var timer = null;
  var lastTerm = '';

  function hideBox(){ box.style.display = 'none'; box.innerHTML = ''; }
  function showBox(){ box.style.display = 'block'; }

  function escapeHtml(str){
    // يدعم المتصفحات القديمة بدون replaceAll
    return String(str)
      .replace(/&/g,'&amp;')
      .replace(/<//g,'&lt;')
      .replace(/>/g,'&gt;')
      .replace(/"/g,'&quot;')
      .replace(/'/g,'&#039;');
  }

  function setSelected(s){
    hid.value = s.id;
    input.value = s.name;
    chip.style.display = 'block';
    chip.innerHTML = "✅ تم اختيار: <b>" + escapeHtml(s.name) + "</b> — (" + escapeHtml(s.stage) + " / " + escapeHtml(s.class) + ") [ID: " + s.id + "]";
    hideBox();
  }

  function fetchStudents(term){
    var stage = stageSel ? stageSel.value : '';
    var clas  = classSel ? classSel.value : '';

    var url = "admin_behavior_manage.php?ajax=student_search"
            + "&term=" + encodeURIComponent(term)
            + "&stage=" + encodeURIComponent(stage)
            + "&class=" + encodeURIComponent(clas);

    fetch(url).then(function(r){ return r.json(); }).then(function(data){
      box.innerHTML = '';
      if (!data || data.length === 0) { hideBox(); return; }

      for (var i=0;i<data.length;i++){
        (function(s){
          var div = document.createElement('div');
          div.className = 'suggest-item';
          div.innerHTML = "<b>" + escapeHtml(s.name) + "</b>"
                        + "<small>" + escapeHtml(s.stage) + " / " + escapeHtml(s.class) + " — ID: " + s.id + "</small>";
          div.onclick = function(){ setSelected(s); };
          box.appendChild(div);
        })(data[i]);
      }

      showBox();
    }).catch(function(){ hideBox(); });
  }

  input.addEventListener('input', function(){
    var term = input.value.replace(/^\s+|\s+$/g,'');
    hid.value = '';
    chip.style.display = 'none';
    chip.innerHTML = '';

    if (term.length < 1) { hideBox(); return; }

    if (timer) clearTimeout(timer);
    timer = setTimeout(function(){
      if (term === lastTerm) return;
      lastTerm = term;
      fetchStudents(term);
    }, 220);
  });

  document.addEventListener('click', function(e){
    if (!box.contains(e.target) && e.target !== input) hideBox();
  });

  document.getElementById('addForm').addEventListener('submit', function(e){
    if (!hid.value || parseInt(hid.value, 10) <= 0) {
      alert("⚠️ لازم تختار الطالب من القائمة (مو فقط تكتب الاسم).");
      e.preventDefault();
    }
  });
})();
</script>

</body>
</html>
