<?php
/**
 * EasyStream Installation Test & System Information
 * Visit this page after installation to verify everything is working
 */

define('_ISVALID', true);

// Start output buffering for clean display
ob_start();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EasyStream Installation Test</title>
    <style>
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            margin: 0; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            min-height: 100vh; 
            padding: 20px; 
        }
        .container { 
            max-width: 1200px; 
            margin: 0 auto; 
            background: white; 
            border-radius: 12px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.2); 
            overflow: hidden; 
        }
        .header { 
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%); 
            color: white; 
            padding: 30px; 
            text-align: center; 
        }
        .header h1 { margin: 0; font-size: 2.5rem; }
        .header p { margin: 10px 0 0 0; opacity: 0.9; font-size: 1.1rem; }
        .content { padding: 30px; }
        .section { 
            margin-bottom: 30px; 
            padding: 20px; 
            border-radius: 8px; 
            border-left: 4px solid #007bff; 
            background: #f8f9fa; 
        }
        .section h2 { 
            margin: 0 0 15px 0; 
            color: #333; 
            font-size: 1.5rem; 
        }
        .status-grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); 
            gap: 20px; 
            margin: 20px 0; 
        }
        .status-card { 
            background: white; 
            padding: 20px; 
            border-radius: 8px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1); 
            border-left: 4px solid #28a745; 
        }
        .status-card.warning { border-left-color: #ffc107; }
        .status-card.error { border-left-color: #dc3545; }
        .status-icon { 
            font-size: 2rem; 
            margin-bottom: 10px; 
            display: block; 
        }
        .status-title { 
            font-weight: bold; 
            font-size: 1.1rem; 
            margin-bottom: 5px; 
        }
        .status-value { 
            color: #666; 
            font-size: 0.9rem; 
        }
        .info-table { 
            width: 100%; 
            border-collapse: collapse; 
            margin: 15px 0; 
        }
        .info-table th, .info-table td { 
            padding: 12px; 
            text-align: left; 
            border-bottom: 1px solid #ddd; 
        }
        .info-table th { 
            background: #f8f9fa; 
            font-weight: 600; 
            width: 30%; 
        }
        .success { color: #28a745; font-weight: bold; }
        .warning { color: #ffc107; font-weight: bold; }
        .error { color: #dc3545; font-weight: bold; }
        .btn { 
            display: inline-block; 
            padding: 12px 24px; 
            background: #007bff; 
            color: white; 
            text-decoration: none; 
            border-radius: 6px; 
            margin: 5px; 
            transition: background 0.3s; 
        }
        .btn:hover { background: #0056b3; }
        .btn.success { background: #28a745; }
        .btn.success:hover { background: #1e7e34; }
        .footer { 
            background: #f8f9fa; 
            padding: 20px; 
            text-align: center; 
            color: #666; 
            border-top: 1px solid #ddd; 
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1>🎬 EasyStream Installation Test</h1>
        <p>System verification and information dashboard</p>
    </div>

    <div class="content">
        <?php
        // System status checks
        $systemStatus = [];
        $overallStatus = 'success';

        // PHP Version Check
        $phpVersion = PHP_VERSION;
        $phpStatus = version_compare($phpVersion, '8.0', '>=') ? 'success' : 'warning';
        if ($phpStatus === 'warning') $overallStatus = 'warning';

        // Database Connection Check
        $dbStatus = 'error';
        $dbInfo = [];
        try {
            $pdo = new PDO(
                "mysql:host=db;dbname=easystream;charset=utf8mb4",
                "easystream",
                "easystream",
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            $dbStatus = 'success';
            
            // Get database info
            $dbInfo['version'] = $pdo->query("SELECT VERSION()")->fetchColumn();
            $dbInfo['tables'] = count($pdo->query("SHOW TABLES")->fetchAll());
            $dbInfo['users'] = $pdo->query("SELECT COUNT(*) FROM db_accountuser")->fetchColumn();
            $dbInfo['videos'] = $pdo->query("SELECT COUNT(*) FROM db_videofiles")->fetchColumn();
            
        } catch (Exception $e) {
            $dbStatus = 'error';
            $overallStatus = 'error';
            $dbInfo['error'] = $e->getMessage();
        }

        // File System Checks
        $coreFiles = [
            'index.php' => 'Main Platform',
            'login.php' => 'Authentication System',
            'admin.php' => 'Admin Dashboard',
            'users.php' => 'User Management',
            'status.php' => 'System Status',
            'f_core/config.database.php' => 'Database Configuration',
            'deploy/create_db.sql' => 'Database Schema'
        ];

        $fileStatus = [];
        foreach ($coreFiles as $file => $desc) {
            $fileStatus[$file] = [
                'exists' => file_exists($file),
                'description' => $desc,
                'size' => file_exists($file) ? filesize($file) : 0
            ];
        }

        // Server Environment
        $serverInfo = [
            'hostname' => gethostname(),
            'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'Unknown',
            'server_name' => $_SERVER['SERVER_NAME'] ?? 'Unknown',
            'server_port' => $_SERVER['SERVER_PORT'] ?? 'Unknown',
            'request_time' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']),
            'container' => $_SERVER['HTTP_X_HOSTNAME'] ?? 'Not in container'
        ];
        ?>

        <!-- Overall Status -->
        <div class="section">
            <h2>🚀 Installation Status</h2>
            <div class="status-grid">
                <div class="status-card <?= $overallStatus ?>">
                    <span class="status-icon"><?= $overallStatus === 'success' ? '✅' : ($overallStatus === 'warning' ? '⚠️' : '❌') ?></span>
                    <div class="status-title">Overall Status</div>
                    <div class="status-value">
                        <?php
                        switch ($overallStatus) {
                            case 'success':
                                echo '<span class="success">✅ Installation Successful</span>';
                                break;
                            case 'warning':
                                echo '<span class="warning">⚠️ Installation Complete with Warnings</span>';
                                break;
                            case 'error':
                                echo '<span class="error">❌ Installation Issues Detected</span>';
                                break;
                        }
                        ?>
                    </div>
                </div>

                <div class="status-card <?= $phpStatus ?>">
                    <span class="status-icon">🐘</span>
                    <div class="status-title">PHP Version</div>
                    <div class="status-value">
                        <?= $phpVersion ?> 
                        <?= $phpStatus === 'success' ? '<span class="success">✅ Compatible</span>' : '<span class="warning">⚠️ Update Recommended</span>' ?>
                    </div>
                </div>

                <div class="status-card <?= $dbStatus ?>">
                    <span class="status-icon">💾</span>
                    <div class="status-title">Database</div>
                    <div class="status-value">
                        <?php if ($dbStatus === 'success'): ?>
                            <span class="success">✅ Connected</span><br>
                            <?= $dbInfo['tables'] ?> tables, <?= $dbInfo['users'] ?> users
                        <?php else: ?>
                            <span class="error">❌ Connection Failed</span>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="status-card success">
                    <span class="status-icon">🐳</span>
                    <div class="status-title">Container</div>
                    <div class="status-value">
                        <span class="success">✅ Docker Active</span><br>
                        <?= $serverInfo['container'] ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- System Information -->
        <div class="section">
            <h2>🖥️ System Information</h2>
            <table class="info-table">
                <tr><th>PHP Version</th><td><?= PHP_VERSION ?></td></tr>
                <tr><th>Server Software</th><td><?= $serverInfo['server_software'] ?></td></tr>
                <tr><th>Hostname</th><td><?= $serverInfo['hostname'] ?></td></tr>
                <tr><th>Container ID</th><td><?= $serverInfo['container'] ?></td></tr>
                <tr><th>Server Name</th><td><?= $serverInfo['server_name'] ?></td></tr>
                <tr><th>Server Port</th><td><?= $serverInfo['server_port'] ?></td></tr>
                <tr><th>Document Root</th><td><?= $serverInfo['document_root'] ?></td></tr>
                <tr><th>Current Time</th><td><?= $serverInfo['request_time'] ?></td></tr>
                <tr><th>Memory Limit</th><td><?= ini_get('memory_limit') ?></td></tr>
                <tr><th>Max Execution Time</th><td><?= ini_get('max_execution_time') ?>s</td></tr>
                <tr><th>Upload Max Filesize</th><td><?= ini_get('upload_max_filesize') ?></td></tr>
                <tr><th>Post Max Size</th><td><?= ini_get('post_max_size') ?></td></tr>
            </table>
        </div>

        <!-- Database Information -->
        <?php if ($dbStatus === 'success'): ?>
        <div class="section">
            <h2>💾 Database Information</h2>
            <table class="info-table">
                <tr><th>Database Version</th><td><?= $dbInfo['version'] ?></td></tr>
                <tr><th>Total Tables</th><td><?= $dbInfo['tables'] ?></td></tr>
                <tr><th>Total Users</th><td><?= $dbInfo['users'] ?></td></tr>
                <tr><th>Total Videos</th><td><?= $dbInfo['videos'] ?></td></tr>
                <tr><th>Connection Host</th><td>db (Docker container)</td></tr>
                <tr><th>Database Name</th><td>easystream</td></tr>
                <tr><th>Character Set</th><td>utf8mb4</td></tr>
            </table>

            <?php
            // Check for key feature tables
            $featureTables = [
                'Core Platform' => ['db_accountuser', 'db_videofiles', 'db_settings'],
                'RBAC System' => ['db_roles', 'db_user_roles', 'db_role_permissions'],
                'Live Streaming' => ['db_live_streams', 'db_stream_viewers'],
                'Token System' => ['token_transactions', 'token_purchases'],
                'API System' => ['db_api_keys', 'db_api_logs'],
                'Branding' => ['db_branding_settings']
            ];

            // Core video platform features
            $videoFeatures = [
                'Video Processing' => [
                    'files' => ['f_core/f_classes/class.videoprocessor.php', 'f_jobs/VideoProcessingJob.php'],
                    'description' => 'Video conversion and thumbnail generation system',
                    'ffmpeg_check' => true
                ],
                'Video Player' => [
                    'files' => ['f_templates/tpl_frontend/tpl_file/tpl_view.tpl', 'f_templates/tpl_frontend/css/player.css'],
                    'description' => 'HTML5 video player with streaming support',
                    'ffmpeg_check' => false
                ],
                'Video Upload' => [
                    'files' => ['f_templates/tpl_frontend/tpl_file/tpl_upload.tpl', 'f_templates/tpl_frontend/css/upload.css'],
                    'description' => 'Video upload and management system',
                    'ffmpeg_check' => false
                ]
            ];

            $allTables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
            ?>

            <h3>🎯 Core Feature Status</h3>
            <div class="status-grid">
                <?php foreach ($featureTables as $feature => $tables): ?>
                    <?php
                    $featureStatus = 'success';
                    $missingTables = [];
                    foreach ($tables as $table) {
                        if (!in_array($table, $allTables)) {
                            $featureStatus = 'warning';
                            $missingTables[] = $table;
                        }
                    }
                    ?>
                    <div class="status-card <?= $featureStatus ?>">
                        <span class="status-icon"><?= $featureStatus === 'success' ? '✅' : '⚠️' ?></span>
                        <div class="status-title"><?= $feature ?></div>
                        <div class="status-value">
                            <?php if ($featureStatus === 'success'): ?>
                                <span class="success">✅ Ready</span>
                            <?php else: ?>
                                <span class="warning">⚠️ Missing: <?= implode(', ', $missingTables) ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <h3>🎬 Video Platform Features</h3>
            <div class="status-grid">
                <?php foreach ($videoFeatures as $feature => $config): ?>
                    <?php
                    // Check if core files exist
                    $filesExist = true;
                    $missingFiles = [];
                    foreach ($config['files'] as $file) {
                        if (!file_exists($file)) {
                            $filesExist = false;
                            $missingFiles[] = basename($file);
                        }
                    }
                    
                    // Check FFmpeg if required
                    $ffmpegExists = false;
                    if ($config['ffmpeg_check']) {
                        $ffmpegExists = file_exists('/usr/bin/ffmpeg') || file_exists('/usr/local/bin/ffmpeg') || 
                                       shell_exec('which ffmpeg 2>/dev/null') !== null;
                    }
                    
                    // Determine status
                    if (!$filesExist) {
                        $status = 'error';
                        $statusText = '❌ Missing Files';
                        $statusDetail = 'Missing: ' . implode(', ', $missingFiles);
                    } elseif ($config['ffmpeg_check'] && !$ffmpegExists) {
                        $status = 'warning';
                        $statusText = '⚠️ FFmpeg Required';
                        $statusDetail = 'Core files ready, FFmpeg needed for processing';
                    } else {
                        $status = 'success';
                        $statusText = '✅ Ready';
                        $statusDetail = 'All components available';
                    }
                    ?>
                    <div class="status-card <?= $status ?>">
                        <span class="status-icon">
                            <?php if ($status === 'success'): ?>
                                ✅
                            <?php elseif ($status === 'warning'): ?>
                                ⚠️
                            <?php else: ?>
                                ❌
                            <?php endif; ?>
                        </span>
                        <div class="status-title"><?= $feature ?></div>
                        <div class="status-value">
                            <span class="<?= $status ?>"><?= $statusText ?></span>
                            <br><small><?= $statusDetail ?></small>
                            <br><small><?= $config['description'] ?></small>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="section">
            <h2>💾 Database Connection Error</h2>
            <div class="status-card error">
                <span class="status-icon">❌</span>
                <div class="status-title">Connection Failed</div>
                <div class="status-value">
                    <span class="error">Error: <?= htmlspecialchars($dbInfo['error']) ?></span><br>
                    <small>Make sure Docker containers are running: <code>docker-compose up -d</code></small>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- File System Status -->
        <div class="section">
            <h2>📁 Core Files Status</h2>
            <table class="info-table">
                <?php foreach ($fileStatus as $file => $info): ?>
                <tr>
                    <th><?= htmlspecialchars($file) ?></th>
                    <td>
                        <?php if ($info['exists']): ?>
                            <span class="success">✅ Present</span> 
                            (<?= number_format($info['size']) ?> bytes) - <?= $info['description'] ?>
                        <?php else: ?>
                            <span class="error">❌ Missing</span> - <?= $info['description'] ?>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>

        <!-- PHP Extensions -->
        <div class="section">
            <h2>🔧 PHP Extensions</h2>
            <div class="status-grid">
                <?php
                $requiredExtensions = [
                    'pdo' => 'Database connectivity',
                    'pdo_mysql' => 'MySQL database support',
                    'gd' => 'Image processing',
                    'curl' => 'HTTP requests',
                    'json' => 'JSON processing',
                    'mbstring' => 'Multibyte string support',
                    'zip' => 'Archive support',
                    'xml' => 'XML processing'
                ];

                foreach ($requiredExtensions as $ext => $desc):
                    $loaded = extension_loaded($ext);
                ?>
                <div class="status-card <?= $loaded ? 'success' : 'error' ?>">
                    <span class="status-icon"><?= $loaded ? '✅' : '❌' ?></span>
                    <div class="status-title"><?= $ext ?></div>
                    <div class="status-value">
                        <?= $loaded ? '<span class="success">✅ Loaded</span>' : '<span class="error">❌ Missing</span>' ?><br>
                        <small><?= $desc ?></small>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Video Platform Requirements -->
        <div class="section">
            <h2>🎬 Video Platform Requirements</h2>
            <p>Core video streaming functionality status:</p>
            
            <?php
            // Check FFmpeg availability
            $ffmpegAvailable = file_exists('/usr/bin/ffmpeg') || file_exists('/usr/local/bin/ffmpeg') || 
                              shell_exec('which ffmpeg 2>/dev/null') !== null;
            ?>
            
            <div class="status-grid">
                <div class="status-card <?= $ffmpegAvailable ? 'success' : 'warning' ?>">
                    <span class="status-icon"><?= $ffmpegAvailable ? '✅' : '⚠️' ?></span>
                    <div class="status-title">FFmpeg (Video Processing)</div>
                    <div class="status-value">
                        <?php if ($ffmpegAvailable): ?>
                            <span class="success">✅ Available</span><br>
                            <strong>Features:</strong> Video conversion, thumbnails, optimization<br>
                            <small>Full video processing capabilities enabled</small>
                        <?php else: ?>
                            <span class="warning">⚠️ Not Found</span><br>
                            <strong>Impact:</strong> Limited video processing<br>
                            <small>Install FFmpeg for full functionality</small>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="status-card success">
                    <span class="status-icon">📡</span>
                    <div class="status-title">SRS Live Streaming</div>
                    <div class="status-value">
                        <span class="success">✅ Configured</span><br>
                        <strong>Protocol:</strong> RTMP input, HLS output<br>
                        <strong>Port:</strong> 1935 (RTMP)<br>
                        <small>Ready for live broadcasts</small>
                    </div>
                </div>

                <div class="status-card success">
                    <span class="status-icon">💰</span>
                    <div class="status-title">Monetization System</div>
                    <div class="status-value">
                        <span class="success">✅ Active</span><br>
                        <strong>Features:</strong> Tokens, payments, donations<br>
                        <strong>Currency:</strong> EasyCoins (EC)<br>
                        <small>Revenue system operational</small>
                    </div>
                </div>

                <div class="status-card success">
                    <span class="status-icon">🔧</span>
                    <div class="status-title">Background Jobs</div>
                    <div class="status-value">
                        <span class="success">✅ Ready</span><br>
                        <strong>Queue:</strong> Redis-based job processing<br>
                        <strong>Workers:</strong> Video, email, notifications<br>
                        <small>Async processing system ready</small>
                    </div>
                </div>
            </div>

            <?php if (!$ffmpegAvailable): ?>
            <div style="background: #fff3cd; padding: 15px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #ffc107;">
                <h4 style="margin: 0 0 10px 0; color: #856404;">⚠️ FFmpeg Setup Required</h4>
                <p style="margin: 0; color: #856404;">
                    <strong>For full video processing capabilities, install FFmpeg:</strong><br>
                    • Automatic video conversion and optimization<br>
                    • Thumbnail generation from videos<br>
                    • Multiple format support<br>
                    • Video quality processing<br><br>
                    <strong>Current Status:</strong> Basic video upload/playback works, but processing features are limited.
                </p>
            </div>
            <?php endif; ?>
        </div>

        <!-- Quick Actions -->
        <div class="section">
            <h2>🚀 Quick Actions</h2>
            <p>Your EasyStream platform is ready! Use these links to get started:</p>
            
            <a href="/" class="btn success">🏠 Visit Main Platform</a>
            <a href="/login" class="btn">🔐 User Login</a>
            <a href="/admin" class="btn">⚙️ Admin Panel</a>
            <a href="/status" class="btn">📊 System Status</a>
            
            <h3>Default Admin Account</h3>
            <table class="info-table" style="max-width: 400px;">
                <tr><th>Username</th><td><code>admin</code></td></tr>
                <tr><th>Password</th><td><code>admin123</code></td></tr>
                <tr><th>Access</th><td><a href="/login" class="btn" style="padding: 5px 10px; font-size: 0.9rem;">Login Now</a></td></tr>
            </table>

            <h3>🎯 Platform Capabilities</h3>
            <ul style="text-align: left; max-width: 600px;">
                <li>✅ <strong>Video Upload & Playback:</strong> Core streaming functionality ready</li>
                <li>✅ <strong>User Management:</strong> Registration, profiles, channels</li>
                <li>✅ <strong>Admin Dashboard:</strong> Complete platform administration</li>
                <li>✅ <strong>Live Streaming:</strong> RTMP broadcasting (port 1935)</li>
                <li>✅ <strong>Monetization:</strong> Token system with payments</li>
                <li>✅ <strong>API System:</strong> RESTful endpoints for mobile apps</li>
                <li><?= $ffmpegAvailable ? '✅' : '⚠️' ?> <strong>Video Processing:</strong> <?= $ffmpegAvailable ? 'Full conversion & thumbnails' : 'Basic upload (FFmpeg needed for processing)' ?></li>
            </ul>
        </div>
    </div>

    <div class="footer">
        <p><strong>EasyStream Professional Video Streaming Platform</strong></p>
        <p>Installation test completed at <?= date('Y-m-d H:i:s') ?> | 
           Server: <?= $serverInfo['hostname'] ?> | 
           PHP: <?= PHP_VERSION ?> | 
           Database: <?= $dbStatus === 'success' ? $dbInfo['tables'] . ' tables' : 'Not connected' ?>
        </p>
    </div>
</div>

</body>
</html>

<?php
// Clean output buffer
ob_end_flush();
?>