<?php
// install.php - Universal Installer for Hospital Management System
// Works in both Browser and CLI modes.

// Determine mode
$is_cli = (php_sapi_name() === 'cli');

if (!$is_cli) {
    // Web Mode
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Installation</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; padding-top: 50px; }
        .container { max-width: 800px; }
        .card { border-radius: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .log-output {
            background: #212529;
            color: #00ff00;
            font-family: monospace;
            padding: 15px;
            border-radius: 5px;
            max-height: 300px;
            overflow-y: auto;
            font-size: 0.9em;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h3 class="mb-0">🏥 Hospital Management System Installer</h3>
            </div>
            <div class="card-body">
    <?php
}

function log_msg($msg, $is_cli) {
    if ($is_cli) {
        echo strip_tags($msg) . "\n";
    } else {
        echo $msg . "<br>";
        flush();
    }
}

// Logic
$do_install = $is_cli || ($_SERVER['REQUEST_METHOD'] === 'POST');

if ($do_install) {
    if (!$is_cli) {
        echo '<h4>Installation Progress</h4><div class="log-output mb-3">';
    } else {
        echo "=== Hospital Management System Installer ===\n";
    }

    try {
        // 1. Check Config
        if (!file_exists(__DIR__ . '/db/config.php')) {
            throw new Exception("Configuration file 'db/config.php' not found.");
        }
        log_msg("✅ Configuration file found.", $is_cli);

        require_once __DIR__ . '/db/config.php';
        $db = db();
        log_msg("✅ Database connection established.", $is_cli);

        // 2. Run init_db.php logic
        log_msg("🔄 Initializing base database schema...", $is_cli);
        
        // Use output buffering to capture init_db output
        ob_start();
        include __DIR__ . '/init_db.php';
        $init_output = ob_get_clean();
        
        if ($is_cli) {
            echo "   >> " . str_replace("\n", "\n   >> ", trim($init_output)) . "\n";
        } else {
            log_msg(">> " . str_replace("\n", "<br>> ", trim($init_output)), $is_cli);
        }
        log_msg("✅ Base schema initialized.", $is_cli);

        // 3. Run migrations
        log_msg("🔄 Applying migrations...", $is_cli);
        
        $db->query("SET FOREIGN_KEY_CHECKS=0;");
        $files = glob(__DIR__ . '/db/migrations/*.sql');
        sort($files);
        
        $migrated_count = 0;
        foreach ($files as $file) {
            $filename = basename($file);
            
            $sql_content = file_get_contents($file);
            $sql_content = preg_replace('/--.*$/m', '', $sql_content);
            $statements = explode(';', $sql_content);
            
            foreach ($statements as $sql) {
                $sql = trim($sql);
                if (empty($sql)) continue;
                
                try {
                    // Use query() instead of exec() to handle potential result sets (like SELECT 1)
                    // and close the cursor explicitly.
                    $stmt = $db->query($sql);
                    if ($stmt) {
                        $stmt->closeCursor();
                    }
                } catch (PDOException $e) {
                    // Ignore "exists" errors
                    if (strpos($e->getMessage(), "Duplicate column") === false && 
                        strpos($e->getMessage(), "already exists") === false &&
                        strpos($e->getMessage(), "Duplicate key") === false &&
                        strpos($e->getMessage(), "1062 Duplicate entry") === false &&
                        strpos($e->getMessage(), "1054 Unknown column") === false &&
                        strpos($e->getMessage(), "1146 Table") === false &&
                        strpos($e->getMessage(), "1553 Cannot drop index") === false && strpos($e->getMessage(), "1826 Duplicate FOREIGN KEY") === false && strpos($e->getMessage(), "1828 Cannot drop column") === false) {
                        log_msg("⚠️ Error in $filename: " . $e->getMessage(), $is_cli);
                    }
                }
            }
            $migrated_count++;
        }
        $db->query("SET FOREIGN_KEY_CHECKS=1;");
        log_msg("✅ Applied $migrated_count migration files.", $is_cli);

        // 4. Verify Admin User
        $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
        $stmt->execute(['admin@hospital.com']);
        $count = $stmt->fetchColumn();
        $stmt->closeCursor(); // Close cursor

        if ($count == 0) {
            log_msg("⚠️ Admin user missing. Creating...", $is_cli);
            $pass = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi'; // admin123
            // Ensure role 1 exists (Administrator) - seed roles first if missing
            $stmt = $db->query("INSERT IGNORE INTO roles (id, name, slug, permissions) VALUES (1, 'Administrator', 'admin', '*')");
            $stmt->closeCursor();
            
            $stmt = $db->query("INSERT INTO users (name, email, password, role_id) VALUES ('System Admin', 'admin@hospital.com', '$pass', 1)");
            $stmt->closeCursor();
            log_msg("✅ Admin user created.", $is_cli);
        } else {
            log_msg("✅ Admin user exists.", $is_cli);
        }

        log_msg("🎉 Installation Completed Successfully!", $is_cli);
        
        if ($is_cli) {
            echo "\nLogin Credentials:\n";
            echo "Email: admin@hospital.com\n";
            echo "Password: admin123\n";
        }

    } catch (Exception $e) {
        log_msg("❌ CRITICAL ERROR: " . $e->getMessage(), $is_cli);
        $error = true;
    }

    if (!$is_cli) {
        echo '</div>'; // End log-output
        if (!isset($error)) {
            echo '<div class="alert alert-success">
                    <h5>Setup Complete!</h5>
                    <p>You can now log in to the system.</p>
                    <ul>
                        <li><strong>Email:</strong> admin@hospital.com</li>
                        <li><strong>Password:</strong> admin123</li>
                    </ul>
                    <a href="index.php" class="btn btn-success btn-lg">Go to Dashboard</a>
                  </div>';
        } else {
            echo '<div class="alert alert-danger">
                    <h5>Setup Failed</h5>
                    <p>Check logs above.</p>
                    <a href="install.php" class="btn btn-secondary">Retry</a>
                  </div>';
        }
    }

} else {
    // Web Mode: Show Welcome Screen
    ?>
                <h5>Welcome</h5>
                <p>This script will set up the database tables and default data.</p>
                
                <div class="alert alert-info">
                    <strong>Prerequisites:</strong>
                    <ul class="mb-0 mt-2">
                        <li>PHP Version: <?php echo phpversion(); ?> ✅</li>
                        <li>Config File: <?php echo file_exists(__DIR__ . '/db/config.php') ? 'Found ✅' : 'Missing ❌'; ?></li>
                    </ul>
                </div>

                <form method="post">
                    <button type="submit" class="btn btn-primary btn-lg w-100">🚀 Run Installation</button>
                </form>
    <?php
}

if (!$is_cli) {
    ?>
            </div>
            <div class="card-footer text-muted text-center">
                &copy; <?php echo date('Y'); ?> Hospital Management System
            </div>
        </div>
    </div>
</body>
</html>
    <?php
}
