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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../products.php');
    exit;
}

$productID = trim($_POST['ProductID'] ?? '');
$buyPrice  = (float) ($_POST['BuyPrice'] ?? 0);
$qty       = (int) ($_POST['Quantity'] ?? 0);

// BASIC VALIDATION
if ($productID === '' || $buyPrice <= 0 || $qty <= 0) {
    die('Invalid restock data.');
}

try {
    // START TRANSACTION
    $pdo->beginTransaction();

    // 1️⃣ Insert stock batch (FIFO)
    $stmt = $pdo->prepare("
        INSERT INTO stock_batches (ProductID, BuyPrice, Quantity, Remaining)
        VALUES (?, ?, ?, ?)
    ");
    $stmt->execute([$productID, $buyPrice, $qty, $qty]);

    // 2️⃣ Update product stock
    $stmt = $pdo->prepare("
        UPDATE products
        SET StockQuantity = StockQuantity + ?
        WHERE ProductID = ?
    ");
    $stmt->execute([$qty, $productID]);

    // COMMIT
    $pdo->commit();

    header('Location: ../products.php?restock=success');
    exit;

} catch (Exception $e) {
    $pdo->rollBack();
    die("Restock failed: " . $e->getMessage());
}
