<?php
require_once('./config/db.php');
require_once('./includes/admin_only.php');

$pageTitle = "Product Restock";
include('./includes/header.php');

/* =========================
   HANDLE FORM SUBMISSION (WAC)
========================= */
$success = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $productID   = $_POST['ProductID'] ?? null;
    $newQty      = (int)($_POST['Quantity'] ?? 0);
    $newPrice    = (float)($_POST['BuyingPrice'] ?? 0);

    if (!$productID || $newQty <= 0 || $newPrice <= 0) {
        $error = "Invalid input";
    } else {

        try {
            $pdo->beginTransaction();

            // 1️⃣ Get current stock & buying price
            $stmt = $pdo->prepare("
                SELECT StockQuantity, BuyingPrice 
                FROM products 
                WHERE ProductID = ?
                FOR UPDATE
            ");
            $stmt->execute([$productID]);
            $product = $stmt->fetch();

            if (!$product) {
                throw new Exception("Product not found");
            }

            $currentQty   = (int)$product['StockQuantity'];
            $currentPrice = (float)$product['BuyingPrice'];

            // 2️⃣ Weighted Average Cost
            $totalQty = $currentQty + $newQty;

            if ($totalQty > 0) {
                $weightedPrice =
                    (($currentQty * $currentPrice) + ($newQty * $newPrice))
                    / $totalQty;
            } else {
                $weightedPrice = $newPrice;
            }

            // 3️⃣ Optional: log restock (recommended)
            $log = $pdo->prepare("
                INSERT INTO RestockLog (ProductID, QuantityReceived, PurchasePrice)
                VALUES (?, ?, ?)
            ");
            $log->execute([$productID, $newQty, $newPrice]);

            // 4️⃣ Update product
            $upd = $pdo->prepare("
                UPDATE products
                SET StockQuantity = ?, BuyingPrice = ?
                WHERE ProductID = ?
            ");
            $upd->execute([
                $totalQty,
                round($weightedPrice, 2),
                $productID
            ]);

            $pdo->commit();
            $success = true;
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = $e->getMessage();
        }
    }
}


/* =========================
   LOAD PRODUCTS
========================= */
$products = $pdo->query("
    SELECT ProductID, Name, BuyingPrice, StockQuantity, Photo
    FROM products
    ORDER BY Name ASC
")->fetchAll();
?>

<style>
    .product-card-item {
        cursor: pointer;
    }

    .product-card-item:hover {
        box-shadow: 0 0 0 2px #0d6efd;
    }

    #CurrentStock,
    #ProductID,
    #CurrentBuying {
        background-color: #f1f3f5;
        cursor: not-allowed;
    }
</style>

<div class="container-fluid mt-4">
    <div class="row">

        <!-- LEFT: RESTOCK FORM -->
        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-body">

                    <h5 class="mb-3">Restock Product</h5>

                    <?php if ($success): ?>
                        <div class="alert alert-success">Stock updated successfully</div>
                    <?php endif; ?>

                    <form method="POST">

                        <input type="text"
                            id="ProductID"
                            name="ProductID"
                            class="form-control"
                            readonly>


                        <div class="mb-3">
                            <label class="form-label fw-bold">Current Stock</label>
                            <input type="number"
                                id="CurrentStock"
                                class="form-control"
                                readonly
                                tabindex="-1">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">Current Buying Price</label>
                            <input type="number"
                                id="CurrentBuying"
                                class="form-control"
                                readonly
                                tabindex="-1">
                        </div>


                        <hr>

                        <div class="mb-3">
                            <label class="form-label fw-bold">Quantity to Add</label>
                            <input type="number" name="Quantity"
                                class="form-control" min="1" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">New Buying Price</label>
                            <input type="number" step="0.01"
                                name="BuyingPrice"
                                id="BuyingPrice"
                                class="form-control" required>
                        </div>

                        <button class="btn btn-primary w-100" type="submit"
                            onclick="return document.getElementById('ProductID').value !== '';">
                            Confirm Restock
                        </button>

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

        <!-- RIGHT: PRODUCT GRID -->
        <div class="col-lg-8">
            <div class="card shadow-sm border-0">
                <div class="card-body">

                    <h6 class="mb-3">Quick Product List</h6>

                    <!-- SEARCH -->
                    <div class="mb-3">
                        <input type="text" id="productSearch"
                            class="form-control"
                            placeholder="Search product by name...">
                    </div>

                    <div class="row" id="productList">
                        <?php foreach ($products as $p): ?>
                            <div class="col-md-6 mb-3 product-card-item"
                                data-name="<?= strtolower(htmlspecialchars($p['Name'])) ?>">

                                <div class="d-flex align-items-center gap-3 p-2 border rounded clickable-product"
                                    data-id="<?= htmlspecialchars($p['ProductID']) ?>"
                                    data-stock="<?= (int)$p['StockQuantity'] ?>"
                                    data-buy="<?= number_format((float)$p['BuyingPrice'], 2, '.', '') ?>">

                                    <div style="width:64px;">
                                        <?php if ($p['Photo']): ?>
                                            <img src="./uploads/<?= htmlspecialchars($p['Photo']) ?>"
                                                class="img-fluid rounded"
                                                style="height:64px; object-fit:cover;">
                                        <?php else: ?>
                                            <div class="bg-light text-center py-2 small rounded">No Image</div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="flex-grow-1">
                                        <div class="fw-semibold"><?= htmlspecialchars($p['Name']) ?></div>
                                        <small class="text-muted">
                                            Buy: <?= number_format($p['BuyingPrice'], 2) ?>
                                            | Stock: <?= (int)$p['StockQuantity'] ?>
                                        </small>
                                    </div>

                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

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

    </div>
</div>

<script>
    /* CLICK PRODUCT → FILL FORM */
    document.querySelectorAll('.clickable-product').forEach(card => {
        card.addEventListener('click', () => {
            document.getElementById('ProductID').value = card.dataset.id;
            document.getElementById('CurrentStock').value = card.dataset.stock;
            document.getElementById('CurrentBuying').value = card.dataset.buy;
        });
    });

    /* SEARCH FILTER */
    document.getElementById('productSearch').addEventListener('input', function() {
        const q = this.value.toLowerCase();
        document.querySelectorAll('.product-card-item').forEach(item => {
            item.style.display = item.dataset.name.includes(q) ? '' : 'none';
        });
    });
</script>

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