<?php
session_start();
$basePath = dirname(__DIR__);
require_once $basePath . '/app/bootstrap.php';
if (file_exists($basePath . '/config.php') || file_exists($basePath . '/install/install.lock')) { die('Installer is locked. To reinstall safely, back up the database, remove config.php and install/install.lock manually, then reload this page.'); }
$step = 4;
$stepNames = ['Welcome', 'Requirements', 'Permissions', 'Database', 'Import', 'Academy', 'Banking', 'Admin'];
$error = '';
$success = '';

// AJAX test connection
if (isset($_GET['ajax']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $host = trim($_POST['db_host'] ?? 'localhost');
    $dbName = trim($_POST['db_name'] ?? '');
    $user = trim($_POST['db_user'] ?? '');
    $pass = $_POST['db_pass'] ?? '';
    try {
        $pdo = new PDO("mysql:host={$host}", $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        echo json_encode(['success' => true, 'message' => 'Connection successful! Database "' . $dbName . '" is ready.']);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'error' => 'Connection failed. Check host, database name, username and password.']);
    }
    exit;
}

// Form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_GET['ajax'])) {
    $host = trim($_POST['db_host'] ?? 'localhost');
    $dbName = trim($_POST['db_name'] ?? '');
    $user = trim($_POST['db_user'] ?? '');
    $pass = $_POST['db_pass'] ?? '';
    $prefix = trim($_POST['table_prefix'] ?? '');
    
    if (empty($dbName) || empty($user)) {
        $error = 'Please fill in all required fields.';
    } else {
        try {
            $pdo = new PDO("mysql:host={$host}", $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $_SESSION['db_host'] = $host;
            $_SESSION['db_name'] = $dbName;
            $_SESSION['db_user'] = $user;
            $_SESSION['db_pass'] = $pass;
            $_SESSION['table_prefix'] = $prefix;
            header('Location: step5.php');
            exit;
        } catch (PDOException $e) {
            $error = 'Database connection failed. Check host, database name, username and password.';
        }
    }
}

$defaults = ['db_host' => 'localhost', 'db_name' => '', 'db_user' => '', 'db_pass' => '', 'table_prefix' => ''];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CIX Orbit Academy - Database Setup</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="assets/css/install.css">
</head>
<body>
<div class="installer-wrapper">
    <div class="installer-card">
        <div class="installer-header">
            <h1><i class="fas fa-orbit"></i> CIX <span>Orbit</span> Academy</h1>
            <p>Complete LMS &amp; Student Management System</p>
        </div>
        <div class="step-indicator">
            <?php for ($i = 1; $i <= 8; $i++): ?>
            <div class="step-dot <?= $i === $step ? 'active' : ($i < $step ? 'completed' : '') ?>">
                <?= $i < $step ? '<i class="fas fa-check"></i>' : $i ?>
                <span class="step-label"><?= $stepNames[$i-1] ?></span>
            </div>
            <?php endfor; ?>
        </div>
        <div class="installer-content">
            <h2><i class="fas fa-database" style="color:var(--cix-orange)"></i> Database Setup</h2>
            <p class="subtitle">Enter your MySQL/MariaDB database credentials.</p>
            <?php if ($error): ?><div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= $error ?></div><?php endif; ?>
            <form method="POST" action="step4.php" id="dbForm" data-validate>
                <div class="form-row">
                    <div class="form-group">
                        <label>Database Host <span class="required">*</span></label>
                        <input type="text" name="db_host" class="form-control" value="<?= e($defaults['db_host']) ?>" required placeholder="localhost">
                    </div>
                    <div class="form-group">
                        <label>Table Prefix</label>
                        <input type="text" name="table_prefix" class="form-control" value="" placeholder="coa_ (optional)">
                    </div>
                </div>
                <div class="form-group">
                    <label>Database Name <span class="required">*</span></label>
                    <input type="text" name="db_name" class="form-control" value="" required placeholder="cix_orbit_academy">
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Database Username <span class="required">*</span></label>
                        <input type="text" name="db_user" class="form-control" value="" required placeholder="root">
                    </div>
                    <div class="form-group">
                        <label>Database Password</label>
                        <input type="password" name="db_pass" class="form-control" value="" placeholder="password">
                    </div>
                </div>
                <div id="dbTestResult"></div>
                <button type="button" id="testDbBtn" class="btn btn-secondary" style="margin-bottom:20px;"><i class="fas fa-plug"></i> Test Connection</button>
                <div class="btn-group">
                    <a href="step3.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
                    <button type="submit" class="btn btn-primary">Save &amp; Continue <i class="fas fa-arrow-right"></i></button>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="assets/js/install.js"></script>
</body>
</html>
