<?php
/**
 * Debug version of subscription.php to find errors
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

try {
    // Check if config exists
    if (!file_exists('config.php')) {
        throw new Exception('config.php not found');
    }
    require_once 'config.php';
    
    // Check if api_auth exists
    if (!file_exists('api_auth.php')) {
        throw new Exception('api_auth.php not found');
    }
    require_once 'api_auth.php';
    
    // Get action
    $action = $_GET['action'] ?? $_POST['action'] ?? '';
    $platform = $_GET['platform'] ?? $_POST['platform'] ?? 'ios';
    
    if ($action === 'get_products') {
        // Connect to database
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        
        if ($conn->connect_error) {
            throw new Exception('Database connection failed: ' . $conn->connect_error);
        }
        
        // Get products
        $stmt = $conn->prepare("
            SELECT product_id, title, price_usd, duration_days, description, features
            FROM subscription_products
            WHERE is_active = 1 AND (platform = ? OR platform = 'both')
            ORDER BY price_usd ASC
        ");
        
        $stmt->bind_param("s", $platform);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $products = [];
        while ($row = $result->fetch_assoc()) {
            $products[] = [
                'product_id' => $row['product_id'],
                'title' => $row['title'],
                'price_usd' => $row['price_usd'],
                'duration_days' => $row['duration_days'],
                'description' => $row['description'],
                'features' => json_decode($row['features'])
            ];
        }
        
        $stmt->close();
        $conn->close();
        
        echo json_encode([
            'success' => true,
            'products' => $products
        ], JSON_PRETTY_PRINT);
        
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid action: ' . $action
        ], JSON_PRETTY_PRINT);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ], JSON_PRETTY_PRINT);
}
