<?php
session_start();
header('Content-Type: application/json');

require_once "db.php"; // Include your PDO db.php

try {
    $user_id = $_SESSION['user_id'] ?? null;
    $session_token = session_id();

    // Validate product ID
    if (!isset($_GET['id'])) {
        echo json_encode(['success' => false, 'message' => 'No product specified']);
        exit();
    }
    $product_id = intval($_GET['id']);
    $qty = isset($_GET['qty']) ? max(1, intval($_GET['qty'])) : 1;

    // Ensure product exists
    $stmt = $conn->prepare("SELECT id, price, name FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$product) {
        echo json_encode(['success' => false, 'message' => 'Invalid product']);
        exit();
    }
    $price = $product['price'];

    // Find or create cart
    if ($user_id) {
        $stmt = $conn->prepare("SELECT id FROM carts WHERE user_id = ?");
        $stmt->execute([$user_id]);
    } else {
        $stmt = $conn->prepare("SELECT id FROM carts WHERE session_token = ?");
        $stmt->execute([$session_token]);
    }
    $cart = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($cart) {
        $cart_id = $cart['id'];
    } else {
        if ($user_id) {
            $stmt = $conn->prepare("INSERT INTO carts (user_id, session_token) VALUES (?, ?)");
            $stmt->execute([$user_id, $session_token]);
        } else {
            $stmt = $conn->prepare("INSERT INTO carts (session_token) VALUES (?)");
            $stmt->execute([$session_token]);
        }
        $cart_id = $conn->lastInsertId();
    }

    // Check if item already in cart
    $stmt = $conn->prepare("SELECT id, qty FROM cart_items WHERE cart_id = ? AND product_id = ?");
    $stmt->execute([$cart_id, $product_id]);
    $item = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($item) {
        // Update quantity
        $new_qty = $item['qty'] + $qty;
        $stmt = $conn->prepare("UPDATE cart_items SET qty = ? WHERE id = ?");
        $stmt->execute([$new_qty, $item['id']]);
    } else {
        // Insert new item
        $stmt = $conn->prepare("INSERT INTO cart_items (cart_id, product_id, qty, price) VALUES (?, ?, ?, ?)");
        $stmt->execute([$cart_id, $product_id, $qty, $price]);
    }

    echo json_encode([
        'success' => true,
        'message' => $product['name'] . ' added to cart',
        'product_id' => $product['id'],
        'in_cart' => true
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    exit();
}
