<?php
/**
 * Test file to debug subscription API issues
 */

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

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

$response = [
    'test' => 'subscription_api_debug',
    'timestamp' => date('Y-m-d H:i:s'),
    'checks' => []
];

// Check 1: Config file exists
if (file_exists('config.php')) {
    $response['checks']['config_file'] = 'EXISTS';
    require_once 'config.php';
    
    // Check 2: Database connection
    try {
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        
        if ($conn->connect_error) {
            $response['checks']['database_connection'] = 'FAILED: ' . $conn->connect_error;
        } else {
            $response['checks']['database_connection'] = 'SUCCESS';
            
            // Check 3: Tables exist
            $tables = ['subscription_products', 'subscriptions', 'subscription_logs'];
            $response['checks']['tables'] = [];
            
            foreach ($tables as $table) {
                $result = $conn->query("SHOW TABLES LIKE '$table'");
                $response['checks']['tables'][$table] = ($result->num_rows > 0) ? 'EXISTS' : 'MISSING';
            }
            
            // Check 4: Products count
            $result = $conn->query("SELECT COUNT(*) as count FROM subscription_products WHERE is_active = 1");
            if ($result) {
                $row = $result->fetch_assoc();
                $response['checks']['active_products'] = $row['count'];
                
                // Check 5: Get products
                $result = $conn->query("SELECT product_id, title, price_usd FROM subscription_products WHERE is_active = 1");
                $products = [];
                while ($row = $result->fetch_assoc()) {
                    $products[] = $row;
                }
                $response['checks']['products_list'] = $products;
            }
            
            $conn->close();
        }
    } catch (Exception $e) {
        $response['checks']['database_error'] = $e->getMessage();
    }
} else {
    $response['checks']['config_file'] = 'MISSING';
}

echo json_encode($response, JSON_PRETTY_PRINT);
