<?php
/**
 * ============================================================
 * AJAX: Add to Cart
 * ============================================================
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be AJAX POST
if (!isAjax() || !isPost()) {
    Response::error('Invalid request', [], 400);
}

// Validate CSRF
if (!csrf_validate()) {
    Response::csrfError();
}

// Load cart service
require_once APP_PATH . '/services/cart_service.php';

// Get data
$productId = (int)post('product_id');
$qty = (int)post('qty', 1);

if ($productId < 1) {
    Response::error('অবৈধ পণ্য');
}

if ($qty < 1) {
    $qty = 1;
}

// Add to cart
$cartService = new CartService();
$result = $cartService->addItem($productId, $qty);

if ($result['success']) {
    Response::success($result['message'], [
        'cart_count' => $result['cart_count']
    ]);
} else {
    Response::error($result['message']);
}
