<?php
/**
 * Safe Database Diagnostic Tool (test_db.php)
 * Checks PDO MySQL extensions, Host environment, and Database connection.
 * Security Note: NEVER displays or reveals the database password.
 */

// Basic error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 1. Check PHP Version
$php_version = PHP_VERSION;

// 2. Check PDO & PDO MySQL Drivers
$pdo_installed = class_exists('PDO');
$pdo_drivers = $pdo_installed ? PDO::getAvailableDrivers() : [];
$pdo_mysql_installed = in_array('mysql', $pdo_drivers);

// 3. Load Project Database Config
$config_loaded = false;
$db_file = __DIR__ . '/config/db.php';
$host = '';
$db_name = '';
$username = '';
$password = '';
$environment = '';

if (file_exists($db_file)) {
    require_once $db_file;
    $config_loaded = true;
    
    // Environment detection
    $server_name = $_SERVER['SERVER_NAME'] ?? $_SERVER['HTTP_HOST'] ?? 'localhost';
    $is_local = in_array($server_name, ['localhost', '127.0.0.1', '::1']) || strpos($server_name, '192.168.') === 0;
    $environment = $is_local ? 'Localhost / XAMPP' : 'Production Server';
    
    if (class_exists('Database')) {
        $ref = new ReflectionClass('Database');
        $props = $ref->getDefaultProperties();
        if ($is_local) {
            $host = $props['local_host'] ?? 'localhost';
            $db_name = $props['local_name'] ?? '';
            $username = $props['local_user'] ?? '';
            $password = $props['local_pass'] ?? '';
        } else {
            $host = $props['prod_host'] ?? 'localhost';
            $db_name = $props['prod_name'] ?? '';
            $username = $props['prod_user'] ?? '';
            $password = $props['prod_pass'] ?? '';
        }
    }
}

// 4. Test MySQL PDO Connection
$conn_status = "NOT TESTED";
$pdo_error_code = "-";
$pdo_error_msg = "-";
$server_version = "-";
$tables = [];

if ($pdo_mysql_installed && $config_loaded) {
    try {
        $dsn = "mysql:host={$host};dbname={$db_name};charset=utf8mb4";
        $pdo = new PDO($dsn, $username, $password, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT => 5
        ]);
        
        $conn_status = "SUCCESS";
        $server_version = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
        
        // Query list of tables
        $stmt = $pdo->query("SHOW TABLES");
        $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
    } catch (PDOException $e) {
        $conn_status = "FAILED";
        $pdo_error_code = $e->getCode();
        
        // Strip sensitive password from error message if present
        $msg = $e->getMessage();
        if (!empty($password)) {
            $msg = str_replace($password, '********', $msg);
        }
        $pdo_error_msg = $msg;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Database Diagnostic Test (test_db.php)</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: #0f172a;
            color: #f8fafc;
            padding: 24px 12px;
            margin: 0;
        }
        .card {
            max-width: 680px;
            margin: 0 auto;
            background: #1e293b;
            border-radius: 12px;
            padding: 28px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.4);
            border: 1px solid #334155;
        }
        h2 {
            margin-top: 0;
            color: #38bdf8;
            border-bottom: 2px solid #334155;
            padding-bottom: 12px;
        }
        .row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #334155;
            font-size: 0.95rem;
        }
        .label {
            color: #94a3b8;
            font-weight: 500;
        }
        .value {
            font-family: Consolas, Monaco, monospace;
            font-weight: 600;
            color: #f1f5f9;
        }
        .badge {
            padding: 4px 12px;
            border-radius: 6px;
            font-weight: bold;
            font-size: 0.85rem;
            display: inline-block;
        }
        .badge-success { background: #065f46; color: #34d399; }
        .badge-failed { background: #7f1d1d; color: #f87171; }
        .badge-info { background: #1e3a8a; color: #60a5fa; }
        .error-container {
            margin-top: 20px;
            background: #450a0a;
            border: 1px solid #991b1b;
            border-radius: 8px;
            padding: 16px;
            color: #fca5a5;
            font-family: Consolas, Monaco, monospace;
            font-size: 0.9rem;
            word-break: break-all;
        }
        .tables-list {
            margin-top: 15px;
            background: #0f172a;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #334155;
            max-height: 180px;
            overflow-y: auto;
        }
        .tables-list span {
            display: inline-block;
            background: #1e293b;
            padding: 3px 8px;
            border-radius: 4px;
            margin: 3px;
            font-size: 0.8rem;
            font-family: Consolas, monospace;
            border: 1px solid #475569;
        }
        .alert-box {
            margin-top: 20px;
            background: #3b2d07;
            border: 1px solid #854d0e;
            color: #fde047;
            padding: 12px;
            border-radius: 8px;
            font-size: 0.85rem;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="card">
        <h2>Database Diagnostic Test</h2>
        
        <div class="row">
            <span class="label">Environment:</span>
            <span class="value"><span class="badge badge-info"><?php echo htmlspecialchars($environment ?: 'Unknown'); ?></span></span>
        </div>
        
        <div class="row">
            <span class="label">PHP Version:</span>
            <span class="value"><?php echo htmlspecialchars($php_version); ?></span>
        </div>
        
        <div class="row">
            <span class="label">PDO Extension:</span>
            <span class="value"><?php echo $pdo_installed ? '<span class="badge badge-success">Enabled</span>' : '<span class="badge badge-failed">Missing</span>'; ?></span>
        </div>
        
        <div class="row">
            <span class="label">PDO MySQL Driver:</span>
            <span class="value"><?php echo $pdo_mysql_installed ? '<span class="badge badge-success">Installed</span>' : '<span class="badge badge-failed">Not Installed</span>'; ?></span>
        </div>
        
        <div class="row">
            <span class="label">Config File (config/db.php):</span>
            <span class="value"><?php echo $config_loaded ? '<span class="badge badge-success">Loaded</span>' : '<span class="badge badge-failed">Not Found</span>'; ?></span>
        </div>
        
        <div class="row">
            <span class="label">Database Host:</span>
            <span class="value"><?php echo htmlspecialchars($host); ?></span>
        </div>
        
        <div class="row">
            <span class="label">Database Name:</span>
            <span class="value"><?php echo htmlspecialchars($db_name); ?></span>
        </div>
        
        <div class="row">
            <span class="label">Database User:</span>
            <span class="value"><?php echo htmlspecialchars($username); ?></span>
        </div>

        <div class="row">
            <span class="label">Database Password:</span>
            <span class="value"><span class="badge badge-info"><?php echo !empty($password) ? 'Configured (Hidden)' : 'Empty'; ?></span></span>
        </div>
        
        <div class="row">
            <span class="label">Connection Status:</span>
            <span class="value">
                <?php if ($conn_status === 'SUCCESS'): ?>
                    <span class="badge badge-success">SUCCESS</span>
                <?php else: ?>
                    <span class="badge badge-failed">FAILED</span>
                <?php endif; ?>
            </span>
        </div>

        <?php if ($conn_status === 'SUCCESS'): ?>
            <div class="row">
                <span class="label">MySQL Server Version:</span>
                <span class="value"><?php echo htmlspecialchars($server_version); ?></span>
            </div>
            
            <div class="label" style="margin-top: 15px;">Existing Tables in Database (<?php echo count($tables); ?>):</div>
            <div class="tables-list">
                <?php if (count($tables) > 0): ?>
                    <?php foreach ($tables as $t): ?>
                        <span><?php echo htmlspecialchars($t); ?></span>
                    <?php endforeach; ?>
                <?php else: ?>
                    <span style="color: #f87171;">No tables found. Please import schema.sql</span>
                <?php endif; ?>
            </div>
        <?php elseif ($conn_status === 'FAILED'): ?>
            <div class="error-container">
                <div style="font-weight: bold; margin-bottom: 6px; color: #ef4444;">Connection Error Details:</div>
                <div><strong>PDO Error Code:</strong> <?php echo htmlspecialchars($pdo_error_code); ?></div>
                <div style="margin-top: 6px;"><strong>PDO Error Message:</strong> <?php echo htmlspecialchars($pdo_error_msg); ?></div>
            </div>
        <?php endif; ?>

        <div class="alert-box">
            🔒 <strong>Security Warning:</strong> This diagnostic tool does NOT expose passwords. Please delete <code>test_db.php</code> after testing is completed.
        </div>
    </div>
</body>
</html>
