<?php
session_start();
require_once 'config.php';

if (!isset($_SESSION['user_id'])) {
    echo "User not logged in.";
    exit;
}

$userId = $_SESSION['user_id'];

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['paymentMethod'])) {
    $paymentMethod = $_POST['paymentMethod'];

    function generateOrderNumber() {
        return rand(1000, 9999);
    }

    // Check if there's already an order that is not done
    $sqlCheck = "SELECT order_number FROM payment_method WHERE user_id = ? AND order_status != 'done' LIMIT 1";
    $stmtCheck = $conn->prepare($sqlCheck);
    $stmtCheck->bind_param("i", $userId);
    $stmtCheck->execute();
    $stmtCheck->store_result();

    if ($stmtCheck->num_rows > 0) {
        $stmtCheck->bind_result($existingOrderNumber);
        $stmtCheck->fetch();

        $sqlUpdate = "UPDATE payment_method SET payment_option = ? WHERE user_id = ? AND order_status != 'done'";
        $stmtUpdate = $conn->prepare($sqlUpdate);
        $stmtUpdate->bind_param("si", $paymentMethod, $userId);

        if ($stmtUpdate->execute()) {
            echo "Payment method updated to '$paymentMethod' (Order: $existingOrderNumber)";
        } else {
            echo "Error updating payment method: " . $stmtUpdate->error;
        }

        $stmtUpdate->close();

    } else {
        $orderNumber = generateOrderNumber();

        $sqlInsert = "INSERT INTO payment_method (user_id, payment_option, order_number, order_status) 
                      VALUES (?, ?, ?, 'pending')";
        $stmtInsert = $conn->prepare($sqlInsert);
        $stmtInsert->bind_param("isi", $userId, $paymentMethod, $orderNumber);

        if ($stmtInsert->execute()) {
            // Update cart2
            $sqlCartUpdate = "UPDATE cart2 SET order_number = ? WHERE user_id = ? AND menu_status = 'pending'";
            $stmtCartUpdate = $conn->prepare($sqlCartUpdate);
            $stmtCartUpdate->bind_param("ii", $orderNumber, $userId);
            $stmtCartUpdate->execute();
            $stmtCartUpdate->close();

            echo "New payment method '$paymentMethod' saved with Order Number: $orderNumber";
        } else {
            echo "Error saving payment method: " . $stmtInsert->error;
        }

        $stmtInsert->close();
    }

    $stmtCheck->close();
} else {
    echo "Invalid request.";
}

$conn->close();
?>
    