<?php
// ========================================
// عملیات سبد خرید (AJAX)
// پروژه فروشگاه کیف‌لند
// ========================================

require_once 'config/database.php';
require_once 'includes/auth.php';

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

// پشتیبانی از هر دو فرمت: JSON و form-urlencoded
$input = json_decode(file_get_contents('php://input'), true);
if ($input && isset($input['product_id'])) {
    // JSON
    $productId = intval($input['product_id']);
    $action    = $input['action'] ?? '';
    $quantity  = intval($input['quantity'] ?? 1);
} else {
    // form-urlencoded یا POST معمولی
    $productId = intval($_POST['product_id'] ?? 0);
    $action    = $_POST['action'] ?? '';
    $quantity  = intval($_POST['quantity'] ?? 1);
}

$db = Database::getInstance()->getConnection();
$response = ['success' => false, 'cart_count' => 0, 'message' => ''];

try {
    if ($action === 'add' && $productId) {
        // بررسی موجودی
        $stmt = $db->prepare("SELECT stock FROM products WHERE id = ?");
        $stmt->execute([$productId]);
        $product = $stmt->fetch();
        
        if (!$product) {
            throw new Exception('محصول یافت نشد');
        }
        
        if (Auth::isLoggedIn()) {
            $stmt = $db->prepare("SELECT quantity FROM cart WHERE user_id = ? AND product_id = ?");
            $stmt->execute([$_SESSION['user_id'], $productId]);
            $existing = $stmt->fetch();
            
            if ($existing) {
                $newQty = $existing['quantity'] + 1;
                if ($newQty <= $product['stock']) {
                    $db->prepare("UPDATE cart SET quantity = ? WHERE user_id = ? AND product_id = ?")
                       ->execute([$existing['quantity'] + $quantity, $_SESSION['user_id'], $productId]);
                } else {
                    throw new Exception('موجودی کافی نیست');
                }
            } else {
                $db->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, 1)")
                   ->execute([$_SESSION['user_id'], $productId]);
            }
            
            $stmt = $db->prepare("SELECT SUM(quantity) FROM cart WHERE user_id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $response['cart_count'] = $stmt->fetchColumn() ?: 0;
        } else {
            $_SESSION['cart_count'] = ($_SESSION['cart_count'] ?? 0) + 1;
            $response['cart_count'] = $_SESSION['cart_count'];
        }
        
        $response['success'] = true;
        $response['message'] = 'محصول به سبد اضافه شد';

        // اگه درخواست معمولی (نه AJAX) بود، ریدایرکت کن
        $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) 
               || str_contains($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json')
               || ($input && isset($input['product_id']));
        if (!$isAjax && $action === 'add') {
            header('Location: cart.php?added=1');
            exit;
        }
        
    } elseif ($action === 'count') {
        if (Auth::isLoggedIn()) {
            $stmt = $db->prepare("SELECT SUM(quantity) FROM cart WHERE user_id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $response['cart_count'] = $stmt->fetchColumn() ?: 0;
        } else {
            $response['cart_count'] = $_SESSION['cart_count'] ?? 0;
        }
        $response['success'] = true;
    } else {
        throw new Exception('عملیات نامعتبر');
    }
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
exit;
?>