<?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'); }
}

$q = trim((string)($_GET['q'] ?? ''));
$stockState = trim((string)($_GET['stock_state'] ?? 'all'));
$rowType = trim((string)($_GET['row_type'] ?? 'all'));
$defaultThreshold = nay_stock_default_threshold($conn);

$sql = "SELECT * FROM (
            SELECT p.id, p.id AS product_id, NULL AS variant_id, p.name, p.name AS parent_name, p.main_image AS image,
                   'simple' AS row_type, p.stock_qty, p.low_stock_alert, p.status
            FROM products p
            WHERE p.has_variants = 0
            UNION ALL
            SELECT pv.id, pv.product_id, pv.id AS variant_id, pv.variant_name AS name, p.name AS parent_name, pv.variant_image AS image,
                   'variant' AS row_type, pv.stock_qty, pv.low_stock_alert, pv.status
            FROM product_variants pv
            INNER JOIN products p ON p.id = pv.product_id
        ) stock_rows WHERE 1=1";
$params = [];
$types = '';
if ($q !== '') {
    $sql .= ' AND (name LIKE ? OR parent_name LIKE ?)';
    $like = '%' . $q . '%';
    $params[] = $like;
    $params[] = $like;
    $types .= 'ss';
}
if ($rowType !== 'all' && in_array($rowType, ['simple', 'variant'], true)) {
    $sql .= ' AND row_type = ?';
    $params[] = $rowType;
    $types .= 's';
}
$sql .= ' ORDER BY stock_qty ASC, id DESC';
$stmt = $conn->prepare($sql);
if ($params) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
while ($row = $res->fetch_assoc()) {
    $row['effective_threshold'] = nay_stock_effective_threshold($conn, $row['low_stock_alert'] ?? 0);
    $row['state'] = nay_stock_state($conn, (int)$row['stock_qty'], (int)$row['effective_threshold']);
    if ($stockState !== 'all' && $row['state'] !== $stockState) {
        continue;
    }
    $rows[] = $row;
}
$stmt->close();

$stats = ['low_stock' => 0, 'zero_stock' => 0, 'healthy' => 0, 'movements_today' => 0];
foreach ($rows as $row) {
    if ($row['state'] === 'zero') $stats['zero_stock']++;
    elseif ($row['state'] === 'low') $stats['low_stock']++;
    else $stats['healthy']++;
}
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);
}
?>
<style>
.products-page{padding:24px;direction:rtl}.products-wrap{max-width:1450px;margin:0 auto}.page-topbar{display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap;margin-bottom:24px}.page-title h1{margin:0 0 8px;font-size:30px;font-weight:800;color:#17324d}.page-title p{margin:0;color:#71839a;font-size:14px}.top-actions{display:flex;gap:10px;flex-wrap:wrap}.btn-modern{display:inline-flex;align-items:center;justify-content:center;gap:8px;text-decoration:none;border:none;border-radius:14px;padding:12px 18px;font-size:14px;font-weight:800;cursor:pointer}.btn-modern.primary{background:linear-gradient(135deg,#2f80ed,#56ccf2);color:#fff}.btn-modern.light{background:#fff;color:#24415c;border:1px solid #d9e6f2}.stats-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin-bottom:20px}.stat-card{background:#fff;border:1px solid #ebf1f6;border-radius:24px;padding:20px;box-shadow:0 12px 35px rgba(16,24,40,.05)}.stat-card .label{color:#6f8398;font-size:13px;margin-bottom:10px;font-weight:700}.stat-card .value{color:#17324d;font-size:28px;font-weight:900;line-height:1}.card-box{background:#fff;border:1px solid #ebf1f6;border-radius:24px;overflow:hidden;box-shadow:0 12px 35px rgba(16,24,40,.05)}.card-body{padding:22px}.monitor-table{width:100%;border-collapse:collapse}.monitor-table th,.monitor-table td{padding:12px;border-bottom:1px solid #edf2f7;text-align:right;vertical-align:middle}.monitor-table th{background:#f8fbff}.badge{display:inline-flex;align-items:center;justify-content:center;padding:6px 12px;border-radius:999px;font-size:12px;font-weight:800}.badge.red{background:#fff1f1;color:#b42318}.badge.orange{background:#fff7ed;color:#c2410c}.badge.green{background:#ecfdf3;color:#166534}.search-box{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px}.search-box input,.search-box select{min-width:200px;padding:11px 13px;border:1px solid #d5e2ec;border-radius:12px}.empty-state{padding:28px;text-align:center;color:#71839a}.title-cell{display:flex;align-items:center;gap:12px}.thumb{width:48px;height:48px;border-radius:12px;background:#f2f7fb;border:1px solid #dbe7f1;overflow:hidden;display:flex;align-items:center;justify-content:center}.thumb img{width:100%;height:100%;object-fit:cover}.muted{color:#71839a;font-size:12px}
</style>
<div class="products-page"><div class="products-wrap">
    <div class="page-topbar">
        <div class="page-title"><h1>مراقبة المخزون</h1><p>عرض العناصر المنخفضة أو النافدة مع اعتماد حد التنبيه الخاص أو الافتراضي من الإعدادات.</p></div>
        <div class="top-actions"><a class="btn-modern light" href="stock_manage.php">إدارة المخزون</a><a class="btn-modern light" href="stock_movements.php">سجل الحركة</a><a class="btn-modern light" href="list.php">قائمة المنتجات</a></div>
    </div>
    <div class="stats-grid">
        <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['healthy']) ?></div></div>
        <div class="stat-card"><div class="label">حركات اليوم</div><div class="value"><?= number_format($stats['movements_today']) ?></div></div>
    </div>
    <div class="card-box"><div class="card-body">
        <form method="get" class="search-box">
            <input type="text" name="q" value="<?= e($q) ?>" placeholder="ابحث باسم المنتج أو الفاريانت">
            <select name="row_type">
                <option value="all" <?= $rowType === 'all' ? 'selected' : '' ?>>كل الأنواع</option>
                <option value="simple" <?= $rowType === 'simple' ? 'selected' : '' ?>>منتج بسيط</option>
                <option value="variant" <?= $rowType === 'variant' ? 'selected' : '' ?>>فاريانت</option>
            </select>
            <select name="stock_state">
                <option value="all" <?= $stockState === 'all' ? 'selected' : '' ?>>كل الحالات</option>
                <option value="zero" <?= $stockState === 'zero' ? 'selected' : '' ?>>نافد</option>
                <option value="low" <?= $stockState === 'low' ? 'selected' : '' ?>>منخفض</option>
                <option value="healthy" <?= $stockState === 'healthy' ? 'selected' : '' ?>>جيد</option>
            </select>
            <button class="btn-modern primary" type="submit">بحث</button>
            <a class="btn-modern light" href="stock_monitor.php">إعادة ضبط</a>
        </form>
        <?php if ($rows): ?>
            <table class="monitor-table">
                <thead><tr><th>#</th><th>العنصر</th><th>النوع</th><th>الكمية</th><th>حد التنبيه الفعلي</th><th>الحالة</th><th>إدارة</th></tr></thead>
                <tbody>
                <?php foreach ($rows as $row): ?>
                    <?php $badge = nay_stock_badge_meta((string)$row['state']); ?>
                    <tr>
                        <td><?= (int)$row['id'] ?></td>
                        <td>
                            <div class="title-cell">
                                <div class="thumb"><?php $img = nay_stock_resolve_image((string)($row['image'] ?? '')); ?><?php if ($img): ?><img src="<?= e($img) ?>" alt=""><?php else: ?>📦<?php endif; ?></div>
                                <div>
                                    <strong><?= e($row['name']) ?></strong>
                                    <?php if (($row['row_type'] ?? '') === 'variant'): ?><div class="muted">المنتج: <?= e($row['parent_name']) ?></div><?php endif; ?>
                                </div>
                            </div>
                        </td>
                        <td><?= ($row['row_type'] ?? '') === 'variant' ? 'فاريانت' : 'منتج بسيط' ?></td>
                        <td><?= number_format((int)$row['stock_qty']) ?></td>
                        <td><?= number_format((int)$row['effective_threshold']) ?><div class="muted">الافتراضي: <?= number_format($defaultThreshold) ?></div></td>
                        <td><span class="badge <?= e($badge['class']) ?>"><?= e($badge['label']) ?></span></td>
                        <td>
                            <?php if (($row['row_type'] ?? '') === 'variant'): ?>
                                <a class="btn-modern light" style="padding:8px 12px" href="variants.php?product_id=<?= (int)$row['product_id'] ?>">الفاريانتات</a>
                            <?php else: ?>
                                <a class="btn-modern light" style="padding:8px 12px" href="inventory.php?product_id=<?= (int)$row['product_id'] ?>">إدارة مباشرة</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="empty-state">ماكو عناصر مطابقة.</div>
        <?php endif; ?>
    </div></div>
</div></div>
<?php require_once '../includes/footer.php'; ?>
