<?php
header('Content-Type: application/json');
require_once('config.php');

$order_id = isset($_POST['order_id']) ? (int)$_POST['order_id'] : 0;

if ($order_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
    exit;
}

try {
    $con->begin_transaction();

    // 🔹 Get all items of this order
    $stmt = $con->prepare("SELECT product_id, quantity FROM order_items WHERE order_id = ?");
    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception("No items found for this order.");
    }

    $update = $con->prepare("UPDATE tbl_stock_items 
                             SET stock = stock - ?, status='Confirmed' 
                             WHERE id = ?");
    while ($row = $result->fetch_assoc()) {
        $qty = (int)$row['quantity'];
        $pid = (int)$row['product_id'];

        $update->bind_param("ii", $qty, $pid);
        $update->execute();

        if ($update->affected_rows === 0) {
            throw new Exception("Failed to update stock for product ID $pid");
        }
    }
    $update->close();
    $stmt->close();

    $con->commit();
    echo json_encode(['success' => true, 'message' => 'Stock updated successfully']);

} catch (Exception $e) {
    $con->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
