<?php
// cart-api.php — Session-based AJAX cart API
// Actions: add_package, add_topup, remove_package, remove_topup, get_cart
session_start();
require_once 'config.php';

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

// Auth check
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['ok' => false, 'error' => 'Not logged in']);
    exit;
}

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

// Initialise cart
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = ['package' => null, 'topup' => null];
}

// ---------- Helper: fetch user's active subscription ----------
function get_active_subscription($conn, $user_id)
{
    $stmt = $conn->prepare(
        "SELECT us.package_id, sp.name, sp.price, sp.token_amount
         FROM user_subscriptions us
         JOIN subscription_packages sp ON us.package_id = sp.id
         WHERE us.user_id = ? AND us.status = 'active'
         LIMIT 1"
    );
    if (!$stmt)
        return null;
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row;
}

// ---------- Actions ----------
switch ($action) {

    // ============================================
    // ADD PACKAGE
    // ============================================
    case 'add_package':
        $pkg_id = intval($_POST['package_id'] ?? 0);
        if ($pkg_id <= 0) {
            echo json_encode(['ok' => false, 'error' => 'Invalid package']);
            exit;
        }

        // Fetch target package
        $stmt = $conn->prepare("SELECT id, name, price, token_amount FROM subscription_packages WHERE id = ? AND is_active = 1");
        $stmt->bind_param("i", $pkg_id);
        $stmt->execute();
        $target = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$target) {
            echo json_encode(['ok' => false, 'error' => 'Package not found']);
            exit;
        }

        // Free package cannot be purchased
        if ($target['price'] <= 0) {
            echo json_encode(['ok' => false, 'error' => 'Cannot purchase the free tier']);
            exit;
        }

        // Get current subscription
        $current = get_active_subscription($conn, $user_id);

        $adjusted_price = $target['price'];
        $adjusted_tokens = $target['token_amount'];
        $upgrade_from = null;

        if ($current && $current['price'] > 0) {
            // User has a paid subscription
            if ($target['price'] <= $current['price']) {
                echo json_encode([
                    'ok' => false,
                    'error' => 'Cannot select a package at or below your current plan (' . $current['name'] . '). Upgrades only.'
                ]);
                exit;
            }

            // Same package
            if ($target['id'] == $current['package_id']) {
                echo json_encode(['ok' => false, 'error' => 'You are already on this package']);
                exit;
            }

            // Upgrade: pay the difference
            $adjusted_price = $target['price'] - $current['price'];
            $adjusted_tokens = $target['token_amount'] - $current['token_amount'];
            $upgrade_from = $current['name'];
        }

        $_SESSION['cart']['package'] = [
            'id' => $target['id'],
            'name' => $target['name'],
            'tokens' => intval($target['token_amount']),
            'original_price' => floatval($target['price']),
            'adjusted_price' => floatval($adjusted_price),
            'adjusted_tokens' => intval($adjusted_tokens),
            'upgrade_from' => $upgrade_from,
        ];

        echo json_encode([
            'ok' => true,
            'cart' => $_SESSION['cart'],
            'count' => cart_count()
        ]);
        break;

    // ============================================
    // ADD TOKEN TOP-UP
    // ============================================
    case 'add_topup':
        $tokens = intval($_POST['tokens'] ?? 0);

        if ($tokens < 1000 || $tokens % 500 !== 0) {
            echo json_encode(['ok' => false, 'error' => 'Minimum 1,000 tokens in increments of 500']);
            exit;
        }

        // Gate: must have paid subscription
        $current = get_active_subscription($conn, $user_id);
        if (!$current || $current['price'] <= 0) {
            // Allow if user has a package upgrade in cart
            if (!$_SESSION['cart']['package']) {
                echo json_encode(['ok' => false, 'error' => 'Token top-ups require a paid subscription (Basic+)']);
                exit;
            }
        }

        $price = $tokens * COST_BASE_VALUE;
        $_SESSION['cart']['topup'] = [
            'tokens' => $tokens,
            'price' => $price,
        ];

        echo json_encode([
            'ok' => true,
            'cart' => $_SESSION['cart'],
            'count' => cart_count()
        ]);
        break;

    // ============================================
    // REMOVE PACKAGE
    // ============================================
    case 'remove_package':
        $_SESSION['cart']['package'] = null;
        echo json_encode(['ok' => true, 'cart' => $_SESSION['cart'], 'count' => cart_count()]);
        break;

    // ============================================
    // REMOVE TOP-UP
    // ============================================
    case 'remove_topup':
        $_SESSION['cart']['topup'] = null;
        echo json_encode(['ok' => true, 'cart' => $_SESSION['cart'], 'count' => cart_count()]);
        break;

    // ============================================
    // GET CART
    // ============================================
    case 'get_cart':
        echo json_encode([
            'ok' => true,
            'cart' => $_SESSION['cart'],
            'count' => cart_count(),
            'total' => cart_total()
        ]);
        break;

    default:
        echo json_encode(['ok' => false, 'error' => 'Unknown action']);
}

// ---------- Helpers ----------
function cart_count()
{
    $c = 0;
    if ($_SESSION['cart']['package'])
        $c++;
    if ($_SESSION['cart']['topup'])
        $c++;
    return $c;
}

function cart_total()
{
    $t = 0;
    if ($_SESSION['cart']['package'])
        $t += $_SESSION['cart']['package']['adjusted_price'];
    if ($_SESSION['cart']['topup'])
        $t += $_SESSION['cart']['topup']['price'];
    return $t;
}
