<?php
session_start();

$host = 'localhost';
$dbname = 'exam_shop';
$user = 'root';
$pass = 'root'; // Укажите свой пароль

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Ошибка подключения: " . $e->getMessage());
}

function h($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function getAllCategories($pdo) {
    $stmt = $pdo->query("SELECT DISTINCT category FROM products WHERE is_active = 1 ORDER BY category");
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

// Функции для работы с корзиной в сессии
function initCart() {
    if(!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
    }
}

function addToCart($product_id, $quantity = 1) {
    initCart();
    if(isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id] += $quantity;
    } else {
        $_SESSION['cart'][$product_id] = $quantity;
    }
}

function removeFromCart($product_id) {
    initCart();
    unset($_SESSION['cart'][$product_id]);
}

function updateCartQuantity($product_id, $quantity) {
    initCart();
    if($quantity <= 0) {
        removeFromCart($product_id);
    } else {
        $_SESSION['cart'][$product_id] = $quantity;
    }
}

function getCartItems($pdo) {
    initCart();
    $items = [];
    $total = 0;
    
    if(!empty($_SESSION['cart'])) {
        $ids = array_keys($_SESSION['cart']);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders) AND is_active = 1");
        $stmt->execute($ids);
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach($products as $product) {
            $quantity = $_SESSION['cart'][$product['id']];
            $subtotal = $product['price'] * $quantity;
            $items[] = [
                'id' => $product['id'],
                'name' => $product['name'],
                'price' => $product['price'],
                'quantity' => $quantity,
                'subtotal' => $subtotal,
                'stock' => $product['stock']
            ];
            $total += $subtotal;
        }
    }
    
    return ['items' => $items, 'total' => $total];
}

function clearCart() {
    $_SESSION['cart'] = [];
}
?>