<?php
require_once '../config/cors.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'PUT') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $data = json_decode(file_get_contents("php://input"), true);

    $orderId = $data['orderId'] ?? $data['order_id'] ?? null;
    $userId = $data['userId'] ?? $data['user_id'] ?? null;

    if (!$orderId || !$userId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Order ID and User ID are required']);
        exit;
    }

    if ($userId === 'guest') {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Guest users cannot cancel orders']);
        exit;
    }

    // Start transaction
    $db->beginTransaction();

    // Check if order exists and belongs to user
    $stmt = $db->prepare("SELECT id, status, user_id FROM orders WHERE id = :order_id AND user_id = :user_id");
    $stmt->bindParam(':order_id', $orderId, PDO::PARAM_STR);
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
    $stmt->execute();
    
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        $db->rollBack();
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Order not found']);
        exit;
    }

    // Check if order can be cancelled (only pending and confirmed orders)
    if (!in_array($order['status'], ['pending', 'confirmed'])) {
        $db->rollBack();
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Order cannot be cancelled. It is already ' . $order['status']]);
        exit;
    }

    // Get order items to restore stock
    $stmt = $db->prepare("SELECT product_id, quantity FROM order_items WHERE order_id = :order_id");
    $stmt->bindParam(':order_id', $orderId, PDO::PARAM_STR);
    $stmt->execute();
    
    $orderItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Restore stock for each product
    foreach ($orderItems as $item) {
        $stmt = $db->prepare("UPDATE products SET stock = stock + :quantity WHERE id = :product_id");
        $stmt->bindParam(':quantity', $item['quantity']);
        $stmt->bindParam(':product_id', $item['product_id'], PDO::PARAM_STR);
        $stmt->execute();
    }

    // Update order status to cancelled
    $stmt = $db->prepare("UPDATE orders SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP WHERE id = :order_id");
    $stmt->bindParam(':order_id', $orderId, PDO::PARAM_STR);
    $stmt->execute();

    // Commit transaction
    $db->commit();

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Order cancelled successfully. Stock has been restored.'
    ]);

} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal Server Error: ' . $e->getMessage()
    ]);
}
?>