<?php
require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/csrf.php';
require_once __DIR__ . '/../app/docno.php';
require_once __DIR__ . '/../app/upload.php';

$me  = require_role(['ADMIN','WAREHOUSE']);
$pdo = db();

$csrf   = csrf_token();
$action = $_GET['action'] ?? 'list';
$errors = [];

$METHOD_AR = [
    'CASH'     => 'نقداً',
    'TRANSFER' => 'تحويل بنكي',
    'OTHER'    => 'أخرى',
];

/* ══════════════════════════════════════════
   دوال مساعدة
══════════════════════════════════════════ */
function fetch_outlets_pay(PDO $pdo): array {
    return $pdo->query("SELECT id, name FROM outlets WHERE active=1 ORDER BY name")->fetchAll();
}

function fetch_open_invoices(PDO $pdo, int $outletId): array {
    $st = $pdo->prepare("
        SELECT id, invoice_no, issued_at, total_amount, total_paid, balance_due
        FROM invoices
        WHERE outlet_id = ? AND status IN ('ISSUED','PARTIAL') AND balance_due > 0
        ORDER BY issued_at ASC
    ");
    $st->execute([$outletId]);
    return $st->fetchAll();
}

function recompute_invoice_totals(PDO $pdo, int $invoiceId): void {
    $st = $pdo->prepare("
        SELECT
            COALESCE((SELECT SUM(amount_allocated) FROM payment_allocations WHERE invoice_id=?),0) AS paid,
            (SELECT total_amount FROM invoices WHERE id=?) AS total
    ");
    $st->execute([$invoiceId, $invoiceId]);
    $row    = $st->fetch();
    $paid   = round((float)$row['paid'], 3);
    $bal    = round(max(0.0, (float)$row['total'] - $paid), 3);
    $status = $bal <= 0 ? 'PAID' : ($paid > 0 ? 'PARTIAL' : 'ISSUED');
    $pdo->prepare("UPDATE invoices SET total_paid=?, balance_due=?, status=? WHERE id=?")
        ->execute([$paid, $bal, $status, $invoiceId]);
}

/* ══════════════════════════════════════════
   معالجة POST
══════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $op = $_POST['op'] ?? '';

    if ($op === 'create_payment') {
        $outlet_id   = (int)($_POST['outlet_id']  ?? 0);
        $amount      = (float)($_POST['amount']   ?? 0);
        $method      = $_POST['method']            ?? 'CASH';
        $paid_at     = trim($_POST['paid_at']      ?? '');
        $notes       = trim($_POST['notes']        ?? '');
        $invoice_ids = $_POST['invoice_id']        ?? [];
        $allocs      = $_POST['alloc_amount']      ?? [];

        if ($outlet_id <= 0 || $amount <= 0 || $paid_at === '') {
            $errors[] = 'يرجى تعبئة جميع الحقول المطلوبة.';
        } elseif (!in_array($method, ['CASH','TRANSFER','OTHER'], true)) {
            $errors[] = 'طريقة دفع غير صحيحة.';
        } else {
            $attId = null;
            if (!empty($_FILES['receipt']) && $_FILES['receipt']['error'] === UPLOAD_ERR_OK) {
                $attId = save_upload($_FILES['receipt'], (int)$me['id']);
            }

            $pdo->beginTransaction();
            try {
                $payNo = next_doc_no('PAY', new DateTimeImmutable($paid_at));
                $pdo->prepare("
                    INSERT INTO payments
                        (payment_no, outlet_id, amount, method, paid_at,
                         receipt_attachment_id, notes, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ")->execute([$payNo, $outlet_id, $amount, $method, $paid_at,
                              $attId, $notes ?: null, (int)$me['id']]);
                $paymentId = (int)$pdo->lastInsertId();

                $sumAlloc = 0.0;
                $touched  = [];
                for ($i = 0; $i < count($invoice_ids); $i++) {
                    $invId = (int)$invoice_ids[$i];
                    $alloc = isset($allocs[$i]) ? (float)$allocs[$i] : 0.0;
                    if ($invId <= 0 || $alloc <= 0) continue;
                    $sumAlloc      += $alloc;
                    $touched[$invId] = true;
                    $pdo->prepare("
                        INSERT INTO payment_allocations
                            (payment_id, invoice_id, amount_allocated)
                        VALUES (?, ?, ?)
                        ON DUPLICATE KEY UPDATE amount_allocated = VALUES(amount_allocated)
                    ")->execute([$paymentId, $invId, $alloc]);
                }

                if (round($sumAlloc, 3) > round($amount, 3)) {
                    throw new RuntimeException('المبلغ الموزع على الفواتير يتجاوز قيمة الدفعة.');
                }

                foreach (array_keys($touched) as $invId) {
                    recompute_invoice_totals($pdo, (int)$invId);
                }

                $pdo->commit();

                if (!empty($invoice_ids)) {
                    redirect('invoices.php?action=view&id=' . (int)$invoice_ids[0]);
                }
                redirect('payments.php');

            } catch (Throwable $e) {
                $pdo->rollBack();
                $errors[] = 'خطأ أثناء الحفظ: ' . $e->getMessage();
            }
        }
    }
}

/* ══════════════════════════════════════════
   تحضير البيانات
══════════════════════════════════════════ */
if ($action === 'new') {
    $outlet_id  = (int)($_GET['outlet_id']  ?? 0);
    $prefInvId  = (int)($_GET['invoice_id'] ?? 0);
    $outlets    = fetch_outlets_pay($pdo);
    $invoices   = $outlet_id > 0 ? fetch_open_invoices($pdo, $outlet_id) : [];
    $rows       = [];
} else {
    $outlet_id  = 0;
    $prefInvId  = 0;
    $outlets    = [];
    $invoices   = [];
    $rows       = $pdo->query("
        SELECT p.id, p.payment_no, p.paid_at, p.method, p.amount,
               o.name AS outlet_name,
               u.name AS created_by_name,
               COUNT(pa.id) AS alloc_count
        FROM payments p
        JOIN outlets o ON o.id = p.outlet_id
        JOIN users   u ON u.id = p.created_by
        LEFT JOIN payment_allocations pa ON pa.payment_id = p.id
        GROUP BY p.id
        ORDER BY p.id DESC LIMIT 200
    ")->fetchAll();
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>التحصيلات (PAY) — MGZ</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Tajawal', sans-serif;
    background: #f4f7f6;
    color: #333;
    direction: rtl;
    padding: 20px;
    font-size: 14px;
}
a { color: #1a73e8; text-decoration: none; }
a:hover { text-decoration: underline; }
.back-link { margin-bottom: 14px; display: inline-block; font-size: .9rem; }
.page-header {
    background: linear-gradient(135deg, #34a853, #0d652d);
    color: #fff;
    padding: 18px 24px;
    border-radius: 10px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}
.page-header h2 { font-size: 1.3rem; font-weight: 700; margin-bottom: 2px; }
.page-header small { opacity: .85; font-size: .85rem; }
.card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    margin-bottom: 20px;
    overflow: hidden;
}
.card-header {
    padding: 14px 20px;
    border-bottom: 1px solid #eee;
    font-weight: 700;
    font-size: .95rem;
    background: #fafafa;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.card-body { padding: 20px; }
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px,1fr));
    gap: 14px;
    margin-bottom: 20px;
}
.stat-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    text-align: center;
    padding: 16px 10px;
}
.stat-card .num { font-size: 1.5rem; font-weight: 700; }
.stat-card .lbl { color: #888; font-size: .82rem; margin-top: 3px; }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px 14px; border-bottom: 1px solid #eee; text-align: right; white-space: nowrap; }
th { background: #f8f9fa; font-weight: 600; color: #555; font-size: .85rem; }
tr:last-child td { border-bottom: none; }
tbody tr:hover td { background: #fafbff; }
.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px,1fr));
    gap: 14px;
    align-items: end;
    margin-bottom: 20px;
}
.form-group label {
    display: block;
    font-weight: 600;
    color: #555;
    margin-bottom: 5px;
    font-size: .85rem;
}
input[type=text], input[type=number], input[type=datetime-local],
input[type=file], select, textarea {
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: .9rem;
    font-family: inherit;
    background: #fff;
    transition: border-color .2s;
}
input:focus, select:focus {
    outline: none;
    border-color: #34a853;
    box-shadow: 0 0 0 3px rgba(52,168,83,.1);
}
.btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 7px 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: .88rem;
    font-family: inherit;
    font-weight: 600;
    text-decoration: none;
    transition: opacity .15s;
    white-space: nowrap;
}
.btn:hover { opacity: .88; }
.btn-primary { background: #1a73e8; color: #fff; }
.btn-success { background: #34a853; color: #fff; }
.btn-outline { background: transparent; border: 1px solid #ccc; color: #555; }
.btn-sm      { padding: 4px 10px; font-size: .8rem; }
.alert {
    padding: 12px 16px;
    border-radius: 7px;
    margin-bottom: 16px;
    font-size: .9rem;
}
.alert-danger  { background: #fce8e6; color: #c62828; border-right: 4px solid #ea4335; }
.alert-info    { background: #e3f2fd; color: #0d47a1; border-right: 4px solid #1a73e8; }
.alert-warning { background: #fff8e1; color: #e65100; border-right: 4px solid #fbbc04; }
.money       { font-weight: 700; color: #1a73e8; }
.money-green { font-weight: 700; color: #34a853; }
.money-red   { font-weight: 700; color: #ea4335; }
.empty-state { text-align: center; padding: 50px 20px; color: #aaa; }
.empty-state .icon { font-size: 3rem; margin-bottom: 10px; }
.total-row td { font-weight: 700; background: #f0fff4; }
.alloc-row td { background: #fafff6; }
.alloc-row input[type=checkbox] { width: 18px; height: 18px; cursor: pointer; }
@media (max-width: 768px) {
    body { padding: 12px; }
    .page-header { flex-direction: column; align-items: flex-start; }
    .form-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: repeat(2,1fr); }
    th, td { padding: 8px; font-size: .82rem; }
}
</style>
</head>
<body>

<a href="../dashboard.php" class="back-link">&#8594; العودة للرئيسية</a>

<?
<?php foreach ($errors as $e): ?>
    <div class="alert alert-danger">&#9888; <?= h($e) ?></div>
<?php endforeach; ?>

<?php if ($action === 'new'): ?>

<!-- ══════════════════════════════════════════
     صفحة تحصيل جديد
══════════════════════════════════════════ -->
<div class="page-header">
    <div>
        <h2>&#128178; تحصيل جديد</h2>
        <small>تسجيل دفعة جديدة وتوزيعها على الفواتير</small>
    </div>
    <a href="payments.php" class="btn btn-outline" style="background:rgba(255,255,255,.2);color:#fff;border-color:rgba(255,255,255,.4);">
        &#8594; قائمة التحصيلات
    </a>
</div>

<!-- اختيار المنفذ -->
<div class="card">
    <div class="card-header">&#127978; اختيار المنفذ</div>
    <div class="card-body">
        <form method="get">
            <input type="hidden" name="action" value="new">
            <div class="form-grid" style="grid-template-columns:1fr auto;">
                <div class="form-group">
                    <label>المنفذ *</label>
                    <select name="outlet_id" required>
                        <option value="0">— اختر المنفذ —</option>
                        <?php foreach ($outlets as $o): ?>
                        <option value="<?= (int)$o['id'] ?>"
                            <?= $outlet_id === (int)$o['id'] ? 'selected' : '' ?>>
                            <?= h($o['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>&nbsp;</label>
                    <button type="submit" class="btn btn-primary" style="width:100%;">
                        &#128269; تحميل الفواتير
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<?php if ($outlet_id > 0): ?>

<!-- بيانات الدفعة -->
<div class="card">
    <div class="card-header">&#128178; بيانات الدفعة</div>
    <div class="card-body">
        <form method="post" enctype="multipart/form-data" id="payForm">
            <input type="hidden" name="csrf"      value="<?= h($csrf) ?>">
            <input type="hidden" name="op"        value="create_payment">
            <input type="hidden" name="outlet_id" value="<?= (int)$outlet_id ?>">

            <!-- حقول الدفعة الرئيسية -->
            <div class="form-grid">
                <div class="form-group">
                    <label>تاريخ ووقت التحصيل *</label>
                    <input type="datetime-local" name="paid_at"
                           value="<?= date('Y-m-d\TH:i') ?>" required>
                </div>
                <div class="form-group">
                    <label>طريقة الدفع *</label>
                    <select name="method">
                        <option value="CASH">نقداً</option>
                        <option value="TRANSFER">تحويل بنكي</option>
                        <option value="OTHER">أخرى</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>المبلغ الإجمالي (ر.ع.) *</label>
                    <input type="number" name="amount" id="totalAmount"
                           step="0.001" min="0.001" required
                           placeholder="0.000"
                           oninput="updateRemaining()">
                </div>
                <div class="form-group">
                    <label>إيصال الدفع (اختياري)</label>
                    <input type="file" name="receipt" accept=".jpg,.jpeg,.png,.pdf">
                </div>
                <div class="form-group">
                    <label>ملاحظات</label>
                    <input type="text" name="notes" placeholder="اختياري...">
                </div>
            </div>

            <!-- توزيع على الفواتير -->
            <div style="margin-top:10px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                    <strong>&#128200; توزيع الدفعة على الفواتير</strong>
                    <span id="remainingBadge"
                          style="background:#e3f2fd;color:#0d47a1;padding:4px 14px;border-radius:20px;font-size:.85rem;font-weight:700;">
                        المتبقي للتوزيع: — ر.ع.
                    </span>
                </div>

                <?php if (empty($invoices)): ?>
                <div class="alert alert-warning">
                    &#9888; لا توجد فواتير مفتوحة لهذا المنفذ.
                </div>
                <?php else: ?>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th style="width:40px;">&#10003;</th>
                                <th>رقم الفاتورة</th>
                                <th>التاريخ</th>
                                <th>إجمالي الفاتورة</th>
                                <th>المدفوع سابقاً</th>
                                <th>المتبقي</th>
                                <th>المبلغ المخصص (ر.ع.)</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($invoices as $idx => $inv):
                            $checked = ($prefInvId > 0 && $prefInvId === (int)$inv['id']);
                        ?>
                        <tr class="alloc-row">
                            <td style="text-align:center;">
                                <input type="checkbox"
                                       id="chk<?= (int)$inv['id'] ?>"
                                       data-balance="<?= (float)$inv['balance_due'] ?>"
                                       onchange="toggleAlloc(this, 'alloc<?= (int)$inv['id'] ?>')"
                                       <?= $checked ? 'checked' : '' ?>>
                            </td>
                            <td><strong><?= h($inv['invoice_no']) ?></strong></td>
                            <td><?= h($inv['issued_at']) ?></td>
                            <td><?= omr((float)$inv['total_amount']) ?></td>
                            <td class="money-green"><?= omr((float)$inv['total_paid']) ?></td>
                            <td class="money-red"><?= omr((float)$inv['balance_due']) ?></td>
                            <td>
                                <input type="hidden" name="invoice_id[]" value="<?= (int)$inv['id'] ?>">
                                <input type="number"
                                       id="alloc<?= (int)$inv['id'] ?>"
                                       name="alloc_amount[]"
                                       step="0.001" min="0"
                                       style="width:130px;"
                                       placeholder="0.000"
                                       <?= $checked ? 'value="' . h($inv['balance_due']) . '"' : 'disabled value=""' ?>
                                       oninput="updateRemaining()">
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="total-row">
                                <td colspan="6" style="text-align:left;">إجمالي الموزع</td>
                                <td>
                                    <span id="totalAllocated" class="money">0.000</span> ر.ع.
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                <?php endif; ?>
            </div>

            <div style="margin-top:20px;display:flex;gap:10px;align-items:center;">
                <button type="submit" class="btn btn-success"
                        onclick="return confirmSave()">
                    &#10003; حفظ التحصيل
                </button>
                <a href="payments.php" class="btn btn-outline">إلغاء</a>
            </div>

        </form>
    </div>
</div>

<?php endif; ?>

<?php else: ?>

<!-- ══════════════════════════════════════════
     صفحة القائمة
══════════════════════════════════════════ -->
<div class="page-header">
    <div>
        <h2>&#128178; التحصيلات (PAY)</h2>
        <small>قائمة جميع التحصيلات المسجلة</small>
    </div>
    <a href="payments.php?action=new" class="btn btn-outline"
       style="background:rgba(255,255,255,.2);color:#fff;border-color:rgba(255,255,255,.4);">
        &#43; تحصيل جديد
    </a>
</div>

<!-- إحصائيات -->
<?php
$stats = $pdo->query("
    SELECT
        COUNT(*)          AS total,
        SUM(amount)       AS sum_amount,
        SUM(method='CASH')     AS cash_count,
        SUM(method='TRANSFER') AS transfer_count
    FROM payments
")->fetch();
?>
<div class="stats-grid">
    <div class="stat-card">
        <div class="num" style="color:#555;"><?= (int)$stats['total'] ?></div>
        <div class="lbl">إجمالي التحصيلات</div>
    </div>
    <div class="stat-card">
        <div class="num" style="color:#34a853;font-size:1.2rem;">
            <?= omr((float)$stats['sum_amount']) ?>
        </div>
        <div class="lbl">إجمالي المحصّل (ر.ع.)</div>
    </div>
    <div class="stat-card">
        <div class="num" style="color:#1a73e8;"><?= (int)$stats['cash_count'] ?></div>
        <div class="lbl">نقداً</div>
    </div>
    <div class="stat-card">
        <div class="num" style="color:#6f42c1;"><?= (int)$stats['transfer_count'] ?></div>
        <div class="lbl">تحويل بنكي</div>
    </div>
</div>

<!-- جدول التحصيلات -->
<div class="card">
    <div class="card-header">
        قائمة التحصيلات
        <span style="font-weight:400;font-size:.85rem;color:#888;"><?= count($rows) ?> تحصيل</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>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($rows)): ?>
                <tr><td colspan="8">
                    <div class="empty-state">
                        <div class="icon">&#128178;</div>
                        <div>لا توجد تحصيلات مسجلة بعد</div>
                    </div>
                </td></tr>
            <?php else: ?>
                <?php foreach ($rows as $idx => $r): ?>
                <tr>
                    <td><?= $idx + 1 ?></td>
                    <td><strong><?= h($r['payment_no']) ?></strong></td>
                    <td><?= h($r['paid_at']) ?></td>
                    <td><?= h($r['outlet_name']) ?></td>
                    <td>
                        <?php
                        $methodIcons = ['CASH'=>'&#128181;','TRANSFER'=>'&#127974;','OTHER'=>'&#128260;'];
                        echo ($methodIcons[$r['method']] ?? '') . ' ' . ($METHOD_AR[$r['method']] ?? h($r['method']));
                        ?>
                    </td>
                    <td class="money-green"><?= omr((float)$r['amount']) ?></td>
                    <td style="text-align:center;">
                        <span style="background:#e8f0fe;color:#1a73e8;padding:2px 10px;border-radius:12px;font-size:.82rem;font-weight:700;">
                            <?= (int)$r['alloc_count'] ?> فاتورة
                        </span>
                    </td>
                    <td><?= h($r['created_by_name']) ?></td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php endif; ?>

<script>
/* ── حساب المتبقي للتوزيع ── */
function updateRemaining() {
    var total    = parseFloat(document.getElementById('totalAmount')?.value) || 0;
    var inputs   = document.querySelectorAll('[name="alloc_amount[]"]:not([disabled])');
    var allocated = 0;
    inputs.forEach(function(inp) {
        allocated += parseFloat(inp.value) || 0;
    });
    allocated = Math.round(allocated * 1000) / 1000;
    var remaining = Math.round((total - allocated) * 1000) / 1000;

    var badge = document.getElementById('remainingBadge');
    var totEl = document.getElementById('totalAllocated');

    if (totEl) totEl.textContent = allocated.toFixed(3);
    if (badge) {
        badge.textContent = 'المتبقي للتوزيع: ' + remaining.toFixed(3) + ' ر.ع.';
        badge.style.background = remaining < 0 ? '#fce8e6' : '#e3f2fd';
        badge.style.color      
        badge.style.color = remaining < 0 ? '#c62828' : '#0d47a1';
    }
}

/* ── تفعيل / تعطيل حقل التخصيص ── */
function toggleAlloc(checkbox, inputId) {
    var input = document.getElementById(inputId);
    if (!input) return;
    input.disabled = !checkbox.checked;
    if (!checkbox.checked) {
        input.value = '';
    } else {
        input.value = checkbox.dataset.balance || '';
    }
    updateRemaining();
}

/* ── تأكيد الحفظ ── */
function confirmSave() {
    var total = parseFloat(document.getElementById('totalAmount')?.value) || 0;
    if (total <= 0) {
        alert('يرجى إدخال المبلغ الإجمالي للتحصيل.');
        return false;
    }
    var inputs    = document.querySelectorAll('[name="alloc_amount[]"]:not([disabled])');
    var allocated = 0;
    inputs.forEach(function(inp) { allocated += parseFloat(inp.value) || 0; });
    allocated = Math.round(allocated * 1000) / 1000;

    if (allocated > Math.round(total * 1000) / 1000) {
        alert('المبلغ الموزع (' + allocated.toFixed(3) + ' ر.ع.) يتجاوز إجمالي الدفعة (' + total.toFixed(3) + ' ر.ع.).');
        return false;
    }
    if (allocated === 0) {
        return confirm('لم يتم تخصيص أي مبلغ على الفواتير. هل تريد المتابعة؟');
    }
    return confirm('حفظ التحصيل بمبلغ ' + total.toFixed(3) + ' ر.ع.؟');
}

/* ── تحديث عند تحميل الصفحة ── */
document.addEventListener('DOMContentLoaded', function() {
    updateRemaining();
});
</script>

</body>
</html>
