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

/*
  ======================================================
  صفحة متابعة أقساط الطلبة
  - تحديد قسط لكل طالب أو بشكل جماعي
  - تسجيل الدفعات
  - عرض المدفوع والمتبقي والحالة
  - متوافقة مع PHP قديم بدون ?? وبدون get_result
  ======================================================
*/

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}

if (function_exists('mysqli_set_charset')) {
    mysqli_set_charset($conn, "utf8mb4");
}

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

function h($s) {
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function jsq($s) {
    $s = (string)$s;
    $s = str_replace("\\", "\\\\", $s);
    $s = str_replace("'", "\\'", $s);
    $s = str_replace("\r", " ", $s);
    $s = str_replace("\n", " ", $s);
    return $s;
}

function money_iqd($n) {
    return number_format((float)$n, 0) . ' د.ع';
}

function current_academic_year_fee() {
    $y = (int)date('Y');
    $m = (int)date('n');
    if ($m >= 9) {
        return $y . '-' . ($y + 1);
    }
    return ($y - 1) . '-' . $y;
}

function fee_status($final_amount, $paid) {
    $final_amount = (float)$final_amount;
    $paid = (float)$paid;
    if ($final_amount <= 0) {
        return 'no_fee';
    }
    if ($paid <= 0) {
        return 'unpaid';
    }
    if ($paid + 0.01 >= $final_amount) {
        return 'paid';
    }
    return 'partial';
}

function fee_status_label($st) {
    if ($st == 'paid') return 'مسدد بالكامل';
    if ($st == 'partial') return 'تسديد جزئي';
    if ($st == 'unpaid') return 'غير مسدد';
    return 'لم يحدد القسط';
}

function fee_status_class($st) {
    if ($st == 'paid') return 'paid';
    if ($st == 'partial') return 'partial';
    if ($st == 'unpaid') return 'unpaid';
    return 'no_fee';
}

function upsert_fee($conn, $student_id, $academic_year, $total_amount, $discount, $notes) {
    $student_id = (int)$student_id;
    $academic_year_s = mysqli_real_escape_string($conn, $academic_year);
    $notes_s = mysqli_real_escape_string($conn, $notes);
    $total_amount = (float)$total_amount;
    $discount = (float)$discount;
    if ($discount < 0) $discount = 0;
    if ($discount > $total_amount) $discount = $total_amount;
    $final_amount = $total_amount - $discount;

    if ($student_id <= 0 || $academic_year == '') {
        return false;
    }

    $check = mysqli_query($conn, "SELECT id FROM student_fees WHERE student_id='$student_id' AND academic_year='$academic_year_s' LIMIT 1");
    if ($check && mysqli_num_rows($check) > 0) {
        $r = mysqli_fetch_assoc($check);
        $id = (int)$r['id'];
        return mysqli_query($conn, "UPDATE student_fees SET total_amount='$total_amount', discount='$discount', final_amount='$final_amount', notes='$notes_s', updated_at=NOW() WHERE id='$id' LIMIT 1");
    }

    return mysqli_query($conn, "INSERT INTO student_fees (student_id, academic_year, total_amount, discount, final_amount, notes, created_at, updated_at) VALUES ('$student_id', '$academic_year_s', '$total_amount', '$discount', '$final_amount', '$notes_s', NOW(), NOW())");
}

/* إنشاء الجداول تلقائياً لتقليل مشاكل الاستضافة */
mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `student_fees` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `student_id` INT(11) NOT NULL,
  `academic_year` VARCHAR(20) NOT NULL,
  `total_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `discount` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `final_amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `notes` TEXT NULL,
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_student_year` (`student_id`,`academic_year`),
  KEY `idx_year` (`academic_year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");

mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `student_fee_payments` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `fee_id` INT(11) NOT NULL,
  `amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `payment_date` DATE NOT NULL,
  `payment_method` VARCHAR(50) DEFAULT 'cash',
  `receipt_no` VARCHAR(80) DEFAULT NULL,
  `note` TEXT NULL,
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_fee` (`fee_id`),
  KEY `idx_payment_date` (`payment_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");

$success = '';
$error = '';
$year = isset($_GET['year']) && trim($_GET['year']) != '' ? trim($_GET['year']) : current_academic_year_fee();
$year_s = mysqli_real_escape_string($conn, $year);

/* إجراءات الحفظ */
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';

    if ($action == 'save_fee') {
        $student_id = isset($_POST['student_id']) ? intval($_POST['student_id']) : 0;
        $academic_year = isset($_POST['academic_year']) ? trim($_POST['academic_year']) : $year;
        $total_amount = isset($_POST['total_amount']) ? floatval(str_replace(',', '', $_POST['total_amount'])) : 0;
        $discount = isset($_POST['discount']) ? floatval(str_replace(',', '', $_POST['discount'])) : 0;
        $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

        if ($student_id <= 0 || $academic_year == '' || $total_amount < 0) {
            $error = 'يرجى إدخال بيانات القسط بصورة صحيحة.';
        } else {
            if (upsert_fee($conn, $student_id, $academic_year, $total_amount, $discount, $notes)) {
                $success = 'تم حفظ قسط الطالب بنجاح.';
                $year = $academic_year;
                $year_s = mysqli_real_escape_string($conn, $year);
            } else {
                $error = 'حدث خطأ أثناء حفظ القسط: ' . mysqli_error($conn);
            }
        }
    }

    if ($action == 'bulk_fee') {
        $academic_year = isset($_POST['academic_year']) ? trim($_POST['academic_year']) : $year;
        $bulk_stage = isset($_POST['bulk_stage']) ? trim($_POST['bulk_stage']) : '';
        $bulk_class = isset($_POST['bulk_class']) ? trim($_POST['bulk_class']) : '';
        $total_amount = isset($_POST['total_amount']) ? floatval(str_replace(',', '', $_POST['total_amount'])) : 0;
        $discount = isset($_POST['discount']) ? floatval(str_replace(',', '', $_POST['discount'])) : 0;
        $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

        if ($academic_year == '' || $total_amount < 0) {
            $error = 'يرجى إدخال السنة الدراسية ومبلغ القسط.';
        } else {
            $where_bulk = " WHERE 1=1 ";
            if ($bulk_stage != '') {
                $where_bulk .= " AND stage='" . mysqli_real_escape_string($conn, $bulk_stage) . "' ";
            }
            if ($bulk_class != '') {
                $where_bulk .= " AND `class`='" . mysqli_real_escape_string($conn, $bulk_class) . "' ";
            }

            $students_bulk = mysqli_query($conn, "SELECT id FROM students $where_bulk");
            $done = 0;
            if ($students_bulk) {
                while ($sb = mysqli_fetch_assoc($students_bulk)) {
                    if (upsert_fee($conn, (int)$sb['id'], $academic_year, $total_amount, $discount, $notes)) {
                        $done++;
                    }
                }
            }
            $success = 'تم تحديد القسط لـ ' . $done . ' طالب بنجاح.';
            $year = $academic_year;
            $year_s = mysqli_real_escape_string($conn, $year);
        }
    }

    if ($action == 'add_payment') {
        $fee_id = isset($_POST['fee_id']) ? intval($_POST['fee_id']) : 0;
        $amount = isset($_POST['amount']) ? floatval(str_replace(',', '', $_POST['amount'])) : 0;
        $payment_date = isset($_POST['payment_date']) ? trim($_POST['payment_date']) : date('Y-m-d');
        $payment_method = isset($_POST['payment_method']) ? trim($_POST['payment_method']) : 'cash';
        $receipt_no = isset($_POST['receipt_no']) ? trim($_POST['receipt_no']) : '';
        $note = isset($_POST['note']) ? trim($_POST['note']) : '';

        if ($fee_id <= 0 || $amount <= 0 || $payment_date == '') {
            $error = 'يرجى إدخال مبلغ الدفعة وتاريخها بصورة صحيحة.';
        } else {
            $method_s = mysqli_real_escape_string($conn, $payment_method);
            $receipt_s = mysqli_real_escape_string($conn, $receipt_no);
            $note_s = mysqli_real_escape_string($conn, $note);
            $date_s = mysqli_real_escape_string($conn, $payment_date);

            if ($receipt_no == '') {
                $receipt_s = 'RCPT-' . date('YmdHis') . '-' . rand(100, 999);
            }

            if (mysqli_query($conn, "INSERT INTO student_fee_payments (fee_id, amount, payment_date, payment_method, receipt_no, note, created_at) VALUES ('$fee_id', '$amount', '$date_s', '$method_s', '$receipt_s', '$note_s', NOW())")) {
                $success = 'تم تسجيل الدفعة بنجاح.';
            } else {
                $error = 'حدث خطأ أثناء تسجيل الدفعة: ' . mysqli_error($conn);
            }
        }
    }

    if ($action == 'delete_payment') {
        $payment_id = isset($_POST['payment_id']) ? intval($_POST['payment_id']) : 0;
        if ($payment_id > 0) {
            if (mysqli_query($conn, "DELETE FROM student_fee_payments WHERE id='$payment_id' LIMIT 1")) {
                $success = 'تم حذف الدفعة بنجاح.';
            } else {
                $error = 'حدث خطأ أثناء حذف الدفعة: ' . mysqli_error($conn);
            }
        }
    }

    if ($action == 'delete_fee') {
        $fee_id = isset($_POST['fee_id']) ? intval($_POST['fee_id']) : 0;
        if ($fee_id > 0) {
            mysqli_query($conn, "DELETE FROM student_fee_payments WHERE fee_id='$fee_id'");
            if (mysqli_query($conn, "DELETE FROM student_fees WHERE id='$fee_id' LIMIT 1")) {
                $success = 'تم حذف القسط ودفعاته بنجاح.';
            } else {
                $error = 'حدث خطأ أثناء حذف القسط: ' . mysqli_error($conn);
            }
        }
    }
}

/* فلاتر */
$stage = isset($_GET['stage']) ? trim($_GET['stage']) : '';
$class = isset($_GET['class']) ? trim($_GET['class']) : '';
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$status_filter = isset($_GET['status']) ? trim($_GET['status']) : '';

/* المراحل والشعب */
$stages = array();
$res_st = mysqli_query($conn, "SELECT DISTINCT stage FROM students WHERE TRIM(stage)<>'' ORDER BY stage ASC");
if ($res_st) {
    while ($r = mysqli_fetch_assoc($res_st)) {
        $stages[] = $r['stage'];
    }
}
$classes = array();
$where_class = " WHERE TRIM(`class`)<>'' ";
if ($stage != '') {
    $where_class .= " AND stage='" . mysqli_real_escape_string($conn, $stage) . "' ";
}
$res_cl = mysqli_query($conn, "SELECT DISTINCT `class` FROM students $where_class ORDER BY `class` ASC");
if ($res_cl) {
    while ($r = mysqli_fetch_assoc($res_cl)) {
        $classes[] = $r['class'];
    }
}

/* جلب الطلبة والأقساط */
$where = " WHERE 1=1 ";
if ($stage != '') {
    $where .= " AND s.stage='" . mysqli_real_escape_string($conn, $stage) . "' ";
}
if ($class != '') {
    $where .= " AND s.`class`='" . mysqli_real_escape_string($conn, $class) . "' ";
}
if ($q != '') {
    $q_s = mysqli_real_escape_string($conn, $q);
    $where .= " AND (s.name LIKE '%$q_s%' OR s.stage LIKE '%$q_s%' OR s.`class` LIKE '%$q_s%') ";
}

$sql = "
SELECT
  s.id AS student_id,
  s.name,
  s.stage,
  s.`class`,
  f.id AS fee_id,
  f.academic_year,
  f.total_amount,
  f.discount,
  f.final_amount,
  f.notes,
  COALESCE(SUM(p.amount),0) AS paid_amount,
  MAX(p.payment_date) AS last_payment
FROM students s
LEFT JOIN student_fees f ON f.student_id=s.id AND f.academic_year='$year_s'
LEFT JOIN student_fee_payments p ON p.fee_id=f.id
$where
GROUP BY s.id, s.name, s.stage, s.`class`, f.id, f.academic_year, f.total_amount, f.discount, f.final_amount, f.notes
ORDER BY s.stage ASC, s.`class` ASC, s.name ASC
";

$res = mysqli_query($conn, $sql);
$rows = array();
$total_final = 0;
$total_paid = 0;
$total_remaining = 0;
$count_paid = 0;
$count_partial = 0;
$count_unpaid = 0;
$count_no_fee = 0;

if ($res) {
    while ($r = mysqli_fetch_assoc($res)) {
        $final_amount = isset($r['final_amount']) ? (float)$r['final_amount'] : 0;
        $paid_amount = isset($r['paid_amount']) ? (float)$r['paid_amount'] : 0;
        $remaining = max(0, $final_amount - $paid_amount);
        $st = fee_status($final_amount, $paid_amount);

        if ($status_filter != '' && $st != $status_filter) {
            continue;
        }

        $r['remaining'] = $remaining;
        $r['fee_status'] = $st;
        $rows[] = $r;

        $total_final += $final_amount;
        $total_paid += $paid_amount;
        $total_remaining += $remaining;

        if ($st == 'paid') $count_paid++;
        elseif ($st == 'partial') $count_partial++;
        elseif ($st == 'unpaid') $count_unpaid++;
        else $count_no_fee++;
    }
}

/* دفعات السنة الحالية */
$payments_by_fee = array();
$pay_res = mysqli_query($conn, "
SELECT p.*, f.id AS fee_id
FROM student_fee_payments p
INNER JOIN student_fees f ON f.id=p.fee_id
WHERE f.academic_year='$year_s'
ORDER BY p.payment_date DESC, p.id DESC
");
if ($pay_res) {
    while ($p = mysqli_fetch_assoc($pay_res)) {
        $fid = (int)$p['fee_id'];
        if (!isset($payments_by_fee[$fid])) $payments_by_fee[$fid] = array();
        $payments_by_fee[$fid][] = $p;
    }
}

function selected_attr($a, $b) {
    return ((string)$a === (string)$b) ? 'selected' : '';
}
?>
<!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;500;700;800;900&display=swap" rel="stylesheet">
<style>
:root{--navy:#07192f;--blue:#0f3a63;--gold:#f59e0b;--cyan:#06b6d4;--green:#16a34a;--red:#dc2626;--muted:#64748b}
*{box-sizing:border-box}
body{margin:0;font-family:Tajawal,Arial;background:
radial-gradient(circle at 15% 12%,rgba(6,182,212,.18),transparent 25%),
radial-gradient(circle at 85% 20%,rgba(245,158,11,.16),transparent 25%),
linear-gradient(135deg,#eef6ff,#f8fafc,#fff7ed);color:#0f172a}
a{text-decoration:none}
.page{width:95%;max-width:1500px;margin:22px auto 45px}
.header{background:linear-gradient(135deg,var(--navy),var(--blue));color:#fff;border-radius:30px;padding:22px;display:grid;grid-template-columns:70px 1fr auto;gap:16px;align-items:center;box-shadow:0 24px 65px rgba(15,23,42,.2)}
.header img{width:70px;height:70px;object-fit:contain;background:#fff;border-radius:20px;padding:7px}
.header h1{margin:0 0 5px;font-size:25px}
.header p{margin:0;color:#dbeafe;line-height:1.7}
.header-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}
.btn{border:0;border-radius:14px;padding:11px 14px;font-family:Tajawal;font-weight:900;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:6px;transition:.2s}
.btn:hover{transform:translateY(-2px)}
.primary{background:linear-gradient(135deg,#0891b2,#0ea5e9);color:#fff}
.gold{background:#fff7db;color:#7c4a03}
.dark{background:#0f172a;color:#fff}
.green{background:#16a34a;color:#fff}
.red{background:#dc2626;color:#fff}
.gray{background:#e2e8f0;color:#0f172a}
.stats{display:grid;grid-template-columns:repeat(5,1fr);gap:13px;margin:18px 0}
.stat{background:#fff;border-radius:22px;padding:18px;box-shadow:0 15px 40px rgba(15,23,42,.08);border:1px solid #edf2f7}
.stat span{display:block;color:var(--muted);font-size:13px;font-weight:900}
.stat b{display:block;font-size:25px;margin-top:6px;color:#0f3a63}
.alert{padding:14px;border-radius:16px;font-weight:900;text-align:center;margin:14px 0}
.success{background:#dcfce7;color:#166534;border:1px solid #bbf7d0}
.error{background:#fee2e2;color:#991b1b;border:1px solid #fecaca}
.panel{background:#fff;border-radius:26px;padding:18px;box-shadow:0 15px 40px rgba(15,23,42,.08);border:1px solid #edf2f7;margin:16px 0}
.panel-title{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px}
.panel-title h2{margin:0;font-size:20px}
.filters{display:grid;grid-template-columns:1fr 1fr 1fr 1.2fr 1fr auto auto;gap:10px;align-items:end}
.bulk{display:grid;grid-template-columns:1fr 1fr 1fr 1fr 1fr 1.2fr auto;gap:10px;align-items:end}
.field{display:flex;flex-direction:column;gap:6px}
label{font-size:13px;font-weight:900;color:#334155}
input,select,textarea{width:100%;border:1px solid #cbd5e1;border-radius:14px;padding:11px 12px;font-family:Tajawal;background:#fff;outline:none}
input:focus,select:focus,textarea:focus{border-color:#0ea5e9;box-shadow:0 0 0 3px rgba(14,165,233,.12)}
.table-wrap{overflow:auto;border-radius:22px;border:1px solid #e2e8f0}
table{width:100%;border-collapse:collapse;min-width:1180px;background:#fff}
th{background:#0f3a63;color:#fff;text-align:right;padding:13px;font-size:13px;white-space:nowrap}
td{padding:12px;border-bottom:1px solid #edf2f7;vertical-align:top}
tr:hover td{background:#f8fafc}
.student-name{font-weight:900;color:#0f3a63}
.small{display:block;color:#64748b;font-size:12px;margin-top:4px}
.status{border-radius:999px;padding:7px 10px;font-size:12px;font-weight:900;display:inline-flex}
.status.paid{background:#dcfce7;color:#166534}
.status.partial{background:#fef3c7;color:#92400e}
.status.unpaid{background:#fee2e2;color:#991b1b}
.status.no_fee{background:#e2e8f0;color:#334155}
.actions{display:flex;gap:7px;flex-wrap:wrap}
.details{margin-top:9px}
details{background:#f8fafc;border:1px solid #e2e8f0;border-radius:14px;padding:8px}
summary{cursor:pointer;font-weight:900;color:#0f3a63}
.pay-item{display:grid;grid-template-columns:1fr 1fr 1fr auto;gap:7px;align-items:center;padding:8px;border-bottom:1px solid #e2e8f0;font-size:13px}
.pay-item:last-child{border-bottom:0}
.modal{display:none;position:fixed;inset:0;background:rgba(15,23,42,.58);z-index:9999;align-items:center;justify-content:center;padding:15px}
.modal.show{display:flex}
.modal-card{background:#fff;border-radius:24px;padding:20px;max-width:560px;width:100%;box-shadow:0 25px 80px rgba(0,0,0,.25)}
.modal-card h3{margin:0 0 6px;color:#0f3a63}
.modal-card p{margin:0 0 14px;color:#64748b}
.modal-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.modal-actions{display:grid;grid-template-columns:1fr 120px;gap:10px;margin-top:14px}
@media(max-width:1100px){.stats{grid-template-columns:1fr 1fr}.filters,.bulk{grid-template-columns:1fr 1fr}.header{grid-template-columns:1fr;text-align:center}.header img{margin:auto}.header-actions{justify-content:center}}
@media(max-width:650px){.stats,.filters,.bulk,.modal-grid,.modal-actions{grid-template-columns:1fr}.header-actions .btn{width:100%}.page{width:96%}}
</style>
</head>
<body>
<div class="page">
  <div class="header">
    <img src="logo.png" alt="logo">
    <div>
      <h1>💰 متابعة أقساط الطلبة</h1>
      <p>لوحة مالية لإدارة القسط السنوي، الدفعات، المتبقي، حالات التسديد، والبحث حسب المرحلة والشعبة والطالب.</p>
    </div>
    <div class="header-actions">
      <a class="btn gold" href="admin_dashboard.php">لوحة التحكم</a>
      <a class="btn dark" href="registration/admin_registrations.php">طلبات التسجيل</a>
      <a class="btn primary" href="admin_students.php">إدارة الطلبة</a>
    </div>
  </div>

  <?php if ($success != '') { ?><div class="alert success"><?php echo h($success); ?></div><?php } ?>
  <?php if ($error != '') { ?><div class="alert error"><?php echo h($error); ?></div><?php } ?>

  <div class="stats">
    <div class="stat"><span>عدد الطلبة المعروضين</span><b><?php echo count($rows); ?></b></div>
    <div class="stat"><span>إجمالي الأقساط</span><b><?php echo money_iqd($total_final); ?></b></div>
    <div class="stat"><span>المدفوع</span><b><?php echo money_iqd($total_paid); ?></b></div>
    <div class="stat"><span>المتبقي</span><b><?php echo money_iqd($total_remaining); ?></b></div>
    <div class="stat"><span>مسدد / جزئي / غير مسدد</span><b><?php echo $count_paid; ?> / <?php echo $count_partial; ?> / <?php echo $count_unpaid; ?></b></div>
  </div>

  <div class="panel">
    <div class="panel-title">
      <h2>فلاتر البحث</h2>
      <span class="small">السنة الدراسية الحالية: <?php echo h($year); ?></span>
    </div>
    <form method="GET" class="filters">
      <div class="field"><label>السنة الدراسية</label><input name="year" value="<?php echo h($year); ?>" placeholder="2025-2026"></div>
      <div class="field"><label>المرحلة</label><select name="stage"><option value="">كل المراحل</option><?php foreach($stages as $stg){ ?><option value="<?php echo h($stg); ?>" <?php echo selected_attr($stage,$stg); ?>><?php echo h($stg); ?></option><?php } ?></select></div>
      <div class="field"><label>الشعبة</label><select name="class"><option value="">كل الشعب</option><?php foreach($classes as $cl){ ?><option value="<?php echo h($cl); ?>" <?php echo selected_attr($class,$cl); ?>><?php echo h($cl); ?></option><?php } ?></select></div>
      <div class="field"><label>بحث</label><input name="q" value="<?php echo h($q); ?>" placeholder="اسم الطالب / المرحلة / الشعبة"></div>
      <div class="field"><label>حالة القسط</label><select name="status"><option value="">كل الحالات</option><option value="paid" <?php echo selected_attr($status_filter,'paid'); ?>>مسدد بالكامل</option><option value="partial" <?php echo selected_attr($status_filter,'partial'); ?>>تسديد جزئي</option><option value="unpaid" <?php echo selected_attr($status_filter,'unpaid'); ?>>غير مسدد</option><option value="no_fee" <?php echo selected_attr($status_filter,'no_fee'); ?>>لم يحدد القسط</option></select></div>
      <button class="btn primary" type="submit">تصفية</button>
      <a class="btn gray" href="admin_fees.php">مسح</a>
    </form>
  </div>

  <div class="panel">
    <div class="panel-title">
      <h2>تحديد قسط جماعي</h2>
      <span class="small">اترك المرحلة أو الشعبة فارغة لتطبيقها على الكل</span>
    </div>
    <form method="POST" class="bulk">
      <input type="hidden" name="action" value="bulk_fee">
      <div class="field"><label>السنة الدراسية</label><input name="academic_year" value="<?php echo h($year); ?>" required></div>
      <div class="field"><label>المرحلة</label><select name="bulk_stage"><option value="">كل المراحل</option><?php foreach($stages as $stg){ ?><option value="<?php echo h($stg); ?>"><?php echo h($stg); ?></option><?php } ?></select></div>
      <div class="field"><label>الشعبة</label><input name="bulk_class" placeholder="مثلاً A أو اتركها فارغة"></div>
      <div class="field"><label>القسط الكلي</label><input name="total_amount" type="number" step="1" min="0" required placeholder="مثلاً 1500000"></div>
      <div class="field"><label>خصم</label><input name="discount" type="number" step="1" min="0" value="0"></div>
      <div class="field"><label>ملاحظة</label><input name="notes" placeholder="اختياري"></div>
      <button class="btn green" type="submit">تطبيق</button>
    </form>
  </div>

  <div class="panel">
    <div class="panel-title">
      <h2>جدول الأقساط والدفعات</h2>
      <span class="small">اضغط على اسم الدفعات لعرض السجل</span>
    </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>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php if (count($rows) > 0) { ?>
            <?php foreach ($rows as $r) {
              $fee_id = isset($r['fee_id']) ? intval($r['fee_id']) : 0;
              $total_amount = isset($r['total_amount']) ? (float)$r['total_amount'] : 0;
              $discount = isset($r['discount']) ? (float)$r['discount'] : 0;
              $final_amount = isset($r['final_amount']) ? (float)$r['final_amount'] : 0;
              $paid_amount = isset($r['paid_amount']) ? (float)$r['paid_amount'] : 0;
              $remaining = isset($r['remaining']) ? (float)$r['remaining'] : 0;
              $st = $r['fee_status'];
              $note = isset($r['notes']) ? $r['notes'] : '';
            ?>
            <tr>
              <td><div class="student-name"><?php echo h($r['name']); ?></div><span class="small">ID: <?php echo intval($r['student_id']); ?></span></td>
              <td><?php echo h($r['stage']); ?> <span class="small">الشعبة: <?php echo h($r['class']); ?></span></td>
              <td><?php echo money_iqd($total_amount); ?></td>
              <td><?php echo money_iqd($discount); ?></td>
              <td><b><?php echo money_iqd($final_amount); ?></b><?php if($note!=''){ ?><span class="small"><?php echo h($note); ?></span><?php } ?></td>
              <td><?php echo money_iqd($paid_amount); ?></td>
              <td><b style="color:<?php echo $remaining>0?'#dc2626':'#16a34a'; ?>"><?php echo money_iqd($remaining); ?></b></td>
              <td><span class="status <?php echo fee_status_class($st); ?>"><?php echo fee_status_label($st); ?></span></td>
              <td><?php echo $r['last_payment'] ? h($r['last_payment']) : '-'; ?></td>
              <td>
                <div class="actions">
                  <button class="btn primary" type="button" onclick="openFee('<?php echo intval($r['student_id']); ?>','<?php echo jsq($r['name']); ?>','<?php echo h($year); ?>','<?php echo $total_amount; ?>','<?php echo $discount; ?>','<?php echo jsq($note); ?>')">تحديد القسط</button>
                  <?php if($fee_id>0){ ?>
                    <button class="btn green" type="button" onclick="openPay('<?php echo $fee_id; ?>','<?php echo jsq($r['name']); ?>','<?php echo $remaining; ?>')">إضافة دفعة</button>
                    <form method="POST" onsubmit="return confirm('هل أنت متأكد من حذف القسط وكل دفعاته؟');">
                      <input type="hidden" name="action" value="delete_fee">
                      <input type="hidden" name="fee_id" value="<?php echo $fee_id; ?>">
                      <button class="btn red" type="submit">حذف</button>
                    </form>
                  <?php } ?>
                </div>
                <?php if($fee_id>0){ ?>
                <div class="details">
                  <details>
                    <summary>سجل الدفعات</summary>
                    <?php if(isset($payments_by_fee[$fee_id]) && count($payments_by_fee[$fee_id])>0){ ?>
                      <?php foreach($payments_by_fee[$fee_id] as $p){ ?>
                        <div class="pay-item">
                          <span><?php echo h($p['payment_date']); ?></span>
                          <b><?php echo money_iqd($p['amount']); ?></b>
                          <span><?php echo h($p['receipt_no']); ?></span>
                          <form method="POST" onsubmit="return confirm('حذف هذه الدفعة؟');">
                            <input type="hidden" name="action" value="delete_payment">
                            <input type="hidden" name="payment_id" value="<?php echo intval($p['id']); ?>">
                            <button class="btn red" type="submit" style="padding:7px 9px;font-size:12px">حذف</button>
                          </form>
                        </div>
                      <?php } ?>
                    <?php } else { ?>
                      <div class="small">لا توجد دفعات مسجلة.</div>
                    <?php } ?>
                  </details>
                </div>
                <?php } ?>
              </td>
            </tr>
            <?php } ?>
          <?php } else { ?>
            <tr><td colspan="10" style="text-align:center;padding:30px">لا توجد نتائج حسب الفلاتر المختارة.</td></tr>
          <?php } ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal" id="feeModal">
  <div class="modal-card">
    <h3>تحديد / تعديل قسط الطالب</h3>
    <p id="feeStudentName"></p>
    <form method="POST">
      <input type="hidden" name="action" value="save_fee">
      <input type="hidden" name="student_id" id="feeStudentId">
      <div class="modal-grid">
        <div class="field"><label>السنة الدراسية</label><input name="academic_year" id="feeYear" required></div>
        <div class="field"><label>القسط الكلي</label><input name="total_amount" id="feeTotal" type="number" step="1" min="0" required></div>
        <div class="field"><label>الخصم</label><input name="discount" id="feeDiscount" type="number" step="1" min="0" value="0"></div>
        <div class="field"><label>ملاحظة</label><input name="notes" id="feeNotes"></div>
      </div>
      <div class="modal-actions"><button class="btn primary" type="submit">حفظ القسط</button><button class="btn gray" type="button" onclick="closeModals()">إلغاء</button></div>
    </form>
  </div>
</div>

<div class="modal" id="payModal">
  <div class="modal-card">
    <h3>إضافة دفعة قسط</h3>
    <p id="payStudentName"></p>
    <form method="POST">
      <input type="hidden" name="action" value="add_payment">
      <input type="hidden" name="fee_id" id="payFeeId">
      <div class="modal-grid">
        <div class="field"><label>المبلغ</label><input name="amount" id="payAmount" type="number" step="1" min="1" required></div>
        <div class="field"><label>تاريخ الدفعة</label><input name="payment_date" type="date" value="<?php echo date('Y-m-d'); ?>" required></div>
        <div class="field"><label>طريقة الدفع</label><select name="payment_method"><option value="cash">نقداً</option><option value="transfer">تحويل</option><option value="card">بطاقة</option><option value="other">أخرى</option></select></div>
        <div class="field"><label>رقم الوصل</label><input name="receipt_no" placeholder="اختياري - ينشأ تلقائياً إذا فارغ"></div>
      </div>
      <div class="field" style="margin-top:10px"><label>ملاحظة</label><textarea name="note" rows="3"></textarea></div>
      <div class="modal-actions"><button class="btn green" type="submit">تسجيل الدفعة</button><button class="btn gray" type="button" onclick="closeModals()">إلغاء</button></div>
    </form>
  </div>
</div>

<script>
function openFee(studentId, name, year, total, discount, notes){
  document.getElementById('feeStudentId').value = studentId;
  document.getElementById('feeStudentName').innerHTML = 'الطالب: <b>' + name + '</b>';
  document.getElementById('feeYear').value = year;
  document.getElementById('feeTotal').value = total;
  document.getElementById('feeDiscount').value = discount;
  document.getElementById('feeNotes').value = notes;
  document.getElementById('feeModal').className = 'modal show';
}
function openPay(feeId, name, remaining){
  document.getElementById('payFeeId').value = feeId;
  document.getElementById('payStudentName').innerHTML = 'الطالب: <b>' + name + '</b> — المتبقي: <b>' + Math.round(parseFloat(remaining||0)).toLocaleString() + ' د.ع</b>';
  document.getElementById('payAmount').value = Math.round(parseFloat(remaining||0));
  document.getElementById('payModal').className = 'modal show';
}
function closeModals(){
  document.getElementById('feeModal').className = 'modal';
  document.getElementById('payModal').className = 'modal';
}
document.addEventListener('keydown', function(e){ if(e.key === 'Escape'){ closeModals(); } });
</script>
</body>
</html>
