<?php
/**
 * Test Script for Subscription Database
 */

header('Content-Type: application/json');
require_once 'config.php';

$action = $_GET['action'] ?? 'check_tables';

try {
    switch ($action) {
        case 'check_tables':
            // Check if subscription tables exist
            $tables = [];
            $stmt = $pdo->query("SHOW TABLES LIKE 'subscription%'");
            while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
                $tables[] = $row[0];
            }
            
            // Check users table columns
            $stmt = $pdo->query("DESCRIBE users");
            $user_columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'tables' => $tables,
                'user_columns' => $user_columns
            ]);
            break;
            
        case 'check_user':
            $userId = $_GET['user_id'] ?? 0;
            
            $stmt = $pdo->prepare("
                SELECT id, email, user_name, user_level, 
                       subscription_type, subscription_expires_at,
                       is_trial_used, trial_expires_at
                FROM users 
                WHERE id = ?
            ");
            $stmt->execute([$userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                echo json_encode([
                    'success' => true,
                    'user' => $user
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'User not found'
                ]);
            }
            break;
            
        case 'test_procedure':
            $userId = $_GET['user_id'] ?? 0;
            
            // Call stored procedure
            $stmt = $pdo->prepare("CALL check_user_subscription(?)");
            $stmt->execute([$userId]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'result' => $result
            ]);
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'message' => 'Unknown action'
            ]);
    }
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
