<?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.'); }
if (empty($_SESSION['db_host'])) { header('Location: step4.php'); exit; }

$step = 8;
$stepNames = ['Welcome', 'Requirements', 'Permissions', 'Database', 'Import', 'Academy', 'Banking', 'Admin'];
$error = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $firstName = trim($_POST['admin_first_name'] ?? '');
    $lastName = trim($_POST['admin_last_name'] ?? '');
    $email = trim($_POST['admin_email'] ?? '');
    $username = trim($_POST['admin_username'] ?? '');
    $password = $_POST['admin_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    if (empty($firstName) || empty($lastName) || empty($email) || empty($username) || empty($password)) {
        $error = 'Please fill in all fields.';
    } elseif (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters.';
    } elseif ($password !== $confirmPassword) {
        $error = 'Passwords do not match.';
    } else {
        try {
            $pdo = new PDO(
                'mysql:host=' . $_SESSION['db_host'] . ';dbname=' . $_SESSION['db_name'] . ';charset=utf8mb4',
                $_SESSION['db_user'],
                $_SESSION['db_pass'],
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            
            // Create admin user
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (role_id, first_name, last_name, email, password_hash, is_active, email_verified_at) VALUES (1, ?, ?, ?, ?, 1, NOW())");
            $stmt->execute([$firstName, $lastName, $email, $hash]);
            $adminId = $pdo->lastInsertId();
            
            // Save academy settings
            $settings = [
                ['academy_name', $_SESSION['academy_name'] ?? 'CIX Orbit Academy'],
                ['company_name', $_SESSION['company_name'] ?? 'CIX Connect'],
                ['academy_url', $_SESSION['academy_url'] ?? ''],
                ['academic_email', $_SESSION['academic_email'] ?? 'academic@cixconnect.co.za'],
                ['office_phone', $_SESSION['office_phone'] ?? '012 004 0207'],
                ['whatsapp_number', $_SESSION['whatsapp_number'] ?? '083 759 8075'],
                ['slogan', $_SESSION['slogan'] ?? 'Learn. Build. Automate. Grow.'],
                ['timezone', $_SESSION['timezone'] ?? 'Africa/Johannesburg'],
                ['default_theme', $_SESSION['default_theme'] ?? 'orbit-dark'],
                ['admin_default_theme', $_SESSION['default_theme'] ?? 'orbit-dark'],
                ['teacher_default_theme', 'teacher-blue'],
                ['student_default_theme', 'student-light'],
                ['public_default_theme', $_SESSION['default_theme'] ?? 'orbit-dark'],
                ['payment_instruction', 'Use your student number as payment reference. Email proof of payment to academic@cixconnect.co.za or WhatsApp proof to 083 759 8075.'],
            ];
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
            foreach ($settings as $s) { $stmt->execute($s); }
            
            $pdo->exec("DELETE FROM banking_details");
            $bankStmt = $pdo->prepare("INSERT INTO banking_details (bank_name, account_name, account_number, branch_code, instructions, is_active, sort_order) VALUES (?, ?, ?, ?, ?, 1, ?)");
            $instruction = 'Use your student number as payment reference. Email proof of payment to academic@cixconnect.co.za or WhatsApp proof to 083 759 8075.';
            $bankStmt->execute(['Standard Bank', 'CIX CONNECT', '10200349927', '051001', $instruction, 1]);
            $bankStmt->execute(['Capitec Business', 'CIX CONNECT', '1051396964', '450105', $instruction, 2]);
            $bankStmt->execute(['ABSA', 'CIX CONNECT', '4123963036', '632005', $instruction, 3]);
            
            // Generate config.php
            $configContent = "<?php\n";
            $configContent .= "define('DB_HOST', " . var_export(addslashes($_SESSION['db_host']), true) . ");\n";
            $configContent .= "define('DB_NAME', " . var_export(addslashes($_SESSION['db_name']), true) . ");\n";
            $configContent .= "define('DB_USER', " . var_export(addslashes($_SESSION['db_user']), true) . ");\n";
            $configContent .= "define('DB_PASS', " . var_export(addslashes($_SESSION['db_pass']), true) . ");\n";
            $configContent .= "define('APP_URL', " . var_export(rtrim($_SESSION['academy_url'] ?? 'http://localhost', '/'), true) . ");\n";
            $configContent .= "define('APP_NAME', " . var_export($_SESSION['academy_name'] ?? 'CIX Orbit Academy', true) . ");\n";
            $configContent .= "define('APP_KEY', " . var_export(bin2hex(random_bytes(32)), true) . ");\n";
            $configContent .= "define('INSTALLED_AT', " . var_export(date('Y-m-d H:i:s'), true) . ");\n";
            $configContent .= "?>";
            file_put_contents($basePath . '/config.php', $configContent);
            
            // Lock installer
            file_put_contents($basePath . '/install/install.lock', '<?php die("Installer is locked. Remove this file to reinstall."); ?>');
            
            // Clear session
            session_destroy();
            
            $success = true;
            
        } catch (PDOException $e) {
            $error = 'Installation failed. Check database permissions and seeded schema, then try again.';
        }
    }
}
?>
<!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 - <?= $success ? 'Installation Complete' : 'Create Admin' ?></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">
            <?php if ($success): ?>
                <div style="text-align:center;">
                    <div class="success-icon"><i class="fas fa-check"></i></div>
                    <h2 style="margin-bottom:10px;">Installation Complete!</h2>
                    <p style="color:var(--cix-muted);">CIX Orbit Academy has been successfully installed.</p>
                    <div class="success-details">
                        <p><strong>Admin Email:</strong> <?= e($email ?? '') ?></p>
                        <p><strong>Login URL:</strong> <a href="../login" style="color:var(--cix-orange)"><?= ($basePath !== '' ? '../login' : 'login') ?></a></p>
                        <p><strong>Admin Panel:</strong> <a href="../admin/dashboard" style="color:var(--cix-orange)">../admin/dashboard</a></p>
                        <p style="margin-top:10px;color:var(--cix-green);"><i class="fas fa-lock"></i> Installer has been locked for security.</p>
                    </div>
                    <div class="btn-group" style="justify-content:center;">
                        <a href="../login" class="btn btn-primary"><i class="fas fa-sign-in-alt"></i> Go to Login</a>
                        <a href="../admin/dashboard" class="btn btn-success"><i class="fas fa-tachometer-alt"></i> Go to Admin Panel</a>
                    </div>
                </div>
            <?php else: ?>
                <h2><i class="fas fa-user-shield" style="color:var(--cix-orange)"></i> Create Super Admin</h2>
                <p class="subtitle">This will be the main administrator account with full access.</p>
                <?php if ($error): ?><div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= $error ?></div><?php endif; ?>
                <form method="POST" action="step8.php" data-validate>
                    <div class="form-row">
                        <div class="form-group"><label>First Name <span class="required">*</span></label><input type="text" name="admin_first_name" class="form-control" required placeholder="Admin"></div>
                        <div class="form-group"><label>Last Name <span class="required">*</span></label><input type="text" name="admin_last_name" class="form-control" required placeholder="User"></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>Email <span class="required">*</span></label><input type="email" name="admin_email" class="form-control" required placeholder="admin@cixconnect.co.za"></div>
                        <div class="form-group"><label>Username <span class="required">*</span></label><input type="text" name="admin_username" class="form-control" required placeholder="admin"></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>Password <span class="required">*</span></label><input type="password" name="admin_password" id="admin_password" class="form-control" required minlength="8" placeholder="Minimum 8 characters"></div>
                        <div class="form-group"><label>Confirm Password <span class="required">*</span></label><input type="password" name="confirm_password" id="confirm_password" class="form-control" required minlength="8" placeholder="Re-enter password"></div>
                    </div>
                    <div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> <strong>Important:</strong> Remember this password. It cannot be recovered.</div>
                    <div class="btn-group">
                        <a href="step7.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
                        <button type="submit" class="btn btn-success"><i class="fas fa-rocket"></i> Complete Installation</button>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>
<script src="assets/js/install.js"></script>
</body>
</html>
