<?php
session_start();

require_once __DIR__ . "/registration_helpers.php";

$conn = sr_connect();
sr_install($conn);
sr_sync_registered_students_to_supply($conn);

$success = "";
$error = "";

/*
    هذه الصفحة لا تعتمد على جدول students القديم.
    تعتمد فقط على جدول school_supply_students
    الذي يتم تحديثه من student_registrations.
*/

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'sync_students') {
    sr_sync_registered_students_to_supply($conn);
    $success = "تم تحديث قائمة الطلبة المسجلين من طلبات التسجيل بنجاح.";
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'add_inventory') {
    $cat = clean_input($_POST['item_category']);
    $name = clean_input($_POST['item_name']);
    $size = clean_input($_POST['size_label']);
    $qty = intval($_POST['initial_qty']);
    $notes = clean_input($_POST['notes']);

    if ($cat == "" || $name == "" || $qty < 0) {
        $error = "يرجى إدخال بيانات المخزون بصورة صحيحة.";
    } else {
        $cat_s = mysqli_real_escape_string($conn, $cat);
        $name_s = mysqli_real_escape_string($conn, $name);
        $size_s = mysqli_real_escape_string($conn, $size);
        $notes_s = mysqli_real_escape_string($conn, $notes);

        $check = mysqli_query($conn, "SELECT id, initial_qty FROM school_supply_inventory WHERE item_category='$cat_s' AND item_name='$name_s' AND size_label='$size_s' LIMIT 1");

        if ($check && mysqli_num_rows($check) > 0) {
            $r = mysqli_fetch_assoc($check);
            $new_qty = intval($r['initial_qty']) + $qty;

            mysqli_query($conn, "UPDATE school_supply_inventory SET initial_qty='$new_qty', notes='$notes_s' WHERE id='" . intval($r['id']) . "' LIMIT 1");
            $success = "تم تحديث كمية المخزون.";
        } else {
            if (mysqli_query($conn, "INSERT INTO school_supply_inventory (item_category,item_name,size_label,initial_qty,notes) VALUES ('$cat_s','$name_s','$size_s','$qty','$notes_s')")) {
                $success = "تمت إضافة عنصر المخزون بنجاح.";
            } else {
                $error = "حدث خطأ أثناء إضافة المخزون: " . mysqli_error($conn);
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'deliver') {
    $supply_student_id = intval($_POST['supply_student_id']);
    $delivered_by = clean_input($_POST['delivered_by']);
    $notes = clean_input($_POST['notes']);

    if ($supply_student_id <= 0) {
        $error = "يرجى اختيار الطالب من الطلبة المسجلين.";
    } else {
        $student_q = mysqli_query($conn, "SELECT * FROM school_supply_students WHERE id='$supply_student_id' LIMIT 1");

        if (!$student_q || mysqli_num_rows($student_q) == 0) {
            $error = "الطالب غير موجود ضمن الطلبة المسجلين.";
        } else {
            $student_row = mysqli_fetch_assoc($student_q);
            $registration_id = intval($student_row['registration_id']);

            $anything = false;

            if (isset($_POST['qty']) && is_array($_POST['qty'])) {
                foreach ($_POST['qty'] as $inv_id => $qty) {
                    $inv_id = intval($inv_id);
                    $qty = intval($qty);

                    if ($qty > 0) {
                        $iq = mysqli_query($conn, "SELECT * FROM school_supply_inventory WHERE id='$inv_id' LIMIT 1");

                        if ($iq && mysqli_num_rows($iq) > 0) {
                            $inv = mysqli_fetch_assoc($iq);

                            $delq = mysqli_query($conn, "SELECT SUM(qty) AS total FROM school_supply_distribution_reg WHERE inventory_id='$inv_id'");
                            $delivered_total = 0;

                            if ($delq && mysqli_num_rows($delq) > 0) {
                                $dr = mysqli_fetch_assoc($delq);
                                $delivered_total = intval($dr['total']);
                            }

                            $remain = intval($inv['initial_qty']) - $delivered_total;

                            if ($qty <= $remain) {
                                $cat_s = mysqli_real_escape_string($conn, $inv['item_category']);
                                $name_s = mysqli_real_escape_string($conn, $inv['item_name']);
                                $size_s = mysqli_real_escape_string($conn, $inv['size_label']);
                                $notes_s = mysqli_real_escape_string($conn, $notes);
                                $by_s = mysqli_real_escape_string($conn, $delivered_by);

                                mysqli_query($conn, "
                                    INSERT INTO school_supply_distribution_reg
                                    (supply_student_id, registration_id, inventory_id, item_category, item_name, size_label, qty, notes, delivered_by)
                                    VALUES
                                    ('$supply_student_id', '$registration_id', '$inv_id', '$cat_s', '$name_s', '$size_s', '$qty', '$notes_s', '$by_s')
                                ");

                                $anything = true;
                            } else {
                                $error = "الكمية المطلوبة من " . $inv['item_name'] . " قياس " . $inv['size_label'] . " أكبر من المتبقي.";
                            }
                        }
                    }
                }
            }

            if ($anything && $error == "") {
                $success = "تم تسجيل تسليم الزي/الكتب للطالب بنجاح.";
            } elseif (!$anything && $error == "") {
                $error = "لم يتم تحديد أي كمية للتسليم.";
            }
        }
    }
}

$student_count = 0;
$sq = mysqli_query($conn, "SELECT COUNT(*) AS c FROM school_supply_students WHERE status='active'");
if ($sq && mysqli_num_rows($sq) > 0) {
    $sr = mysqli_fetch_assoc($sq);
    $student_count = intval($sr['c']);
}

$uniform_received_count = 0;
$uq = mysqli_query($conn, "SELECT COUNT(DISTINCT supply_student_id) AS c FROM school_supply_distribution_reg WHERE item_category='uniform'");
if ($uq && mysqli_num_rows($uq) > 0) {
    $ur = mysqli_fetch_assoc($uq);
    $uniform_received_count = intval($ur['c']);
}

$book_received_count = 0;
$bq = mysqli_query($conn, "SELECT COUNT(DISTINCT supply_student_id) AS c FROM school_supply_distribution_reg WHERE item_category='book'");
if ($bq && mysqli_num_rows($bq) > 0) {
    $br = mysqli_fetch_assoc($bq);
    $book_received_count = intval($br['c']);
}

$total_initial = 0;
$total_delivered = 0;
$total_remaining = 0;

$sumq = mysqli_query($conn, "
    SELECT 
    IFNULL(SUM(i.initial_qty),0) AS initial_sum,
    IFNULL((SELECT SUM(d.qty) FROM school_supply_distribution_reg d),0) AS delivered_sum
    FROM school_supply_inventory i
");

if ($sumq && mysqli_num_rows($sumq) > 0) {
    $sumr = mysqli_fetch_assoc($sumq);
    $total_initial = intval($sumr['initial_sum']);
    $total_delivered = intval($sumr['delivered_sum']);
    $total_remaining = $total_initial - $total_delivered;
}

$inventory = mysqli_query($conn, "
    SELECT i.*,
    IFNULL((SELECT SUM(d.qty) FROM school_supply_distribution_reg d WHERE d.inventory_id=i.id),0) AS delivered_qty
    FROM school_supply_inventory i
    ORDER BY i.item_category ASC, i.item_name ASC, i.size_label ASC
");

$students = mysqli_query($conn, "
    SELECT *
    FROM school_supply_students
    WHERE status='active'
    ORDER BY stage ASC, class_name ASC, student_name ASC
");

$not_uniform = mysqli_query($conn, "
    SELECT s.*
    FROM school_supply_students s
    WHERE s.status='active'
    AND s.id NOT IN (
        SELECT DISTINCT supply_student_id FROM school_supply_distribution_reg WHERE item_category='uniform'
    )
    ORDER BY s.stage, s.class_name, s.student_name
");

$not_books = mysqli_query($conn, "
    SELECT s.*
    FROM school_supply_students s
    WHERE s.status='active'
    AND s.id NOT IN (
        SELECT DISTINCT supply_student_id FROM school_supply_distribution_reg WHERE item_category='book'
    )
    ORDER BY s.stage, s.class_name, s.student_name
");

$recent = mysqli_query($conn, "
    SELECT d.*, s.student_name, s.stage, s.class_name, s.guardian_phone
    FROM school_supply_distribution_reg d
    LEFT JOIN school_supply_students s ON s.id=d.supply_student_id
    ORDER BY d.delivered_at DESC, d.id DESC
    LIMIT 40
");
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>إدارة الزي والكتب للطلبة المسجلين</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800;900&display=swap" rel="stylesheet">

<style>
:root{
    --navy:#0b2d4d;
    --dark:#061b30;
    --gold:#d7a328;
    --line:#e2e8f0;
    --green:#166534;
    --red:#991b1b;
}
*{box-sizing:border-box}
body{
    margin:0;
    font-family:Cairo,Arial;
    background:
        radial-gradient(circle at 10% 8%,rgba(215,163,40,.22),transparent 25%),
        linear-gradient(135deg,#f8fafc,#eaf0f7,#f6f2e8);
    color:#132238;
}
.container{width:95%;max-width:1420px;margin:25px auto}
.header{
    background:linear-gradient(135deg,var(--dark),var(--navy));
    color:#fff;
    border-radius:30px;
    padding:24px;
    display:grid;
    grid-template-columns:95px 1fr auto;
    gap:18px;
    align-items:center;
    box-shadow:0 25px 70px rgba(6,27,48,.22);
}
.logo{
    background:#fff;
    border:3px solid var(--gold);
    border-radius:24px;
    padding:10px;
    width:90px;
    height:90px;
}
.logo img{width:100%;height:100%;object-fit:contain}
.header h1{margin:0;font-size:30px}
.header p{margin:6px 0 0;color:#dbeafe;line-height:1.8}
.header-actions{display:flex;gap:10px;flex-wrap:wrap}
.top-btn{
    display:inline-flex;
    text-decoration:none;
    border:none;
    cursor:pointer;
    background:#fff7df;
    color:#6e5207;
    border-radius:15px;
    padding:12px 15px;
    font-family:Cairo;
    font-weight:900;
}
.top-btn.white{background:#fff;color:#0b2d4d}
.stats{
    display:grid;
    grid-template-columns:repeat(5,1fr);
    gap:14px;
    margin:18px 0;
}
.stat{
    background:#fff;
    border-radius:22px;
    padding:18px;
    box-shadow:0 15px 35px rgba(15,23,42,.08);
}
.stat span{display:block;color:#64748b;font-weight:800;font-size:13px}
.stat b{display:block;font-size:28px;color:#0b2d4d;margin-top:4px}
.card{
    background:#fff;
    border-radius:26px;
    padding:20px;
    margin-bottom:18px;
    box-shadow:0 16px 40px rgba(15,23,42,.08);
}
.card h2{margin:0 0 14px;color:#0b2d4d}
.note{
    background:#eef2ff;
    color:#3730a3;
    border:1px solid #c7d2fe;
    border-radius:16px;
    padding:13px;
    margin-bottom:15px;
    line-height:1.8;
    font-weight:800;
}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}
.field{display:flex;flex-direction:column}
label{font-size:13px;font-weight:900;color:#334155;margin-bottom:7px}
input,select,textarea{
    width:100%;
    font-family:Cairo;
    border:1px solid #dbe3ef;
    background:#fff;
    border-radius:15px;
    padding:12px;
}
.btn{
    border:0;
    border-radius:15px;
    padding:13px 16px;
    background:linear-gradient(135deg,#0b2d4d,#123f6d);
    color:#fff;
    font-family:Cairo;
    font-weight:900;
    cursor:pointer;
}
.btn.gold{background:linear-gradient(135deg,#d7a328,#f4d06f);color:#061b30}
.alert{padding:14px;border-radius:16px;margin:15px 0;font-weight:900;text-align:center}
.success{background:#dcfce7;color:#166534}
.error{background:#fee2e2;color:#991b1b}
.table-wrap{overflow-x:auto;border-radius:18px;border:1px solid #edf2f7}
table{width:100%;min-width:980px;border-collapse:collapse;background:#fff}
th,td{text-align:center;padding:10px;border-bottom:1px solid #edf2f7}
th{background:#0b2d4d;color:#fff}
.remain{font-weight:900;color:#166534}
.danger{color:#991b1b;font-weight:900}
.qty-input{max-width:80px;text-align:center}
.two{display:grid;grid-template-columns:1fr 1fr;gap:18px}
.list-box{max-height:420px;overflow:auto;border:1px solid #edf2f7;border-radius:18px}
.student-row{padding:11px;border-bottom:1px solid #edf2f7}
.student-row b{color:#0b2d4d}
.student-row span{color:#64748b;font-size:13px}
.badge{
    display:inline-flex;
    padding:5px 10px;
    border-radius:999px;
    background:#fff7df;
    color:#6e5207;
    font-weight:900;
    font-size:12px;
}
@media(max-width:1100px){
    .stats{grid-template-columns:repeat(2,1fr)}
    .grid,.two{grid-template-columns:1fr}
    .header{grid-template-columns:1fr;text-align:center}
    .logo{margin:auto}
    .header-actions{justify-content:center}
}
</style>
</head>
<body>

<div class="container">

<div class="header">
    <div class="logo">
        <img src="/sy/school_system/logo.png" alt="شعار المدرسة">
    </div>

    <div>
        <h1>إدارة استلام الزي المدرسي والكتب</h1>
        <p>
            هذه الصفحة تعتمد فقط على الطلبة المسجلين من صفحة التسجيل.
            لا تستخدم جدول الطلبة القديم ولا تؤثر على قاعدة بيانات الدرجات السابقة.
        </p>
    </div>

    <div class="header-actions">
        <a class="top-btn" href="admin_registrations.php">طلبات التسجيل</a>

        <form method="POST" style="display:inline;">
            <input type="hidden" name="action" value="sync_students">
            <button class="top-btn white" type="submit">تحديث الطلبة المسجلين</button>
        </form>
    </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 $student_count; ?></b>
    </div>

    <div class="stat">
        <span>إجمالي المخزون</span>
        <b><?php echo $total_initial; ?></b>
    </div>

    <div class="stat">
        <span>المسلّم</span>
        <b><?php echo $total_delivered; ?></b>
    </div>

    <div class="stat">
        <span>لم يستلموا الزي</span>
        <b><?php echo max(0,$student_count-$uniform_received_count); ?></b>
    </div>

    <div class="stat">
        <span>لم يستلموا الكتب</span>
        <b><?php echo max(0,$student_count-$book_received_count); ?></b>
    </div>
</div>

<div class="card">
    <h2>ملاحظة مهمة</h2>
    <div class="note">
        أسماء الطلاب هنا مأخوذة من جدول التسجيل الجديد <b>student_registrations</b> وتم نسخها إلى جدول مستقل اسمه
        <b>school_supply_students</b>.
        لذلك لا يوجد أي اعتماد على جدول <b>students</b> القديم.
    </div>
</div>

<div class="card">
    <h2>إضافة مخزون زي أو كتاب</h2>

    <form method="POST">
        <input type="hidden" name="action" value="add_inventory">

        <div class="grid">
            <div class="field">
                <label>النوع</label>
                <select name="item_category">
                    <option value="uniform">زي</option>
                    <option value="book">كتاب</option>
                </select>
            </div>

            <div class="field">
                <label>اسم المادة</label>
                <input type="text" name="item_name" required placeholder="مثال: تيشيرت / كتاب رياضيات">
            </div>

            <div class="field">
                <label>القياس / المرحلة</label>
                <input type="text" name="size_label" placeholder="مثال: 6 / M / الأول المتوسط">
            </div>

            <div class="field">
                <label>الكمية</label>
                <input type="number" name="initial_qty" min="0" required>
            </div>

            <div class="field" style="grid-column:1/-1">
                <label>ملاحظات</label>
                <input type="text" name="notes">
            </div>
        </div>

        <br>
        <button class="btn" type="submit">إضافة للمخزون</button>
    </form>
</div>

<div class="card">
    <h2>تسليم زي / كتب لطالب مسجل</h2>

    <form method="POST">
        <input type="hidden" name="action" value="deliver">

        <div class="grid">
            <div class="field" style="grid-column:1/3">
                <label>اختر الطالب من الطلبة المسجلين فقط</label>
                <select name="supply_student_id" required>
                    <option value="">اختر الطالب</option>

                    <?php if($students){ while($s=mysqli_fetch_assoc($students)){ ?>
                        <option value="<?php echo intval($s['id']); ?>">
                            <?php
                            echo h($s['student_name']);
                            echo " - ";
                            echo h($s['stage']);
                            if($s['class_name']!=""){
                                echo " - " . h($s['class_name']);
                            }
                            if($s['registration_no']!=""){
                                echo " - " . h($s['registration_no']);
                            }
                            ?>
                        </option>
                    <?php }} ?>
                </select>
            </div>

            <div class="field">
                <label>المسلّم بواسطة</label>
                <input type="text" name="delivered_by" placeholder="اسم الموظف">
            </div>

            <div class="field">
                <label>ملاحظات</label>
                <input type="text" name="notes">
            </div>
        </div>

        <br>

        <div class="table-wrap">
            <table>
                <tr>
                    <th>النوع</th>
                    <th>الاسم</th>
                    <th>القياس</th>
                    <th>المخزون</th>
                    <th>المسلّم</th>
                    <th>المتبقي</th>
                    <th>كمية التسليم</th>
                </tr>

                <?php
                $delivery_inventory = mysqli_query($conn, "
                    SELECT i.*,
                    IFNULL((SELECT SUM(d.qty) FROM school_supply_distribution_reg d WHERE d.inventory_id=i.id),0) AS delivered_qty
                    FROM school_supply_inventory i
                    ORDER BY i.item_category ASC, i.item_name ASC, i.size_label ASC
                ");

                if($delivery_inventory){
                    while($di=mysqli_fetch_assoc($delivery_inventory)){
                        $remain = intval($di['initial_qty']) - intval($di['delivered_qty']);
                ?>
                    <tr>
                        <td><?php echo $di['item_category']=='book' ? 'كتاب' : 'زي'; ?></td>
                        <td><?php echo h($di['item_name']); ?></td>
                        <td><?php echo h($di['size_label']); ?></td>
                        <td><?php echo intval($di['initial_qty']); ?></td>
                        <td><?php echo intval($di['delivered_qty']); ?></td>
                        <td class="<?php echo $remain<=0 ? 'danger' : 'remain'; ?>"><?php echo $remain; ?></td>
                        <td>
                            <input class="qty-input" type="number" min="0" max="<?php echo max(0,$remain); ?>" name="qty[<?php echo intval($di['id']); ?>]" value="0">
                        </td>
                    </tr>
                <?php }} ?>
            </table>
        </div>

        <br>
        <button class="btn gold" type="submit">تسجيل التسليم للطالب</button>
    </form>
</div>

<div class="card">
    <h2>إحصائيات المخزون والمتبقي</h2>

    <div class="table-wrap">
        <table>
            <tr>
                <th>النوع</th>
                <th>الاسم</th>
                <th>القياس</th>
                <th>المخزون الابتدائي</th>
                <th>المسلّم</th>
                <th>المتبقي</th>
                <th>ملاحظات</th>
            </tr>

            <?php if($inventory){ while($i=mysqli_fetch_assoc($inventory)){ $remain=intval($i['initial_qty'])-intval($i['delivered_qty']); ?>
                <tr>
                    <td><?php echo $i['item_category']=='book' ? 'كتاب' : 'زي'; ?></td>
                    <td><?php echo h($i['item_name']); ?></td>
                    <td><?php echo h($i['size_label']); ?></td>
                    <td><?php echo intval($i['initial_qty']); ?></td>
                    <td><?php echo intval($i['delivered_qty']); ?></td>
                    <td class="<?php echo $remain<=0 ? 'danger' : 'remain'; ?>"><?php echo $remain; ?></td>
                    <td><?php echo h($i['notes']); ?></td>
                </tr>
            <?php }} ?>
        </table>
    </div>
</div>

<div class="two">

    <div class="card">
        <h2>طلبة مسجلون لم يستلموا الزي</h2>

        <div class="list-box">
            <?php if($not_uniform && mysqli_num_rows($not_uniform)>0){ ?>
                <?php while($n=mysqli_fetch_assoc($not_uniform)){ ?>
                    <div class="student-row">
                        <b><?php echo h($n['student_name']); ?></b>
                        <br>
                        <span>
                            <?php echo h($n['stage']); ?>
                            <?php if($n['class_name']!=""){ echo " - " . h($n['class_name']); } ?>
                            <?php if($n['guardian_phone']!=""){ echo " - هاتف: " . h($n['guardian_phone']); } ?>
                        </span>
                    </div>
                <?php } ?>
            <?php } else { ?>
                <div class="student-row">كل الطلبة المسجلين لديهم تسليم زي مسجل.</div>
            <?php } ?>
        </div>
    </div>

    <div class="card">
        <h2>طلبة مسجلون لم يستلموا الكتب</h2>

        <div class="list-box">
            <?php if($not_books && mysqli_num_rows($not_books)>0){ ?>
                <?php while($n=mysqli_fetch_assoc($not_books)){ ?>
                    <div class="student-row">
                        <b><?php echo h($n['student_name']); ?></b>
                        <br>
                        <span>
                            <?php echo h($n['stage']); ?>
                            <?php if($n['class_name']!=""){ echo " - " . h($n['class_name']); } ?>
                            <?php if($n['guardian_phone']!=""){ echo " - هاتف: " . h($n['guardian_phone']); } ?>
                        </span>
                    </div>
                <?php } ?>
            <?php } else { ?>
                <div class="student-row">كل الطلبة المسجلين لديهم تسليم كتب مسجل.</div>
            <?php } ?>
        </div>
    </div>

</div>

<div class="card">
    <h2>آخر عمليات التسليم</h2>

    <div class="list-box">
        <?php if($recent && mysqli_num_rows($recent)>0){ ?>
            <?php while($r=mysqli_fetch_assoc($recent)){ ?>
                <div class="student-row">
                    <b><?php echo h($r['student_name']); ?></b>
                    <span class="badge"><?php echo $r['item_category']=='book' ? 'كتاب' : 'زي'; ?></span>
                    <br>
                    <span>
                        <?php echo h($r['item_name']); ?>
                        /
                        <?php echo h($r['size_label']); ?>
                        /
                        الكمية:
                        <?php echo intval($r['qty']); ?>
                        /
                        <?php echo h($r['delivered_at']); ?>
                    </span>
                </div>
            <?php } ?>
        <?php } else { ?>
            <div class="student-row">لا توجد عمليات تسليم بعد.</div>
        <?php } ?>
    </div>
</div>

</div>

</body>
</html>
