<?php
require_once __DIR__ . '/../../config/db.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$fingerprint = $input['fingerprint'] ?? null;

if (!$fingerprint) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing fingerprint']);
    exit;
}

try {
    // 1. Get Subscription Status
    $stmt = $pdo->prepare("SELECT * FROM subscriptions WHERE fingerprint = :fingerprint AND is_active = 1 ORDER BY id DESC LIMIT 1");
    $stmt->execute([':fingerprint' => $fingerprint]);
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);

    $plan = $sub ? $sub['plan'] : 'free';
    $expiresAt = $sub ? $sub['expires_at'] : null;

    // Check expiration
    if ($expiresAt && strtotime($expiresAt) < time()) {
        // Expired, revert to free
        $stmt = $pdo->prepare("UPDATE subscriptions SET is_active = 0 WHERE id = :id");
        $stmt->execute([':id' => $sub['id']]);
        $plan = 'free';
        $expiresAt = null;
    }

    // 2. Get Daily Usage
    $today = date('Y-m-d');
    $stmt = $pdo->prepare("SELECT rides_accepted FROM daily_usage WHERE fingerprint = :fingerprint AND usage_date = :today");
    $stmt->execute([
        ':fingerprint' => $fingerprint,
        ':today' => $today
    ]);
    $usage = $stmt->fetch(PDO::FETCH_ASSOC);
    $ridesToday = $usage ? (int)$usage['rides_accepted'] : 0;

    // 3. Determine limits
    $limit = 1; // Default for free
    if ($plan === 'basic') $limit = 10;
    if ($plan === 'pro' || $plan === 'annual') $limit = -1; // Unlimited

    $canAccept = ($limit === -1) || ($ridesToday < $limit);

    echo json_encode([
        'success' => true,
        'plan' => $plan,
        'expires_at' => $expiresAt,
        'rides_today' => $ridesToday,
        'rides_limit' => $limit,
        'can_accept' => $canAccept
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
