<?php

session_start();
require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json; charset=utf-8');

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

$userId = $_SESSION['user_id'] ?? 0;
$action = $_GET['action'] ?? $_POST['action'] ?? '';

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

try {
    switch ($action) {
        case 'add':
            $productId = (int)($_POST['product_id'] ?? 0);
            $quantity = (int)($_POST['quantity'] ?? 1);

            if ($productId <= 0) {
                echo json_encode(['success' => false, 'message' => 'Неверный ID товара']);
                exit();
            }

            $checkProduct = $db->prepare("SELECT product_id, stock_quantity FROM products WHERE product_id = ? AND is_available = TRUE");
            $checkProduct->execute([$productId]);
            $product = $checkProduct->fetch();

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

            $checkCart = $db->prepare("SELECT cart_id, quantity FROM cart WHERE user_id = ? AND product_id = ?");
            $checkCart->execute([$userId, $productId]);
            $cartItem = $checkCart->fetch();

            if ($cartItem) {

                $newQuantity = $cartItem['quantity'] + $quantity;
                $stmt = $db->prepare("UPDATE cart SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE cart_id = ?");
                $stmt->execute([$newQuantity, $cartItem['cart_id']]);
            } else {

                $stmt = $db->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)");
                $stmt->execute([$userId, $productId, $quantity]);
            }

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

        case 'update':
            $productId = (int)($_POST['product_id'] ?? 0);
            $quantity = (int)($_POST['quantity'] ?? 1);

            if ($quantity <= 0) {

                $stmt = $db->prepare("DELETE FROM cart WHERE user_id = ? AND product_id = ?");
                $stmt->execute([$userId, $productId]);
            } else {
                $stmt = $db->prepare("UPDATE cart SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND product_id = ?");
                $stmt->execute([$quantity, $userId, $productId]);
            }

            echo json_encode(['success' => true, 'message' => 'Корзина обновлена']);
            break;

        case 'remove':
            $productId = (int)($_POST['product_id'] ?? 0);

            $stmt = $db->prepare("DELETE FROM cart WHERE user_id = ? AND product_id = ?");
            $stmt->execute([$userId, $productId]);

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

        case 'get':
            $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([$userId]);
            $items = $stmt->fetchAll();

            $total = 0;
            foreach ($items as &$item) {
                $item['subtotal'] = $item['price'] * $item['quantity'];
                $total += $item['subtotal'];
            }

            echo json_encode([
                'success' => true,
                'items' => $items,
                'total' => $total,
                'count' => array_sum(array_column($items, 'quantity'))
            ]);
            break;

        case 'count':
            $stmt = $db->prepare("SELECT COALESCE(SUM(quantity), 0) FROM cart WHERE user_id = ?");
            $stmt->execute([$userId]);
            $count = $stmt->fetchColumn();

            echo json_encode(['success' => true, 'count' => (int)$count]);
            break;

        case 'clear':
            $stmt = $db->prepare("DELETE FROM cart WHERE user_id = ?");
            $stmt->execute([$userId]);

            echo json_encode(['success' => true, 'message' => 'Корзина очищена']);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Неизвестное действие']);
    }

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