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

// Database configuration
$host = 'localhost';
$dbname = 'equipment';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    die(json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]));
}

// Initialize cart if not exists (FIXED: customer_id can be NULL)
function initCart($pdo) {
    if (!isset($_SESSION['cart_id'])) {
        $stmt = $pdo->prepare("INSERT INTO carts (customer_id) VALUES (NULL)");
        $stmt->execute();
        $_SESSION['cart_id'] = $pdo->lastInsertId();
    }
    return $_SESSION['cart_id'];
}

function getCartCount($pdo) {
    if (!isset($_SESSION['cart_id'])) return 0;
    
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(quantity), 0) as total FROM cart_items WHERE cart_id = ?");
    $stmt->execute([$_SESSION['cart_id']]);
    $result = $stmt->fetch();
    return (int)$result['total'];
}

function getCartItems($pdo) {
    if (!isset($_SESSION['cart_id'])) return [];
    
    $stmt = $pdo->prepare("
        SELECT ci.*, e.name, e.price, e.description, e.image_url, e.stock_quantity 
        FROM cart_items ci 
        JOIN equipment e ON ci.equipment_id = e.id 
        WHERE ci.cart_id = ?
    ");
    $stmt->execute([$_SESSION['cart_id']]);
    return $stmt->fetchAll();
}

function getCartTotal($pdo) {
    $items = getCartItems($pdo);
    $total = 0;
    foreach ($items as $item) {
        $total += $item['price'] * $item['quantity'];
    }
    return $total;
}

// Initialize cart on every page load
initCart($pdo);
?>