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

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

$user_id = $_SESSION['user_id'] ?? 0;

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

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

try {
    // Получаем корзину из БД
    $stmt = $db->prepare("
        SELECT
            c.cart_id,
            c.product_id,
            c.quantity,
            p.name,
            p.price,
            p.image_url,
            p.stock_quantity
        FROM cart c
        JOIN products p ON c.product_id = p.product_id
        WHERE c.user_id = ? AND p.is_available = TRUE
        ORDER BY c.created_at DESC
    ");
    $stmt->execute([$user_id]);
    $cart_items = $stmt->fetchAll();

    // Обновляем сессию
    $_SESSION['cart'] = [];
    foreach ($cart_items as $item) {
        $_SESSION['cart'][$item['product_id']] = [
            'quantity' => $item['quantity'],
            'name' => $item['name'],
            'price' => $item['price'],
            'added_at' => time()
        ];
    }

    echo json_encode([
        'success' => true,
        'cart_items' => $cart_items,
        'total_items' => count($cart_items)
    ]);

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