<?php
session_start();
include "../config/db.php";

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($order_id > 0) {
    // Verify this order belongs to the user and is still 'Pending'
    $order_check = mysqli_query($conn, "SELECT id, status FROM orders WHERE id = $order_id AND user_id = $user_id");
    
    if ($order_check && mysqli_num_rows($order_check) > 0) {
        $order = mysqli_fetch_assoc($order_check);
        
        if ($order['status'] === 'Pending') {
            // Update order status
            $update = mysqli_query($conn, "UPDATE orders SET status = 'Cancelled' WHERE id = $order_id");
            
            if ($update) {
                // Restore stock for cancelled items
                $items = mysqli_query($conn, "SELECT product_id, quantity FROM order_items WHERE order_id = $order_id");
                if ($items) {
                    while ($item = mysqli_fetch_assoc($items)) {
                        $pid = $item['product_id'];
                        $qty = $item['quantity'];
                        mysqli_query($conn, "UPDATE products SET stock = stock + $qty WHERE id = $pid");
                    }
                }
                $_SESSION['success_msg'] = "Order #0000" .$order_id ." has been successfully cancelled.";
            } else {
                $_SESSION['error_msg'] = "Error cancelling order. Please try again.";
            }
        } else {
            $_SESSION['error_msg'] = "Only Pending orders can be cancelled.";
        }
    } else {
        $_SESSION['error_msg'] = "Order not found or access denied.";
    }
} else {
    $_SESSION['error_msg'] = "Invalid order ID.";
}

header("Location: my-rentals.php");
exit();
?>
