<?php

require_once '../includes/auth.php';
require_once 'functions.php';

$search_keyword = trim($_GET['search_keyword'] ?? '');
$success_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_inventory'])) {
    if (!empty($_POST['stock_qty']) && is_array($_POST['stock_qty'])) {
        $stmt_update = $conn->prepare("
            UPDATE products
            SET stock_qty = ?, quantity = ?, updated_at = NOW()
            WHERE id = ?
            LIMIT 1
        ");

        if ($stmt_update) {
            foreach ($_POST['stock_qty'] as $product_id => $stock_qty) {
                $product_id = (int)$product_id;
                $stock_qty  = max(0, (int)$stock_qty);

                $stmt_update->bind_param("iii", $stock_qty, $stock_qty, $product_id);
                $stmt_update->execute();
            }

            $stmt_update->close();
            $success_message = 'تم تحديث المخزون بنجاح.';
        }
    }
}

if (isset($_GET['reset_id'])) {
    $reset_id = (int)$_GET['reset_id'];
    if ($reset_id > 0) {
        $stmt_reset = $conn->prepare("
            UPDATE products
            SET stock_qty = 0, quantity = 0, updated_at = NOW()
            WHERE id = ?
            LIMIT 1
        ");
        if ($stmt_reset) {
            $stmt_reset->bind_param("i", $reset_id);
            $stmt_reset->execute();
            $stmt_reset->close();
        }
        header("Location: inventory.php?reset=1");
        exit;
    }
}

$sql = "
    SELECT
        products.id,
        products.name,
        products.sku,
        products.image,
        products.stock_qty,
        products.low_stock_alert,
        products.track_stock,
        products.status,
        brands.name AS brand_name
    FROM products
    LEFT JOIN brands ON brands.id = products.brand_id
    WHERE 1=1
";

$params = [];
$bind_types = '';

if ($search_keyword !== '') {
    $sql .= " AND (products.name LIKE ? OR products.sku LIKE ?)";
    $search_value = '%' . $search_keyword . '%';
    $params[] = $search_value;
    $params[] = $search_value;
    $bind_types .= 'ss';
}

$sql .= " ORDER BY products.id DESC";

$stmt = $conn->prepare($sql);
$products_result = false;

if ($stmt) {
    if (!empty($params)) {
        $stmt->bind_param($bind_types, ...$params);
    }
    $stmt->execute();
    $products_result = $stmt->get_result();
}

$page_title = 'إدارة المخزون';

require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<div class="content-page">
    <div class="container-fluid">

        <div class="page-header-card mb-4">
            <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
                <div>
                    <h1 class="page-title mb-2">إدارة المخزون</h1>
                    <p class="page-subtitle mb-0">تعديل كميات المنتجات بسرعة من صفحة واحدة.</p>
                </div>

                <div class="d-flex flex-wrap gap-2">
                    <a href="index.php" class="btn btn-outline-secondary">
                        <i class="fa-solid fa-arrow-right me-1"></i>
                        رجوع
                    </a>
                </div>
            </div>
        </div>

        <?php if (!empty($success_message) || isset($_GET['reset'])): ?>
            <div class="alert alert-success">
                <?php echo !empty($success_message) ? htmlspecialchars($success_message) : 'تم تصفير كمية المنتج بنجاح.'; ?>
            </div>
        <?php endif; ?>

        <div class="card custom-card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-12 col-lg-10">
                        <label class="form-label">بحث باسم المنتج أو SKU</label>
                        <input type="text" name="search_keyword" class="form-control" value="<?php echo htmlspecialchars($search_keyword); ?>">
                    </div>

                    <div class="col-12 col-lg-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fa-solid fa-magnifying-glass me-1"></i>
                            بحث
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card custom-card">
            <div class="card-body">
                <form method="post">
                    <input type="hidden" name="save_inventory" value="1">

                    <?php if ($products_result && $products_result->num_rows > 0): ?>
                        <div class="table-responsive">
                            <table class="table align-middle custom-table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>الصورة</th>
                                        <th>المنتج</th>
                                        <th>البراند</th>
                                        <th>SKU</th>
                                        <th>الحالة</th>
                                        <th>المخزون</th>
                                        <th style="width:150px;">تعديل الكمية</th>
                                        <th style="width:120px;">إجراء سريع</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($product = $products_result->fetch_assoc()): ?>
                                        <tr>
                                            <td><?php echo (int)$product['id']; ?></td>
                                            <td>
                                                <img
                                                    src="<?php echo htmlspecialchars(products_image_url($product['image'] ?? '')); ?>"
                                                    alt="<?php echo htmlspecialchars($product['name'] ?? ''); ?>"
                                                    style="width:50px;height:50px;object-fit:cover;border-radius:12px;border:1px solid #e5e7eb;"
                                                >
                                            </td>
                                            <td class="fw-bold"><?php echo htmlspecialchars($product['name'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($product['brand_name'] ?? '---'); ?></td>
                                            <td><?php echo htmlspecialchars($product['sku'] ?? '---'); ?></td>
                                            <td><?php echo products_status_badge($product['status'] ?? 0); ?></td>
                                            <td>
                                                <div><?php echo number_format((int)$product['stock_qty']); ?></div>
                                                <div class="mt-1">
                                                    <?php echo products_stock_badge((int)$product['stock_qty'], (int)$product['low_stock_alert'], (int)$product['track_stock']); ?>
                                                </div>
                                            </td>
                                            <td>
                                                <input
                                                    type="number"
                                                    min="0"
                                                    name="stock_qty[<?php echo (int)$product['id']; ?>]"
                                                    class="form-control"
                                                    value="<?php echo (int)$product['stock_qty']; ?>"
                                                >
                                            </td>
                                            <td>
                                                <a href="inventory.php?reset_id=<?php echo (int)$product['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('هل تريد تصفير الكمية؟');">
                                                    تصفير
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>

                        <div class="mt-4 d-flex justify-content-end">
                            <button type="submit" class="btn btn-primary">
                                <i class="fa-solid fa-floppy-disk me-1"></i>
                                حفظ الكميات
                            </button>
                        </div>
                    <?php else: ?>
                        <div class="empty-state-box text-center py-5">
                            <i class="fa-solid fa-warehouse mb-3" style="font-size:48px;color:#96b8cc;"></i>
                            <h5 class="mb-2">لا توجد منتجات</h5>
                            <p class="text-muted mb-0">أضف منتجات أولاً حتى تقدر تدير المخزون.</p>
                        </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>

    </div>
</div>

<?php require_once '../includes/footer.php'; ?>