<?php
require_once 'includes/config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_once 'includes/email_helper.php';

// Provera CSRF tokena
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !verify_csrf_token($_POST['csrf_token'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Security error']);
        exit;
    }
}

header('Content-Type: application/json');

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Get product_id and quantity
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;

// Validate product_id and quantity
if ($product_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid product ID']);
    exit;
}

if ($quantity < 0) {
    echo json_encode(['success' => false, 'message' => 'Quantity must be greater than or equal to 0']);
    exit;
}

// Check if product exists
$product = get_product($product_id);
if (!$product) {
    echo json_encode(['success' => false, 'message' => 'Product not found']);
    exit;
}

// Update cart
if ($quantity == 0) {
    remove_from_cart($product_id);
} else {
    update_cart_item($product_id, $quantity);
}

// Calculate subtotal
$price = !empty($product['sale_price']) ? $product['sale_price'] : $product['price'];
$subtotal = $price * $quantity;

// Calculate cart totals
$cart_subtotal = get_cart_total();
$cart_total = $cart_subtotal; // In case we add shipping or discounts later

// Get cart count
$cart = get_cart();
$cart_count = 0;
foreach ($cart as $qty) {
    $cart_count += $qty;
}

// Return success response
echo json_encode([
    'success' => true,
    'message' => 'Cart updated',
    'subtotal' => format_price($subtotal),
    'cart_subtotal' => format_price($cart_subtotal),
    'cart_total' => format_price($cart_total),
    'cart_count' => $cart_count
]);