<?php
/**
 * System Information
 * Display PHP, MySQL, and server configuration
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireAdmin();

$pdo = getDB();

// PHP Information
$phpVersion = phpversion();
$phpExtensions = get_loaded_extensions();
sort($phpExtensions);

// MySQL Information
$mysqlVersion = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
$stmt = $pdo->query("SHOW VARIABLES LIKE 'max_allowed_packet'");
$maxPacket = $stmt->fetch();
$stmt = $pdo->query("SHOW VARIABLES LIKE 'innodb_buffer_pool_size'");
$bufferPool = $stmt->fetch();

// Database size
$stmt = $pdo->query("SELECT SUM(data_length + index_length) as size 
                    FROM information_schema.tables 
                    WHERE table_schema = DATABASE()");
$dbSize = $stmt->fetch()['size'];

// Table counts
$stmt = $pdo->query("SELECT table_name, table_rows 
                    FROM information_schema.tables 
                    WHERE table_schema = DATABASE() 
                    ORDER BY table_rows DESC");
$tableStats = $stmt->fetchAll();

// Server Information
$serverSoftware = $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown';
$serverProtocol = $_SERVER['SERVER_PROTOCOL'] ?? 'Unknown';
$serverOS = php_uname();
$serverTime = date('Y-m-d H:i:s');
$serverTimezone = date_default_timezone_get();

// PHP Configuration
$phpMemoryLimit = ini_get('memory_limit');
$phpMaxExecutionTime = ini_get('max_execution_time');
$phpUploadMaxFilesize = ini_get('upload_max_filesize');
$phpPostMaxSize = ini_get('post_max_size');
$phpDisplayErrors = ini_get('display_errors');

// Check if directories are writable
$writableDirs = [
    '../../config/' => is_writable('../../config/'),
    '../../assets/uploads/' => is_writable('../../assets/uploads/'),
    '../../logs/' => is_writable('../../logs/'),
    '../../backups/' => is_writable('../../backups/'),
    '../../tmp/cache/' => is_writable('../../tmp/cache/')
];

// Get database connection info
$dbHost = DB_HOST;
$dbName = DB_NAME;

// Get application statistics
$appStats = [
    'total_users' => $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn(),
    'total_doctors' => $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'doctor'")->fetchColumn(),
    'total_cases' => $pdo->query("SELECT COUNT(*) FROM cases")->fetchColumn(),
    'total_rubrics' => $pdo->query("SELECT COUNT(*) FROM rubrics")->fetchColumn(),
    'total_remedies' => $pdo->query("SELECT COUNT(*) FROM remedies")->fetchColumn(),
    'total_subscriptions' => $pdo->query("SELECT COUNT(*) FROM subscriptions")->fetchColumn()
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Information - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            padding: 15px 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .info-card {
            background: white;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .info-card .card-header {
            background: #f8f9fa;
            border-bottom: 1px solid #e0e0e0;
            font-weight: bold;
        }
        .status-ok { color: #28a745; }
        .status-warning { color: #ffc107; }
        .status-error { color: #dc3545; }
        .table-sm td, .table-sm th {
            padding: 8px;
        }
        .progress {
            height: 20px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin</h4>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                    <a class="nav-link" href="../doctors/index.php">
                        <i class="fas fa-user-md"></i> Doctors
                    </a>
                    <a class="nav-link" href="../subscriptions/index.php">
                        <i class="fas fa-credit-card"></i> Subscriptions
                    </a>
                    <a class="nav-link" href="../rubrics/index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link" href="../remedies/index.php">
                        <i class="fas fa-capsules"></i> Remedies
                    </a>
                    <a class="nav-link active" href="index.php">
                        <i class="fas fa-cog"></i> Settings
                    </a>
                    <a class="nav-link" href="system-info.php">
                        <i class="fas fa-info-circle"></i> System Info
                    </a>
                    <a class="nav-link" href="../profile.php">
                        <i class="fas fa-user"></i> Profile
                    </a>
                    <hr>
                    <a class="nav-link" href="../../logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </nav>
            </div>
            
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <h4 class="mb-0"><i class="fas fa-info-circle"></i> System Information</h4>
                </div>
                
                <div class="p-4">
                    <div class="row">
                        <div class="col-md-6">
                            <!-- Server Information -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fas fa-server"></i> Server Information
                                </div>
                                <div class="card-body">
                                    <table class="table table-sm table-bordered">
                                        <tr><th width="40%">Server Software:</th>
                                            <td><?php echo escape($serverSoftware); ?>
                                                <?php if (strpos($serverSoftware, 'Apache') !== false): ?>
                                                    <span class="status-ok"><i class="fas fa-check-circle"></i></span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Server OS:</th>
                                            <td><?php echo escape($serverOS); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Server Protocol:</th>
                                            <td><?php echo $serverProtocol; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Server Time:</th>
                                            <td><?php echo $serverTime; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Server Timezone:</th>
                                            <td><?php echo $serverTimezone; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Document Root:</th>
                                            <td><?php echo $_SERVER['DOCUMENT_ROOT']; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Server IP:</th>
                                            <td><?php echo $_SERVER['SERVER_ADDR'] ?? 'Unknown'; ?></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- PHP Information -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fab fa-php"></i> PHP Configuration
                                </div>
                                <div class="card-body">
                                    <table class="table table-sm table-bordered">
                                        <tr>
                                            <th width="40%">PHP Version:</th>
                                            <td>
                                                <?php echo $phpVersion; ?>
                                                <?php if (version_compare($phpVersion, '7.4.0', '<')): ?>
                                                    <span class="status-warning"><i class="fas fa-exclamation-triangle"></i> Update recommended (7.4+)</span>
                                                <?php elseif (version_compare($phpVersion, '8.0.0', '>=')): ?>
                                                    <span class="status-ok"><i class="fas fa-check-circle"></i> Modern version</span>
                                                <?php else: ?>
                                                    <span class="status-ok"><i class="fas fa-check-circle"></i> Compatible</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Memory Limit:</th>
                                            <td><?php echo $phpMemoryLimit; ?>
                                                <?php if ((int)$phpMemoryLimit < 128): ?>
                                                    <span class="status-warning"> (Recommended: 256M)</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Max Execution Time:</th>
                                            <td><?php echo $phpMaxExecutionTime; ?> seconds</td>
                                        </tr>
                                        <tr>
                                            <th>Upload Max Filesize:</th>
                                            <td><?php echo $phpUploadMaxFilesize; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Post Max Size:</th>
                                            <td><?php echo $phpPostMaxSize; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Display Errors:</th>
                                            <td class="<?php echo $phpDisplayErrors == '1' ? 'status-warning' : 'status-ok'; ?>">
                                                <?php echo $phpDisplayErrors == '1' ? 'ON (Disable in production)' : 'OFF'; ?>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- PHP Extensions -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fas fa-puzzle-piece"></i> PHP Extensions
                                    <span class="float-end text-muted small"><?php echo count($phpExtensions); ?> total</span>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php 
                                        $requiredExtensions = ['pdo_mysql', 'mysqli', 'json', 'session', 'curl', 'gd', 'mbstring'];
                                        foreach ($phpExtensions as $ext): 
                                            $isRequired = in_array($ext, $requiredExtensions);
                                        ?>
                                            <div class="col-md-4 col-6 mb-1">
                                                <small class="badge <?php echo $isRequired ? 'bg-primary' : 'bg-secondary'; ?>">
                                                    <?php echo $ext; ?>
                                                    <?php if ($isRequired): ?>
                                                        <i class="fas fa-check-circle"></i>
                                                    <?php endif; ?>
                                                </small>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <!-- MySQL Information -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fas fa-database"></i> MySQL Information
                                </div>
                                <div class="card-body">
                                    <table class="table table-sm table-bordered">
                                        <tr>
                                            <th width="40%">MySQL Version:</th>
                                            <td>
                                                <?php echo $mysqlVersion; ?>
                                                <?php if (version_compare($mysqlVersion, '5.7.0', '<')): ?>
                                                    <span class="status-warning"><i class="fas fa-exclamation-triangle"></i> Update recommended (5.7+)</span>
                                                <?php else: ?>
                                                    <span class="status-ok"><i class="fas fa-check-circle"></i></span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Database Name:</th>
                                            <td><?php echo $dbName; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Database Host:</th>
                                            <td><?php echo $dbHost; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Database Size:</th>
                                            <td><?php echo formatFileSize($dbSize); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Max Allowed Packet:</th>
                                            <td><?php echo $maxPacket['Value'] ?? 'Unknown'; ?></td>
                                        </tr>
                                        <tr>
                                            <th>InnoDB Buffer Pool:</th>
                                            <td><?php echo isset($bufferPool['Value']) ? round($bufferPool['Value'] / 1024 / 1024, 2) . ' MB' : 'Unknown'; ?></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- Table Statistics -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fas fa-table"></i> Database Tables
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered">
                                            <thead>
                                                <tr><th>Table Name</th><th>Rows</th><th>Estimated Size</th></tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($tableStats as $table): ?>
                                                <tr>
                                                    <td><?php echo $table['table_name']; ?></td>
                                                    <td><?php echo number_format($table['table_rows'] ?? 0); ?></td>
                                                    <td><?php echo formatFileSize(($table['table_rows'] ?? 0) * 1024); ?></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Application Statistics -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fas fa-chart-bar"></i> Application Statistics
                                </div>
                                <div class="card-body">
                                    <table class="table table-sm table-bordered">
                                        <tr>
                                            <th width="40%">Total Users:</th>
                                            <td><?php echo number_format($appStats['total_users']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Total Doctors:</th>
                                            <td><?php echo number_format($appStats['total_doctors']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Total Cases:</th>
                                            <td><?php echo number_format($appStats['total_cases']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Total Rubrics:</th>
                                            <td><?php echo number_format($appStats['total_rubrics']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Total Remedies:</th>
                                            <td><?php echo number_format($appStats['total_remedies']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Total Subscriptions:</th>
                                            <td><?php echo number_format($appStats['total_subscriptions']); ?></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- Directory Permissions -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fas fa-folder"></i> Directory Permissions
                                </div>
                                <div class="card-body">
                                    <table class="table table-sm table-bordered">
                                        <?php foreach ($writableDirs as $dir => $isWritable): ?>
                                        <tr>
                                            <th width="60%"><?php echo $dir; ?></th>
                                            <td class="<?php echo $isWritable ? 'status-ok' : 'status-error'; ?>">
                                                <?php if ($isWritable): ?>
                                                    <i class="fas fa-check-circle"></i> Writable
                                                <?php else: ?>
                                                    <i class="fas fa-times-circle"></i> Not Writable
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- System Health Score -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fas fa-heartbeat"></i> System Health Score
                                </div>
                                <div class="card-body">
                                    <?php
                                    $healthScore = 100;
                                    
                                    // Check PHP version
                                    if (version_compare($phpVersion, '7.4.0', '<')) $healthScore -= 20;
                                    if (version_compare($phpVersion, '8.0.0', '<')) $healthScore -= 10;
                                    
                                    // Check MySQL version
                                    if (version_compare($mysqlVersion, '5.7.0', '<')) $healthScore -= 20;
                                    
                                    // Check required extensions
                                    foreach ($requiredExtensions as $ext) {
                                        if (!in_array($ext, $phpExtensions)) $healthScore -= 15;
                                    }
                                    
                                    // Check writable directories
                                    foreach ($writableDirs as $isWritable) {
                                        if (!$isWritable) $healthScore -= 10;
                                    }
                                    
                                    $healthScore = max(0, $healthScore);
                                    $healthClass = $healthScore >= 80 ? 'success' : ($healthScore >= 60 ? 'warning' : 'danger');
                                    ?>
                                    <div class="text-center">
                                        <div class="progress">
                                            <div class="progress-bar bg-<?php echo $healthClass; ?>" 
                                                 role="progressbar" 
                                                 style="width: <?php echo $healthScore; ?>%" 
                                                 aria-valuenow="<?php echo $healthScore; ?>" 
                                                 aria-valuemin="0" 
                                                 aria-valuemax="100">
                                                <?php echo $healthScore; ?>%
                                            </div>
                                        </div>
                                        <p class="mt-2">
                                            <?php if ($healthScore >= 80): ?>
                                                <span class="status-ok"><i class="fas fa-check-circle"></i> System is healthy</span>
                                            <?php elseif ($healthScore >= 60): ?>
                                                <span class="status-warning"><i class="fas fa-exclamation-triangle"></i> Some issues detected</span>
                                            <?php else: ?>
                                                <span class="status-error"><i class="fas fa-times-circle"></i> System needs attention</span>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Export System Info -->
                            <div class="info-card">
                                <div class="card-header">
                                    <i class="fas fa-download"></i> Export
                                </div>
                                <div class="card-body">
                                    <a href="?export=system-info" class="btn btn-sm btn-info">
                                        <i class="fas fa-download"></i> Download System Report
                                    </a>
                                    <button onclick="window.print()" class="btn btn-sm btn-secondary">
                                        <i class="fas fa-print"></i> Print Report
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>