<?php
session_start();
require_once 'config/database.php';

if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Требуется авторизация']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['product_id'])) {
    $product_id = intval($_POST['product_id']);
    $quantity = intval($_POST['quantity'] ?? 1);
    $user_id = $_SESSION['user_id'] ?? 0;

    if ($user_id == 0) {
        echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
        exit();
    }

    $db = Database::getInstance()->getConnection();

    try {
        // Проверяем наличие товара на складе
        $checkStock = $db->prepare("
            SELECT stock_quantity, name, price
            FROM products
            WHERE product_id = ? AND is_available = TRUE
        ");
        $checkStock->execute([$product_id]);
        $product = $checkStock->fetch();

        if (!$product) {
            echo json_encode(['success' => false, 'message' => 'Товар не найден']);
            exit();
        }

        if ($product['stock_quantity'] < $quantity) {
            echo json_encode(['success' => false, 'message' => 'Недостаточно товара на складе']);
            exit();
        }

        // Проверяем, есть ли товар уже в корзине пользователя
        $checkCart = $db->prepare("
            SELECT cart_id, quantity
            FROM cart
            WHERE user_id = ? AND product_id = ?
        ");
        $checkCart->execute([$user_id, $product_id]);
        $cartItem = $checkCart->fetch();

        if ($cartItem) {
            // Обновляем количество
            $newQuantity = $cartItem['quantity'] + $quantity;

            // Проверяем общее количество
            if ($newQuantity > $product['stock_quantity']) {
                echo json_encode(['success' => false, 'message' => 'Превышено доступное количество']);
                exit();
            }

            $updateStmt = $db->prepare("
                UPDATE cart
                SET quantity = ?, updated_at = CURRENT_TIMESTAMP
                WHERE cart_id = ?
            ");
            $updateStmt->execute([$newQuantity, $cartItem['cart_id']]);
        } else {
            // Добавляем новый товар
            $insertStmt = $db->prepare("
                INSERT INTO cart (user_id, product_id, quantity)
                VALUES (?, ?, ?)
            ");
            $insertStmt->execute([$user_id, $product_id, $quantity]);
        }

        // Обновляем сессию
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = [];
        }

        if (isset($_SESSION['cart'][$product_id])) {
            $_SESSION['cart'][$product_id]['quantity'] += $quantity;
        } else {
            $_SESSION['cart'][$product_id] = [
                'quantity' => $quantity,
                'name' => $product['name'],
                'price' => $product['price'],
                'added_at' => time()
            ];
        }

        // Получаем общее количество товаров в корзине
        $cartCountStmt = $db->prepare("
            SELECT SUM(quantity) as total
            FROM cart
            WHERE user_id = ?
        ");
        $cartCountStmt->execute([$user_id]);
        $cart_count = $cartCountStmt->fetchColumn() ?: 0;

        echo json_encode([
            'success' => true,
            'cart_count' => $cart_count,
            'message' => 'Товар добавлен в корзину'
        ]);

    } catch (PDOException $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Ошибка базы данных: ' . $e->getMessage()
        ]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Неверный запрос']);
}
?>