<?php
/**
 * PSAU GAD System - Health Check
 * This script checks if all system components are working correctly
 */

// Prevent caching
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PSAU GAD System - Health Check</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            min-height: 100vh;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
        }
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }
        .check-item {
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 5px;
            border-left: 4px solid #ccc;
            background: #f9f9f9;
        }
        .check-item.success {
            border-left-color: #10b981;
            background: #d1fae5;
        }
        .check-item.error {
            border-left-color: #ef4444;
            background: #fee2e2;
        }
        .check-item.warning {
            border-left-color: #f59e0b;
            background: #fef3c7;
        }
        .check-title {
            font-weight: bold;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
        }
        .icon {
            margin-right: 10px;
            font-size: 20px;
        }
        .check-message {
            font-size: 14px;
            color: #666;
            margin-left: 30px;
        }
        .section-title {
            font-size: 20px;
            font-weight: bold;
            margin: 30px 0 15px 0;
            color: #333;
            border-bottom: 2px solid #8b5cf6;
            padding-bottom: 10px;
        }
        .summary {
            background: #8b5cf6;
            color: white;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 30px;
            text-align: center;
        }
        .summary h2 {
            margin-bottom: 10px;
        }
        .stats {
            display: flex;
            justify-content: space-around;
            margin-top: 15px;
        }
        .stat {
            text-align: center;
        }
        .stat-number {
            font-size: 32px;
            font-weight: bold;
        }
        .stat-label {
            font-size: 12px;
            opacity: 0.9;
        }
        .footer {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e5e7eb;
            text-align: center;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🏥 PSAU GAD System Health Check</h1>
        <p class="subtitle">System diagnostics and status report</p>

        <?php
        $checks = [];
        $successCount = 0;
        $errorCount = 0;
        $warningCount = 0;

        // Check 1: PHP Version
        $phpVersion = phpversion();
        $phpOk = version_compare($phpVersion, '8.0.0', '>=');
        $checks[] = [
            'status' => $phpOk ? 'success' : 'warning',
            'title' => 'PHP Version',
            'message' => "Version $phpVersion " . ($phpOk ? '(OK)' : '(Recommended: 8.0+)')
        ];
        if ($phpOk) $successCount++; else $warningCount++;

        // Check 2: Config file
        $configExists = file_exists('config/config.php');
        $checks[] = [
            'status' => $configExists ? 'success' : 'error',
            'title' => 'Configuration File',
            'message' => $configExists ? 'config/config.php found' : 'config/config.php missing'
        ];
        if ($configExists) $successCount++; else $errorCount++;

        // Check 3: Database connection
        if ($configExists) {
            try {
                require_once 'config/database.php';
                $db = getDB();
                $checks[] = [
                    'status' => 'success',
                    'title' => 'Database Connection',
                    'message' => 'Successfully connected to database'
                ];
                $successCount++;
                
                // Check 4: Database tables
                $stmt = $db->query("SHOW TABLES");
                $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
                $tableCount = count($tables);
                $tablesOk = $tableCount >= 15;
                $checks[] = [
                    'status' => $tablesOk ? 'success' : 'warning',
                    'title' => 'Database Tables',
                    'message' => "$tableCount tables found " . ($tablesOk ? '(OK)' : '(Expected: 15+)')
                ];
                if ($tablesOk) $successCount++; else $warningCount++;
                
            } catch (Exception $e) {
                $checks[] = [
                    'status' => 'error',
                    'title' => 'Database Connection',
                    'message' => 'Failed: ' . $e->getMessage()
                ];
                $errorCount++;
            }
        }

        // Check 5: Composer dependencies
        $vendorExists = file_exists('vendor/autoload.php');
        $checks[] = [
            'status' => $vendorExists ? 'success' : 'error',
            'title' => 'Composer Dependencies',
            'message' => $vendorExists ? 'Dependencies installed' : 'Run: composer install'
        ];
        if ($vendorExists) $successCount++; else $errorCount++;

        // Check 6: Upload directories
        $uploadDirs = [
            'uploads' => 'Main uploads directory',
            'uploads/profiles' => 'Profile images',
            'uploads/certificates' => 'Certificates',
            'uploads/resources' => 'Resources',
            'uploads/qr_codes' => 'QR codes',
            'logs' => 'Log files'
        ];

        foreach ($uploadDirs as $dir => $label) {
            $exists = file_exists($dir);
            $writable = $exists && is_writable($dir);
            
            if ($exists && $writable) {
                $checks[] = [
                    'status' => 'success',
                    'title' => $label,
                    'message' => "$dir (writable)"
                ];
                $successCount++;
            } elseif ($exists && !$writable) {
                $checks[] = [
                    'status' => 'warning',
                    'title' => $label,
                    'message' => "$dir exists but not writable. Run: chmod 777 $dir"
                ];
                $warningCount++;
            } else {
                $checks[] = [
                    'status' => 'error',
                    'title' => $label,
                    'message' => "$dir missing. Run: mkdir -p $dir && chmod 777 $dir"
                ];
                $errorCount++;
            }
        }

        // Check 7: Required PHP extensions
        $extensions = [
            'pdo' => 'PDO',
            'pdo_mysql' => 'PDO MySQL',
            'mbstring' => 'Multibyte String',
            'json' => 'JSON',
            'curl' => 'cURL'
        ];

        foreach ($extensions as $ext => $label) {
            $loaded = extension_loaded($ext);
            $checks[] = [
                'status' => $loaded ? 'success' : 'error',
                'title' => "PHP Extension: $label",
                'message' => $loaded ? 'Loaded' : 'Not loaded'
            ];
            if ($loaded) $successCount++; else $errorCount++;
        }

        // Summary
        $totalChecks = count($checks);
        $overallStatus = $errorCount > 0 ? 'error' : ($warningCount > 0 ? 'warning' : 'success');
        ?>

        <div class="summary">
            <h2>Overall Status: <?php 
                if ($overallStatus === 'success') echo '✅ Healthy';
                elseif ($overallStatus === 'warning') echo '⚠️ Needs Attention';
                else echo '❌ Issues Found';
            ?></h2>
            <div class="stats">
                <div class="stat">
                    <div class="stat-number"><?php echo $successCount; ?></div>
                    <div class="stat-label">Passed</div>
                </div>
                <div class="stat">
                    <div class="stat-number"><?php echo $warningCount; ?></div>
                    <div class="stat-label">Warnings</div>
                </div>
                <div class="stat">
                    <div class="stat-number"><?php echo $errorCount; ?></div>
                    <div class="stat-label">Errors</div>
                </div>
            </div>
        </div>

        <div class="section-title">System Checks</div>

        <?php foreach ($checks as $check): ?>
            <div class="check-item <?php echo $check['status']; ?>">
                <div class="check-title">
                    <span class="icon">
                        <?php 
                        if ($check['status'] === 'success') echo '✅';
                        elseif ($check['status'] === 'warning') echo '⚠️';
                        else echo '❌';
                        ?>
                    </span>
                    <?php echo htmlspecialchars($check['title']); ?>
                </div>
                <div class="check-message">
                    <?php echo htmlspecialchars($check['message']); ?>
                </div>
            </div>
        <?php endforeach; ?>

        <div class="footer">
            <p><strong>PSAU GAD Information System</strong></p>
            <p>Health Check Report Generated: <?php echo date('F j, Y g:i A'); ?></p>
            <p style="margin-top: 10px;">
                <a href="index.php" style="color: #8b5cf6;">← Back to Homepage</a>
            </p>
        </div>
    </div>
</body>
</html>

