<?php
// Start the session
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo 'You need to log in first.';
    exit();
}

$user_id = $_SESSION['user_id'];  // Get the user ID from the session

// Get the machine ID from the URL
if (isset($_GET['machine_id'])) {
    $machine_id = $_GET['machine_id'];

    // Include your DB connection
    include './db.php';

    // Check if machine exists and fetch price
    $stmt = $conn->prepare("SELECT type, price FROM machine WHERE serialNumber = ?");
    $stmt->bind_param("s", $machine_id);
    $stmt->execute();
    $stmt->bind_result($machine_type, $price); // Bind both machine type and price
    $stmt->fetch();
    $stmt->close();

    // If the machine type and price are found
    if ($machine_type && $price !== null) {
        // Check if the machine already exists in the user's cart
        $stmt = $conn->prepare("SELECT COUNT(*) FROM cart WHERE user_id = ? AND machine_id = ?");
        $stmt->bind_param("is", $user_id, $machine_id);
        $stmt->execute();
        $stmt->bind_result($cart_count);
        $stmt->fetch();
        $stmt->close();

        // If the machine is already in the cart
        if ($cart_count > 0) {
            // Set a 'already exists' message in session
            $_SESSION['cart_message'] = [
                'type' => 'error',
                'message' => 'Machine already exists in your cart.'
            ];
            // Redirect back to the dashboard (no insert into cart)
            header("Location: dashboard.php");
            exit();
        } else {
            // Insert the machine into the cart, including the price
            $stmt = $conn->prepare("INSERT INTO cart (user_id, machine_id, machine_type, price) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("issd", $user_id, $machine_id, $machine_type, $price); // Use 'd' for decimal type
            $stmt->execute();
            $stmt->close();

            // Redirect to the order page after adding to the cart
            header("Location: order.php");
            exit();
        }
    } else {
        // Set error message if machine is not found
        $_SESSION['cart_message'] = [
            'type' => 'error',
            'message' => 'Machine not found or price unavailable.'
        ];
    }

    // Close the DB connection
    $conn->close();
} else {
    // Set error message if no machine is selected
    $_SESSION['cart_message'] = [
        'type' => 'error',
        'message' => 'No machine selected.'
    ];
}

// Redirect back to the dashboard
header("Location: dashboard.php");
exit();
?>
