<?php
// Include DB connection
include './db.php';

// Start session
session_start();

// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not logged in']);
    exit();
}

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

// Decode JSON request body
$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);
$product_id = $data['id'] ?? null; // Get product ID from JSON input

if ($product_id) {
    // Query to get product details
    $stmt = $conn->prepare("SELECT id, product_name, price FROM products WHERE id = ?");
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    $stmt->bind_result($id, $product_name, $price);
    
    if ($stmt->fetch()) {
        $stmt->close();

        // Insert into cart
        $insert_stmt = $conn->prepare("INSERT INTO cart (user_id, machine_type, product_id, price) VALUES (?, ?, ?, ?)");
        $insert_stmt->bind_param("isii", $user_id, $product_name, $product_id, $price);
        $insert_stmt->execute();
        $insert_stmt->close();

        // Query updated cart items
        $cart_html = '';
        $fetch_cart = $conn->prepare("SELECT machine_id, machine_type, price FROM cart WHERE user_id = ?");
        $fetch_cart->bind_param("i", $user_id);
        $fetch_cart->execute();
        $fetch_cart->bind_result($machine_id, $machine_type, $item_price);

        while ($fetch_cart->fetch()) {
            $cart_html .= "
                <tr>
                    <td>" . htmlspecialchars($machine_type) . "</td>
                    <td>" . htmlspecialchars($machine_id) . "</td>
                    <td>Rp " . number_format($item_price, 0, ',', '.') . "</td>
                    <td>
                        <a href='remove_from_cart.php?machine_id=" . htmlspecialchars($machine_id) . "' class='btn btn-danger shadow btn-xs sharp'>
                            <i class='fa fa-trash'></i>
                        </a>
                    </td>
                </tr>
            ";
        }
        $fetch_cart->close();

        echo json_encode(['success' => true, 'cart_html' => $cart_html]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Product not found']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid product ID']);
}

$conn->close();
?>