<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

try {
    // For now, we'll just check the database for subscription status
    // In a real implementation, you would integrate with Stripe to check actual subscription status
    
    // Check subscription status
    $stmt = $pdo->prepare("SELECT subscribed, subscription_end, st.name as subscription_tier FROM subscribers s LEFT JOIN subscription_tiers st ON s.subscription_tier_id = st.id WHERE s.email = ?");
    $stmt->execute([$user['email']]);
    $subscription = $stmt->fetch();
    
    if (!$subscription) {
        jsonResponse([
            'subscribed' => false,
            'subscription_tier' => null,
            'subscription_end' => null
        ], 200);
    }
    
    $isActive = $subscription['subscribed'] && 
        (!$subscription['subscription_end'] || new DateTime($subscription['subscription_end']) > new DateTime());
    
    jsonResponse([
        'subscribed' => $isActive,
        'subscription_tier' => $subscription['subscription_tier'],
        'subscription_end' => $subscription['subscription_end']
    ], 200);
} catch (Exception $e) {
    errorResponse('Error checking subscription status: ' . $e->getMessage(), 500);
}
?>