<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include '../connection.php'; // This should define $conn

try {
    // Validate POST parameters
    if (!isset($_POST['user_id'], $_POST['order_id'], $_POST['payment_method'])) {
        throw new Exception("Missing parameters");
    }

    $user_id = intval($_POST['user_id']);
    $order_id = intval($_POST['order_id']);
    $payment_method = $_POST['payment_method'];

    if ($user_id <= 0 || $order_id <= 0 || empty($payment_method)) {
        throw new Exception("Invalid parameter values");
    }

    // Start transaction
    //$conn->begin_transaction();

    // 1. Delete cart items
    $deleteCart = $conn->prepare("DELETE FROM tblcart WHERE user_id = ?");
    if (!$deleteCart) throw new Exception("Prepare failed for DELETE tblcart: " . $conn->error);
    $deleteCart->bind_param("i", $user_id);
    $deleteCart->execute();
    if ($deleteCart->error) throw new Exception("Failed to delete cart: " . $deleteCart->error);

    // 2. Update order status
    $payment_status = $payment_method === 'cod' ? 'Paid by cod' : 'Paid';
    $updateOrder = $conn->prepare("UPDATE tbl_order SET status='Submitted', payment_status=? WHERE id=? AND user_id=?");
    if (!$updateOrder) throw new Exception("Prepare failed for UPDATE tbl_order: " . $conn->error);
    $updateOrder->bind_param("sii", $payment_status, $order_id, $user_id);
    $updateOrder->execute();
    if ($updateOrder->error) throw new Exception("Failed to update order: " . $updateOrder->error);

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

    // Return success response
    echo json_encode([
        "success" => true,
        "message" => "Payment processed and cart cleared successfully"
    ]);

} catch (Exception $e) {
    // Rollback transaction on error
    if ($conn->in_transaction) $conn->rollback();

    // Return error JSON
    echo json_encode([
        "success" => false,
        "message" => $e->getMessage()
    ]);
    exit;
}
?>
