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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'User not authenticated. Please login first.']);
    exit;
}

// Check if user is a customer
if ($_SESSION['user_role'] !== 'customer') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Only customers can add items to cart.']);
    exit;
}

require_once 'config/db.php';

$user_id = $_SESSION['user_id'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

try {
    // ADD TO CART
    if ($action === 'add') {
        $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
        $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
        $product_name = isset($_POST['product_name']) ? $_POST['product_name'] : '';
        $price = isset($_POST['price']) ? floatval($_POST['price']) : 0;
        $image = isset($_POST['image']) ? $_POST['image'] : '';

        if ($product_id <= 0 || $quantity <= 0) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid product data']);
            exit;
        }

        // Check if product already in cart
        $stmt = $conn->prepare("SELECT id, quantity FROM cart WHERE user_id = ? AND product_id = ?");
        $stmt->bind_param("ii", $user_id, $product_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            // Update quantity
            $row = $result->fetch_assoc();
            $new_quantity = $row['quantity'] + $quantity;
            $cart_id = $row['id'];

            $update_stmt = $conn->prepare("UPDATE cart SET quantity = ? WHERE id = ?");
            $update_stmt->bind_param("ii", $new_quantity, $cart_id);
            $update_stmt->execute();
            $message = 'Product quantity updated in cart';
        } else {
            // Insert new cart item
            $insert_stmt = $conn->prepare("INSERT INTO cart (user_id, product_id, product_name, price, image, quantity) VALUES (?, ?, ?, ?, ?, ?)");
            $insert_stmt->bind_param("iisssi", $user_id, $product_id, $product_name, $price, $image, $quantity);
            $insert_stmt->execute();
            $message = 'Product added to cart successfully';
        }

        // Get updated cart count
        $count_stmt = $conn->prepare("SELECT COUNT(*) as count FROM cart WHERE user_id = ?");
        $count_stmt->bind_param("i", $user_id);
        $count_stmt->execute();
        $count_result = $count_stmt->get_result();
        $count_row = $count_result->fetch_assoc();

        echo json_encode([
            'success' => true,
            'message' => $message,
            'cart_count' => $count_row['count']
        ]);
        exit;
    }

    // REMOVE FROM CART
    else if ($action === 'remove') {
        // Get JSON data from request body
        $json_data = json_decode(file_get_contents('php://input'), true);
        $cart_id = isset($json_data['cart_id']) ? intval($json_data['cart_id']) : 0;
        
        error_log("REMOVE ACTION: cart_id = $cart_id, user_id = $user_id");

        if ($cart_id <= 0) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid cart item']);
            exit;
        }

        // Verify the cart item belongs to the user
        $verify_stmt = $conn->prepare("SELECT id FROM cart WHERE id = ? AND user_id = ?");
        $verify_stmt->bind_param("ii", $cart_id, $user_id);
        $verify_stmt->execute();
        $verify_result = $verify_stmt->get_result();

        if ($verify_result->num_rows === 0) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
            exit;
        }

        // Delete cart item
        $delete_stmt = $conn->prepare("DELETE FROM cart WHERE id = ?");
        $delete_stmt->bind_param("i", $cart_id);
        $delete_stmt->execute();
        
        error_log("Item deleted: $cart_id");

        // Get updated cart count
        $count_stmt = $conn->prepare("SELECT COUNT(*) as count FROM cart WHERE user_id = ?");
        $count_stmt->bind_param("i", $user_id);
        $count_stmt->execute();
        $count_result = $count_stmt->get_result();
        $count_row = $count_result->fetch_assoc();

        echo json_encode([
            'success' => true,
            'message' => 'Product removed from cart',
            'cart_count' => $count_row['count']
        ]);
        exit;
    }

    // GET CART
    else if ($action === 'get') {
        $stmt = $conn->prepare("SELECT id, product_id, product_name, price, image, quantity FROM cart WHERE user_id = ? ORDER BY id DESC");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $cart_items = [];
        $total = 0;

        while ($row = $result->fetch_assoc()) {
            $row['total_price'] = $row['price'] * $row['quantity'];
            $total += $row['total_price'];
            $cart_items[] = $row;
        }

        echo json_encode([
            'success' => true,
            'items' => $cart_items,
            'total' => $total,
            'count' => count($cart_items)
        ]);
        exit;
    }

    // GET CART COUNT
    else if ($action === 'count') {
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM cart WHERE user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();

        echo json_encode([
            'success' => true,
            'count' => $row['count']
        ]);
        exit;
    }

    else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        exit;
    }

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