<?php
require_once '../includes/auth.php';
require_once __DIR__ . '/stock_helpers.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

if (!function_exists('e')) {
    function e($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}

$successMessage = $_SESSION['stock_success'] ?? '';
$errorMessages = [];
if (!empty($_SESSION['stock_error'])) {
    $errorMessages[] = (string)$_SESSION['stock_error'];
}
unset($_SESSION['stock_success'], $_SESSION['stock_error']);

$q = trim((string)($_GET['q'] ?? ''));
$reasonLabels = nay_stock_reason_labels();
$defaultThreshold = nay_stock_default_threshold($conn);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $reasonCode = trim((string)($_POST['reason_code'] ?? 'manual_adjustment')) ?: 'manual_adjustment';
    $notes = trim((string)($_POST['notes'] ?? ''));
    try {
        $conn->begin_transaction();
        foreach ((array)($_POST['product_stock'] ?? []) as $productId => $stockQty) {
            $productId = (int)$productId;
            if ($productId <= 0) continue;
            $row = nay_stock_fetch_target($conn, 'product', $productId);
            if (!$row || ($row['managed_by'] ?? '') === 'variants') continue;
            nay_stock_apply_change($conn, 'product', $productId, 'set', max(0, (int)$stockQty), [
                'admin_id' => current_admin_id(),
                'source' => 'admin_bulk_form',
                'reason_code' => $reasonCode,
                'notes' => $notes,
            ]);
            nay_stock_update_meta($conn, 'product', $productId, [
                'low_stock_alert' => max(0, (int)(($_POST['product_alert'][$productId] ?? 0))),
                'status' => isset($_POST['product_status'][$productId]) ? (int)$_POST['product_status'][$productId] : 1,
            ]);
        }
        foreach ((array)($_POST['variant_stock'] ?? []) as $variantId => $stockQty) {
            $variantId = (int)$variantId;
            if ($variantId <= 0) continue;
            nay_stock_apply_change($conn, 'variant', $variantId, 'set', max(0, (int)$stockQty), [
                'admin_id' => current_admin_id(),
                'source' => 'admin_bulk_form',
                'reason_code' => $reasonCode,
                'notes' => $notes,
            ]);
            nay_stock_update_meta($conn, 'variant', $variantId, [
                'low_stock_alert' => max(0, (int)(($_POST['variant_alert'][$variantId] ?? 0))),
                'status' => isset($_POST['variant_status'][$variantId]) ? (int)$_POST['variant_status'][$variantId] : 1,
            ]);
        }
        $conn->commit();
        $successMessage = 'تم حفظ تعديلات المخزون وسجل الحركات بنجاح.';
    } catch (Throwable $e) {
        $conn->rollback();
        $errorMessages[] = 'فشل حفظ المخزون: ' . $e->getMessage();
    }
}

$where = 'WHERE 1=1';
$params = [];
$types = '';
if ($q !== '') {
    $where .= ' AND (p.name LIKE ? OR p.brand_part LIKE ? OR p.product_part LIKE ? OR EXISTS (SELECT 1 FROM product_variants pv2 WHERE pv2.product_id = p.id AND pv2.variant_name LIKE ?))';
    $like = '%' . $q . '%';
    $params = [$like, $like, $like, $like];
    $types = 'ssss';
}

$sql = "SELECT p.id, p.name, p.brand_part, p.product_part, p.main_image, p.has_variants, p.stock_qty, p.low_stock_alert, p.status,
               (SELECT COALESCE(SUM(pv.stock_qty),0) FROM product_variants pv WHERE pv.product_id = p.id AND pv.status = 1) AS variants_stock_total,
               (SELECT COUNT(*) FROM product_variants pv WHERE pv.product_id = p.id AND pv.status = 1) AS variants_count
        FROM products p
        {$where}
        ORDER BY p.id DESC";
$stmt = $conn->prepare($sql);
if ($params) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$res = $stmt->get_result();
$products = [];
while ($row = $res->fetch_assoc()) {
    $row['managed_by'] = (int)$row['has_variants'] === 1 ? 'variants' : 'product';
    $row['effective_threshold'] = nay_stock_effective_threshold($conn, $row['low_stock_alert'] ?? 0);
    $visibleQty = $row['managed_by'] === 'variants' ? (int)$row['variants_stock_total'] : (int)$row['stock_qty'];
    $row['visible_stock_qty'] = $visibleQty;
    $row['state'] = nay_stock_state($conn, $visibleQty, (int)$row['effective_threshold']);
    $row['variants'] = [];
    if ((int)$row['has_variants'] === 1) {
        $vStmt = $conn->prepare('SELECT id, variant_name, stock_qty, low_stock_alert, status, variant_image FROM product_variants WHERE product_id = ? AND status IN (0,1) ORDER BY sort_order ASC, id ASC');
        $vStmt->bind_param('i', $row['id']);
        $vStmt->execute();
        $vRes = $vStmt->get_result();
        while ($variant = $vRes->fetch_assoc()) {
            $variant['effective_threshold'] = nay_stock_effective_threshold($conn, $variant['low_stock_alert'] ?? 0);
            $variant['state'] = nay_stock_state($conn, (int)$variant['stock_qty'], (int)$variant['effective_threshold']);
            $row['variants'][] = $variant;
        }
        $vStmt->close();
    }
    $products[] = $row;
}
$stmt->close();

$stats = [
    'simple_products' => 0,
    'variants' => 0,
    'low_stock' => 0,
    'zero_stock' => 0,
    'movements_today' => 0,
];
$res = $conn->query("SELECT COUNT(*) c FROM products WHERE has_variants = 0"); if ($res) $stats['simple_products'] = (int)($res->fetch_assoc()['c'] ?? 0);
$res = $conn->query("SELECT COUNT(*) c FROM product_variants WHERE status = 1"); if ($res) $stats['variants'] = (int)($res->fetch_assoc()['c'] ?? 0);
$res = $conn->query("SELECT (
    (SELECT COUNT(*) FROM products WHERE has_variants = 0 AND stock_qty <= COALESCE(NULLIF(low_stock_alert,0),{$defaultThreshold}))
    +
    (SELECT COUNT(*) FROM product_variants WHERE status = 1 AND stock_qty <= COALESCE(NULLIF(low_stock_alert,0),{$defaultThreshold}))
) c"); if ($res) $stats['low_stock'] = (int)($res->fetch_assoc()['c'] ?? 0);
$res = $conn->query("SELECT (
    (SELECT COUNT(*) FROM products WHERE has_variants = 0 AND stock_qty = 0)
    +
    (SELECT COUNT(*) FROM product_variants WHERE status = 1 AND stock_qty = 0)
) c"); if ($res) $stats['zero_stock'] = (int)($res->fetch_assoc()['c'] ?? 0);
if (nay_stock_table_exists($conn, 'inventory_movements')) {
    $res = $conn->query("SELECT COUNT(*) c FROM inventory_movements WHERE DATE(created_at) = CURDATE()");
    if ($res) $stats['movements_today'] = (int)($res->fetch_assoc()['c'] ?? 0);
}
$recentMoves = nay_stock_fetch_movements($conn, ['limit' => 10]);
?>
<style>
.stock-page{padding:24px;direction:rtl}.stock-wrap{max-width:1550px;margin:0 auto}.stock-hero{background:linear-gradient(135deg,#153650,#204d73);color:#fff;border-radius:28px;padding:24px 26px;display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap;margin-bottom:20px}.stock-hero h1{margin:0 0 8px;font-size:31px;font-weight:900}.stock-hero p{margin:0;color:rgba(255,255,255,.82)}.hero-actions{display:flex;gap:10px;flex-wrap:wrap}.hero-actions a{display:inline-flex;align-items:center;justify-content:center;padding:12px 18px;border-radius:14px;text-decoration:none;font-weight:800}.hero-actions .light{background:#fff;color:#153650}.hero-actions .dark{background:rgba(255,255,255,.1);color:#fff;border:1px solid rgba(255,255,255,.18)}.stock-stats{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:16px;margin-bottom:18px}.stat-card{background:#fff;border:1px solid #e6eef5;border-radius:24px;padding:18px 20px;box-shadow:0 12px 35px rgba(16,24,40,.05)}.stat-card .label{font-size:13px;color:#6f8398;font-weight:700;margin-bottom:10px}.stat-card .value{font-size:28px;color:#17324d;font-weight:900;line-height:1}.stock-card{background:#fff;border:1px solid #e6eef5;border-radius:24px;box-shadow:0 12px 35px rgba(16,24,40,.05);overflow:hidden}.stock-card-header{padding:18px 22px;border-bottom:1px solid #edf2f7;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}.stock-card-header h3{margin:0;color:#17324d;font-size:18px}.stock-card-body{padding:22px}.toolbar{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;align-items:flex-start;margin-bottom:16px}.toolbar-left{display:flex;gap:10px;flex-wrap:wrap;align-items:flex-start}.toolbar input,.toolbar select,.toolbar textarea{padding:11px 13px;border:1px solid #d5e2ec;border-radius:12px;background:#fff}.toolbar input{min-width:240px}.toolbar textarea{min-width:280px;min-height:86px;resize:vertical}.toolbar button,.toolbar a{display:inline-flex;align-items:center;justify-content:center;padding:11px 15px;border-radius:12px;text-decoration:none;font-weight:800;border:none;cursor:pointer}.toolbar .primary{background:linear-gradient(135deg,#2f80ed,#56ccf2);color:#fff}.toolbar .light{background:#fff;color:#24415c;border:1px solid #d9e6f2}.toolbar .danger{background:#fff1f1;color:#b42318;border:1px solid #ffd5d5}.inventory-table{width:100%;border-collapse:collapse}.inventory-table th,.inventory-table td{padding:12px;border-bottom:1px solid #edf2f7;text-align:right;vertical-align:middle}.inventory-table th{background:#f8fbff;color:#23465f;font-size:13px}.thumb{width:54px;height:54px;border-radius:14px;overflow:hidden;background:#f2f7fb;border:1px solid #dbe7f1;display:flex;align-items:center;justify-content:center}.thumb img{width:100%;height:100%;object-fit:cover}.thumb-fallback{font-size:20px;color:#8aa0b7}.title-cell{display:flex;align-items:center;gap:12px}.title-main{font-weight:900;color:#17324d}.muted{color:#71839a;font-size:12px}.stock-input,.tiny-select{width:88px;padding:10px 12px;border:1px solid #d5e2ec;border-radius:12px;text-align:center;font-weight:800}.tiny-select{width:95px}.state-chip,.type-chip,.source-chip{display:inline-flex;align-items:center;justify-content:center;padding:6px 12px;border-radius:999px;font-size:12px;font-weight:800}.state-chip.red{background:#fff1f1;color:#b42318}.state-chip.orange{background:#fff7ed;color:#c2410c}.state-chip.green{background:#ecfdf3;color:#166534}.type-chip{background:#eef3f8;color:#4b647d}.source-chip{background:#eaf4ff;color:#0f5ca8}.quick-btns{display:flex;gap:6px;flex-wrap:wrap}.quick-btn{border:none;background:#eef5f9;color:#23465f;border-radius:10px;padding:7px 10px;font-weight:800;cursor:pointer}.variant-row{background:#fbfdff}.variant-cell{padding-right:32px}.flash{border-radius:18px;padding:14px 16px;margin-bottom:18px;font-weight:700}.flash.success{background:#ecfdf3;border:1px solid #b7ebc6;color:#166534}.flash.error{background:#fff1f1;border:1px solid #ffd5d5;color:#b42318}.split-grid{display:grid;grid-template-columns:1.4fr .9fr;gap:18px;margin-top:18px}.movements-table{width:100%;border-collapse:collapse}.movements-table th,.movements-table td{padding:12px;border-bottom:1px solid #edf2f7;text-align:right;vertical-align:top}.movements-table th{background:#f8fbff;color:#23465f;font-size:13px}.empty-state{padding:26px;text-align:center;color:#71839a}@media (max-width:1280px){.stock-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.split-grid{grid-template-columns:1fr}}@media (max-width:860px){.stock-stats{grid-template-columns:1fr}.toolbar,.toolbar-left{flex-direction:column}.inventory-table{font-size:13px}}
</style>
<div class="stock-page"><div class="stock-wrap">
    <div class="stock-hero">
        <div>
            <h1>إدارة المخزون</h1>
            <p>مرجع موحّد للمخزون: المنتج البسيط يُدار مباشرة، والمنتج ذو الفاريانتات يُدار من فاريانتاته مع سجل حركة واضح.</p>
        </div>
        <div class="hero-actions">
            <a class="light" href="stock_monitor.php">مراقبة المخزون</a>
            <a class="light" href="stock_movements.php">سجل الحركة</a>
            <a class="dark" href="list.php">قائمة المنتجات</a>
        </div>
    </div>

    <?php if ($successMessage): ?><div class="flash success"><?= e($successMessage) ?></div><?php endif; ?>
    <?php foreach ($errorMessages as $msg): ?><div class="flash error"><?= e($msg) ?></div><?php endforeach; ?>

    <div class="stock-stats">
        <div class="stat-card"><div class="label">منتجات بسيطة</div><div class="value"><?= number_format($stats['simple_products']) ?></div></div>
        <div class="stat-card"><div class="label">إجمالي الفاريانتات</div><div class="value"><?= number_format($stats['variants']) ?></div></div>
        <div class="stat-card"><div class="label">مخزون منخفض</div><div class="value"><?= number_format($stats['low_stock']) ?></div></div>
        <div class="stat-card"><div class="label">نفد مخزون</div><div class="value"><?= number_format($stats['zero_stock']) ?></div></div>
        <div class="stat-card"><div class="label">حركات اليوم</div><div class="value"><?= number_format($stats['movements_today']) ?></div></div>
    </div>

    <div class="stock-card">
        <div class="stock-card-header"><h3>تعديل جماعي للمخزون</h3><span class="muted">المنتج ذو الفاريانتات يعرض مجموع مخزونه لكن التعديل يكون على الفاريانتات فقط.</span></div>
        <div class="stock-card-body">
            <form method="get" class="toolbar" style="margin-bottom:18px">
                <div class="toolbar-left">
                    <input type="text" name="q" value="<?= e($q) ?>" placeholder="ابحث باسم المنتج أو البراند أو الفاريانت">
                    <button type="submit" class="primary">بحث</button>
                    <a href="stock_manage.php" class="light">إعادة ضبط</a>
                </div>
                <div class="muted">حد التنبيه الافتراضي الحالي: <strong><?= number_format($defaultThreshold) ?></strong></div>
            </form>

            <form method="post" id="bulk-stock-form">
                <div class="toolbar">
                    <div class="toolbar-left">
                        <select name="reason_code">
                            <?php foreach ($reasonLabels as $key => $label): ?>
                                <option value="<?= e($key) ?>"><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <textarea name="notes" placeholder="ملاحظة عامة ستُسجل على جميع الحركات الناتجة عن هذه العملية."></textarea>
                    </div>
                    <div class="toolbar-left">
                        <button type="button" class="danger" onclick="resetVisibleStocks()">تصفير الحقول الظاهرة</button>
                        <button type="submit" class="primary">حفظ كل التعديلات</button>
                    </div>
                </div>

                <?php if ($products): ?>
                    <table class="inventory-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 foreach ($products as $product): ?>
                            <?php $badge = nay_stock_badge_meta((string)$product['state']); ?>
                            <tr>
                                <td><?= (int)$product['id'] ?></td>
                                <td>
                                    <div class="title-cell">
                                        <div class="thumb">
                                            <?php $img = nay_stock_resolve_image((string)($product['main_image'] ?? '')); ?>
                                            <?php if ($img): ?><img src="<?= e($img) ?>" alt=""><?php else: ?><div class="thumb-fallback">🧴</div><?php endif; ?>
                                        </div>
                                        <div>
                                            <div class="title-main"><?= e($product['name']) ?></div>
                                            <div class="muted"><?= e(trim((string)($product['brand_part'] ?? '') . ' ' . (string)($product['product_part'] ?? ''))) ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td><span class="type-chip"><?= (int)$product['has_variants'] === 1 ? 'منتج مع فاريانتات' : 'منتج بسيط' ?></span></td>
                                <td><span class="source-chip"><?= (int)$product['has_variants'] === 1 ? 'المصدر: الفاريانتات' : 'المصدر: المنتج نفسه' ?></span></td>
                                <td><span class="state-chip <?= e($badge['class']) ?>"><?= e($badge['label']) ?></span></td>
                                <td><?= number_format((int)$product['visible_stock_qty']) ?></td>
                                <td>
                                    <?php if ((int)$product['has_variants'] === 0): ?>
                                        <input class="stock-input js-stock-input" type="number" min="0" name="product_stock[<?= (int)$product['id'] ?>]" value="<?= (int)$product['stock_qty'] ?>">
                                    <?php else: ?>
                                        <span class="muted">من الفاريانتات</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ((int)$product['has_variants'] === 0): ?>
                                        <input class="stock-input" type="number" min="0" name="product_alert[<?= (int)$product['id'] ?>]" value="<?= (int)$product['low_stock_alert'] ?>">
                                    <?php else: ?>
                                        <span class="muted">لكل فاريانت</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ((int)$product['has_variants'] === 0): ?>
                                        <select class="tiny-select" name="product_status[<?= (int)$product['id'] ?>]">
                                            <option value="1" <?= (int)$product['status'] === 1 ? 'selected' : '' ?>>مفعّل</option>
                                            <option value="0" <?= (int)$product['status'] === 0 ? 'selected' : '' ?>>معطّل</option>
                                        </select>
                                    <?php else: ?>
                                        <span class="muted">حسب الفاريانت</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ((int)$product['has_variants'] === 0): ?>
                                        <div class="quick-btns">
                                            <button class="quick-btn" type="button" onclick="adjustStock(this, 1)">+1</button>
                                            <button class="quick-btn" type="button" onclick="adjustStock(this, 5)">+5</button>
                                            <button class="quick-btn" type="button" onclick="adjustStock(this, 10)">+10</button>
                                            <button class="quick-btn" type="button" onclick="setZero(this)">تصفير</button>
                                        </div>
                                    <?php else: ?>
                                        <a class="quick-btn" href="variants.php?product_id=<?= (int)$product['id'] ?>">إدارة الفاريانتات</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php foreach ($product['variants'] as $variant): ?>
                                <?php $vBadge = nay_stock_badge_meta((string)$variant['state']); ?>
                                <tr class="variant-row">
                                    <td><?= (int)$variant['id'] ?></td>
                                    <td class="variant-cell">
                                        <div class="title-cell">
                                            <div class="thumb">
                                                <?php $vImg = nay_stock_resolve_image((string)($variant['variant_image'] ?? '')); ?>
                                                <?php if ($vImg): ?><img src="<?= e($vImg) ?>" alt=""><?php else: ?><div class="thumb-fallback">📦</div><?php endif; ?>
                                            </div>
                                            <div>
                                                <div class="title-main">↳ <?= e($variant['variant_name']) ?></div>
                                                <div class="muted">تبع المنتج: <?= e($product['name']) ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td><span class="type-chip">فاريانت</span></td>
                                    <td><span class="source-chip">المصدر: هذا السطر</span></td>
                                    <td><span class="state-chip <?= e($vBadge['class']) ?>"><?= e($vBadge['label']) ?></span></td>
                                    <td><?= number_format((int)$variant['stock_qty']) ?></td>
                                    <td><input class="stock-input js-stock-input" type="number" min="0" name="variant_stock[<?= (int)$variant['id'] ?>]" value="<?= (int)$variant['stock_qty'] ?>"></td>
                                    <td><input class="stock-input" type="number" min="0" name="variant_alert[<?= (int)$variant['id'] ?>]" value="<?= (int)$variant['low_stock_alert'] ?>"></td>
                                    <td>
                                        <select class="tiny-select" name="variant_status[<?= (int)$variant['id'] ?>]">
                                            <option value="1" <?= (int)$variant['status'] === 1 ? 'selected' : '' ?>>مفعّل</option>
                                            <option value="0" <?= (int)$variant['status'] === 0 ? 'selected' : '' ?>>معطّل</option>
                                        </select>
                                    </td>
                                    <td>
                                        <div class="quick-btns">
                                            <button class="quick-btn" type="button" onclick="adjustStock(this, 1)">+1</button>
                                            <button class="quick-btn" type="button" onclick="adjustStock(this, 5)">+5</button>
                                            <button class="quick-btn" type="button" onclick="adjustStock(this, 10)">+10</button>
                                            <button class="quick-btn" type="button" onclick="setZero(this)">تصفير</button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="empty-state">ماكو منتجات مطابقة.</div>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <div class="split-grid">
        <div class="stock-card">
            <div class="stock-card-header"><h3>آخر حركات المخزون</h3><a class="light" style="padding:10px 14px;border:1px solid #d9e6f2;border-radius:12px;text-decoration:none;color:#24415c" href="stock_movements.php">فتح السجل الكامل</a></div>
            <div class="stock-card-body">
                <?php if ($recentMoves): ?>
                    <table class="movements-table">
                        <thead><tr><th>العنصر</th><th>الحركة</th><th>قبل / بعد</th><th>المصدر</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentMoves as $move): ?>
                            <tr>
                                <td>
                                    <strong><?= e($move['variant_name'] ? (($move['product_name'] ?? '—') . ' - ' . $move['variant_name']) : ($move['product_name'] ?? '—')) ?></strong>
                                    <div class="muted"><?= e($move['created_at'] ?? '') ?></div>
                                </td>
                                <td>
                                    <div><?= e($reasonLabels[$move['reason_code'] ?? ''] ?? ($move['action_type'] ?? '—')) ?></div>
                                    <div class="muted"><?= e($move['notes'] ?? '—') ?></div>
                                </td>
                                <td>
                                    <div>قبل: <?= number_format((int)($move['qty_before'] ?? 0)) ?></div>
                                    <div>تغير: <?= number_format((int)($move['qty_change'] ?? 0)) ?></div>
                                    <div>بعد: <?= number_format((int)($move['qty_after'] ?? 0)) ?></div>
                                </td>
                                <td>
                                    <div><?= e($move['admin_name'] ?? 'النظام') ?></div>
                                    <div class="muted"><?= e($move['source'] ?? '—') ?></div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="empty-state">ماكو حركات مسجلة حتى الآن.</div>
                <?php endif; ?>
            </div>
        </div>
        <div class="stock-card">
            <div class="stock-card-header"><h3>ملاحظات المنطق الحالي</h3></div>
            <div class="stock-card-body">
                <div class="muted" style="line-height:1.9;font-size:14px">
                    <div>• المنتج البسيط يُدار من <strong>products.stock_qty</strong>.</div>
                    <div>• المنتج ذو الفاريانتات مصدره الحقيقي هو <strong>product_variants.stock_qty</strong>.</div>
                    <div>• مجموع مخزون الفاريانتات يُزامن تلقائياً داخل المنتج الأب لأغراض العرض فقط.</div>
                    <div>• أي تعديل من هنا يكتب سطر داخل <strong>سجل الحركة</strong>.</div>
                    <div>• تغييرات الطلبات والإلغاء منطقياً مرتبطة بنفس سجل الحركة إذا طُبّق SQL الجديد.</div>
                </div>
            </div>
        </div>
    </div>
</div></div>
<script>
function findInput(el){ return el.closest('tr').querySelector('.js-stock-input'); }
function adjustStock(el, amount){ const input = findInput(el); if(!input) return; input.value = Math.max(0, parseInt(input.value||0,10) + amount); }
function setZero(el){ const input = findInput(el); if(!input) return; input.value = 0; }
function resetVisibleStocks(){ document.querySelectorAll('.js-stock-input').forEach(el => el.value = 0); }
</script>
<?php require_once '../includes/footer.php'; ?>
