<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$username = $_SESSION['username'] ?? 'Guest';

// ================== FETCH PRODUCT ==================
$product_id = intval($_GET['id'] ?? 0);
$product = $conn->query("SELECT * FROM products WHERE id=$product_id")->fetch_assoc();
if (!$product) {
    echo "<div class='alert alert-danger'>Product not found.</div>";
    exit;
}

// ================== FETCH DEPARTMENTS ==================
$departments = $conn->query("SELECT * FROM departments ORDER BY name ASC");

// ================== HANDLE RESTOCK ==================
if (isset($_POST['restock'])) {
    $qty = intval($_POST['quantity'] ?? 0);
    $department_id = intval($_POST['department_id'] ?? 0);

    if ($qty > 0 && $department_id > 0) {
        // Check if stock exists for this department
        $exists = $conn->query("SELECT * FROM product_stock WHERE product_id=$product_id AND store_id=$department_id")->fetch_assoc();
        if ($exists) {
            $conn->query("UPDATE product_stock SET quantity = quantity + $qty WHERE product_id=$product_id AND store_id=$department_id");
        } else {
            $conn->query("INSERT INTO product_stock (product_id, store_id, quantity) VALUES ($product_id, $department_id, $qty)");
        }

        // Update total quantity in products table
        $sum_stock = $conn->query("SELECT SUM(quantity) AS total_qty FROM product_stock WHERE product_id=$product_id")->fetch_assoc()['total_qty'] ?? 0;
        $conn->query("UPDATE products SET quantity=$sum_stock WHERE id=$product_id");

        // Log movement
        $conn->query("INSERT INTO stock_movements (product_id, from_store_id, to_store_id, quantity, movement_type, created_at)
                      VALUES ($product_id, NULL, $department_id, $qty, 'Restock', NOW())");

        $dept_name = $conn->query("SELECT name FROM departments WHERE id=$department_id")->fetch_assoc()['name'];
        echo "<script>alert('Successfully restocked {$qty} units to {$dept_name}'); window.location='products.php';</script>";
        exit;
    } else {
        echo "<div class='alert alert-danger'>Enter a valid quantity and select a department.</div>";
    }
}

// ================== CURRENT STOCK BY DEPARTMENT ==================
$stock_by_department = $conn->query("
    SELECT d.name, ps.quantity 
    FROM departments d
    LEFT JOIN product_stock ps ON ps.store_id=d.id AND ps.product_id=$product_id
    ORDER BY d.name ASC
")->fetch_all(MYSQLI_ASSOC);

?>

<div class="container mt-4">
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>
    <button class="btn btn-secondary mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h3 class="text-center">Restock Product</h3>
    <hr>

    <div class="card p-4 mb-3">
        <h5>Product: <?= htmlspecialchars($product['name']) ?> (SKU: <?= $product['sku'] ?>)</h5>
        <h6>Current Stock by Department:</h6>
        <ul>
            <?php foreach($stock_by_department as $s): ?>
                <li><?= htmlspecialchars($s['name']) ?>: <?= intval($s['quantity'] ?? 0) ?> units</li>
            <?php endforeach; ?>
        </ul>

        <form method="POST" class="row g-3">
            <div class="col-md-4">
                <select name="department_id" class="form-control" required>
                    <option value="">-- Select Department --</option>
                    <?php while($d = $departments->fetch_assoc()): ?>
                        <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-3">
                <input type="number" name="quantity" class="form-control" placeholder="Quantity to add" min="1" required>
            </div>
            <div class="col-md-3">
                <button type="submit" name="restock" class="btn btn-success w-100">
                    <i class="fa fa-plus-circle"></i> Restock
                </button>
            </div>
        </form>
    </div>
</div>

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