<?php
/**
 * EduTrack School Setup Wizard
 * Multi-step automated school onboarding.
 * Step 1: Auth  → Step 2: School Info  → Step 3: DB Config
 * → Step 4: DB Create  → Step 5: Admin User  → Step 6: Done
 */
require_once __DIR__ . '/config.php';
if (session_status() === PHP_SESSION_NONE) session_start();

$step  = max(1, min(5, (int)($_GET['step'] ?? ($_SESSION['setup_step'] ?? 1))));
$error = '';
$info  = [];

// ── Step 1: Authenticate ──────────────────────────────────────────────
if ($step === 1 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_POST['secret'] === SETUP_SECRET) {
        session_regenerate_id(true);
        $_SESSION['setup_auth'] = true;
        $_SESSION['setup_step'] = 2;
        header('Location: ?step=2'); exit;
    }
    $error = 'Invalid setup secret.';
}

if ($step > 1 && empty($_SESSION['setup_auth'])) {
    header('Location: ?step=1'); exit;
}

// ── Step 2: School Info ───────────────────────────────────────────────
if ($step === 2 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $d = [
        'school_name'  => trim($_POST['school_name'] ?? ''),
        'school_code'  => strtoupper(preg_replace('/[^A-Z0-9]/', '', strtoupper(trim($_POST['school_code'] ?? '')))),
        'contact_name' => trim($_POST['contact_name'] ?? ''),
        'contact_phone'=> trim($_POST['contact_phone'] ?? ''),
        'contact_email'=> trim($_POST['contact_email'] ?? ''),
        'plan'         => $_POST['plan'] ?? 'starter',
        'admin_user'   => trim($_POST['admin_user'] ?? 'admin'),
        'admin_pass'   => $_POST['admin_pass'] ?? '',
        'db_host'      => trim($_POST['db_host'] ?? 'localhost') ?: 'localhost',
        'db_name'      => preg_replace('/[^A-Za-z0-9_]/', '', trim($_POST['db_name'] ?? '')),
        'db_user'      => trim($_POST['db_user'] ?? ''),
        'db_pass'      => $_POST['db_pass'] ?? '',
        'site_url'     => rtrim(trim($_POST['site_url'] ?? ''), '/'),
    ];
    if (!$d['school_name'] || !$d['school_code'] || !$d['db_name'] || !$d['admin_pass']) {
        $error = 'All required fields must be filled.';
    } else {
        $_SESSION['setup_data'] = $d;
        $_SESSION['setup_step'] = 3;
        header('Location: ?step=3'); exit;
    }
}

// ── Step 3: Run Setup ─────────────────────────────────────────────────
if ($step === 3 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $d   = $_SESSION['setup_data'] ?? [];
    if (empty($d['db_name']) || empty($d['admin_pass'])) {
        // Session expired or tampered — send back to step 2
        $_SESSION['setup_step'] = 2;
        header('Location: ?step=2'); exit;
    }
    $log = [];
    $ok  = true;

    // a) Create database (or verify it already exists — e.g. pre-created via cPanel)
    $dbHost = $d['db_host'];
    try {
        $tmp = new mysqli($dbHost, $d['db_user'], $d['db_pass']);
        if ($tmp->connect_error) throw new Exception('DB connect failed: ' . $tmp->connect_error);
        $tmp->query("CREATE DATABASE IF NOT EXISTS `{$d['db_name']}` DEFAULT CHARACTER SET utf8mb4");
        $tmp->close();
        $log[] = ['ok', 'Database ready: ' . $d['db_name']];
    } catch (Exception $e) {
        // On shared hosting (Namecheap/cPanel) the DB is pre-created and the user
        // lacks CREATE DATABASE privilege — try connecting directly to verify it exists.
        try {
            mysqli_report(MYSQLI_REPORT_OFF);
            $testConn = new mysqli($dbHost, $d['db_user'], $d['db_pass'], $d['db_name']);
            mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
            if (!$testConn->connect_error) {
                $testConn->close();
                $log[] = ['warn', 'Could not CREATE DATABASE (no privilege) — using existing database: ' . $d['db_name']];
                // Not fatal — continue with import
            } else {
                $log[] = ['err', 'DB credentials rejected: ' . $testConn->connect_error];
                $ok = false;
            }
        } catch (Exception $inner) {
            mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
            $log[] = ['err', 'DB credentials rejected: ' . $inner->getMessage()];
            $ok = false;
        }
    }

    // b) Import schema — run all SQL files in order
    if ($ok) {
        $base = SETUP_TEMPLATE_DIR . '/';
        $sql_files = [];

        // 1. Core schema (must come first)
        if (file_exists($base . 'database.sql'))
            $sql_files[] = $base . 'database.sql';

        // 2. All addon tables, online payments, timetable, exams, AI, etc.
        if (file_exists($base . 'database_updates.sql'))
            $sql_files[] = $base . 'database_updates.sql';

        // 3. Terminal reports schema (grade_boundaries, report_details, etc.)
        if (file_exists($base . 'modules/reports/database_setup.sql'))
            $sql_files[] = $base . 'modules/reports/database_setup.sql';

        // 4. All add-on migrations (finance, calendar, whatsapp, activities,
        //    health, payroll, biometric, exams, timetable, SBA). Idempotent.
        foreach (glob($base . 'database/migrations/*.sql') ?: [] as $mig) {
            $sql_files[] = $mig;
        }

        if (empty($sql_files)) {
            $log[] = ['warn', 'No SQL schema files found — skipping import.'];
        } else {
            // Disable strict exception mode for imports so ALTER TABLE / duplicate-key
            // warnings in database_updates.sql don't abort the whole wizard.
            $prevReport = mysqli_report(MYSQLI_REPORT_OFF);

            foreach ($sql_files as $sql_file) {
                $fname = basename($sql_file);
                $conn2 = new mysqli($dbHost, $d['db_user'], $d['db_pass'], $d['db_name']);
                if ($conn2->connect_error) {
                    $log[] = ['err', "Cannot connect for {$fname}: " . $conn2->connect_error];
                    continue;
                }
                $sql = file_get_contents($sql_file);
                $warnings = [];
                try {
                    if ($conn2->multi_query($sql)) {
                        do {
                            if ($res = $conn2->store_result()) $res->free();
                            if ($conn2->errno) {
                                $warnings[] = $conn2->error;
                            }
                        } while ($conn2->more_results() && $conn2->next_result());
                    } else {
                        $warnings[] = $conn2->error;
                    }
                } catch (Exception $e) {
                    // Swallow non-fatal SQL errors (duplicate keys, existing columns, etc.)
                    $warnings[] = $e->getMessage();
                }
                if (empty($warnings)) {
                    $log[] = ['ok', "Imported: {$fname}"];
                } else {
                    // Warnings are expected on fresh installs (ALTER TABLE on new tables, etc.)
                    $log[] = ['ok', "Imported: {$fname} (with " . count($warnings) . " non-fatal notice(s))"];
                }
                $conn2->close();
            }

            // Always restore previous reporting level
            mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        }

        // c) Verify critical tables exist
        $critical_tables = [
            'users','students','payments','fee_structures','staff','class_subjects',
            'grade_boundaries','exam_papers','timetable_periods',
            'parent_accounts','ai_tasks','online_payments',
            'attendance','announcements','internal_messages','classes',
            // add-on module tables (self-heal in code, verified here)
            'expense_requests','event_accounts','student_health','infirmary_visits',
            'student_leadership','student_activities','payroll_staff_pay','payroll_runs',
            'biometric_devices','biometric_enrollments','whatsapp_log',
            'exam_format_profiles','exam_format_profile_versions',
        ];
        $verify_conn = new mysqli($dbHost, $d['db_user'], $d['db_pass'], $d['db_name']);
        if (!$verify_conn->connect_error) {
            foreach ($critical_tables as $table) {
                $res = $verify_conn->query("SHOW TABLES LIKE '{$table}'");
                if (!$res || $res->num_rows === 0) {
                    $log[] = ['warn', "Table [{$table}] not found — check SQL imports"];
                }
            }
            $verify_conn->close();
        }
    }

    // c) Create admin user in the new school DB
    if ($ok) {
        try {
            $conn     = new mysqli($dbHost, $d['db_user'], $d['db_pass'], $d['db_name']);
            $hash     = password_hash($d['admin_pass'], PASSWORD_DEFAULT);
            $fullName = $d['school_name'] . ' Admin';
            $adminEmail = $d['contact_email'] ?? '';
            $stmt     = $conn->prepare(
                "INSERT IGNORE INTO users (username, password, full_name, email, role, is_active, created_at)
                 VALUES (?, ?, ?, ?, 'admin', 1, NOW())"
            );
            if (!$stmt) {
                throw new Exception('Could not prepare admin INSERT — users table may not exist: ' . $conn->error);
            }
            $stmt->bind_param('ssss', $d['admin_user'], $hash, $fullName, $adminEmail);
            $stmt->execute();
            $created = $stmt->affected_rows > 0;
            $stmt->close();
            $conn->close();
            $log[] = $created
                ? ['ok',   'Admin user created: '  . $d['admin_user']]
                : ['warn', 'Admin user already exists: ' . $d['admin_user']];
        } catch (Exception $e) {
            $log[] = ['warn', 'Could not create admin user: ' . $e->getMessage()];
        }
    }

    // d) Seed school-specific settings from the setup form
    if ($ok) {
        try {
            $sConn = new mysqli($dbHost, $d['db_user'], $d['db_pass'], $d['db_name']);
            $seedSettings = [
                'school_name'  => $d['school_name'],
                'school_email' => $d['contact_email'],
                'school_phone' => $d['contact_phone'],
                'from_name'    => $d['school_name'],
                'from_email'   => $d['contact_email'],
            ];
            $sStmt = $sConn->prepare(
                "INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)
                 ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)"
            );
            foreach ($seedSettings as $sKey => $sVal) {
                $sStmt->bind_param('ss', $sKey, $sVal);
                $sStmt->execute();
            }
            $sStmt->close();
            $sConn->close();
            $log[] = ['ok', 'School settings initialized: ' . $d['school_name']];
        } catch (Exception $e) {
            $log[] = ['warn', 'Could not seed school settings: ' . $e->getMessage()];
        }
    }

    // e) Generate .env snippet for the school
    // The installer does not write files to disk — display the snippet for manual placement.
    $config_content = "; EduTrack .env — generated by Setup Wizard\n"
        . "; Place this file in the EduTrack project root as .env\n\n"
        . "DB_HOST=" . $dbHost              . "\n"
        . "DB_USER=" . $d['db_user']        . "\n"
        . "DB_PASS=" . $d['db_pass']        . "\n"
        . "DB_NAME=" . $d['db_name']        . "\n"
        . "BASE_URL=" . rtrim($d['site_url'], '/') . "/\n"
        . "SCHOOL_CODE=" . $d['school_code'] . "\n"
        . "LICENSE_SERVER_URL=" . SETUP_LS_URL . "\n"
        . "\n; Error tracking — same Sentry project as all EduTrack installs\n"
        . "SENTRY_DSN=" . ($_ENV['SENTRY_DSN'] ?? '') . "\n"
        . "APP_ENV=production\n"
        . "APP_VERSION=" . ($_ENV['APP_VERSION'] ?? '1.0.0') . "\n"
        . "\n; Fill in remaining keys from .env.example\n";
    $log[] = ['ok', '.env snippet generated (see below).'];

    // e) Register school with license server
    $ls_data = [
        'school_code'  => $d['school_code'],
        'plan'         => $d['plan'],
        'student_limit'=> ['starter'=>200,'growth'=>500,'premium'=>0][$d['plan']] ?? 200,
        'addons'       => [],
        'is_active'    => 1,
        'valid_until'  => date('Y-m-d', strtotime('+30 days')),
    ];
    if (function_exists('curl_init')) {
        $ch = curl_init(SETUP_LS_URL);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($ls_data),
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'X-LS-Api-Key: ' . ($_ENV['LS_API_KEY'] ?? ''),
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 5,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        $resp     = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr  = curl_error($ch);
        curl_close($ch);
        $decoded = json_decode($resp ?: '{}', true);
        if ($httpCode === 200 && !empty($decoded['success'])) {
            $log[] = ['ok', 'School registered in license server.'];
        } else {
            $detail = $decoded['error'] ?? $resp ?: 'no response';
            if ($curlErr) $detail .= " — cURL: {$curlErr}";
            $log[] = ['warn', "License server: {$detail} (HTTP {$httpCode})"];
        }
    } else {
        $log[] = ['warn', 'cURL not available — register school manually in license server.'];
    }

    $_SESSION['setup_log']    = $log;
    $_SESSION['setup_config'] = $config_content;
    $_SESSION['setup_data']   = $d;
    $_SESSION['setup_step']   = 4;
    header('Location: ?step=4'); exit;
}

$page_titles = [1=>'Authentication',2=>'School Information',3=>'Confirm & Install',4=>'Payment Settlement',5=>'Setup Complete'];
$current_title = $page_titles[$step] ?? 'Setup';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EduTrack Setup — <?= $current_title ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
  body{background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);min-height:100vh;font-family:'Segoe UI',sans-serif;padding:2rem 1rem}
  .setup-card{max-width:680px;margin:0 auto;background:rgba(255,255,255,.95);border-radius:20px;overflow:hidden;box-shadow:0 30px 80px rgba(0,0,0,.4)}
  .setup-header{background:linear-gradient(135deg,#6f42c1,#0d6efd);padding:2rem;color:#fff}
  .setup-header h3{font-weight:800;margin:0}
  .setup-header .subtitle{opacity:.8;font-size:.9rem}
  .step-bar{display:flex;gap:.5rem;margin-top:1rem}
  .step-dot{flex:1;height:4px;border-radius:2px;background:rgba(255,255,255,.3)}
  .step-dot.done{background:#fff}
  .setup-body{padding:2rem}
  .form-label{font-size:.82rem;font-weight:600;color:#495057}
  .form-control,.form-select{border-radius:10px;border:1.5px solid #dee2e6;font-size:.875rem}
  .form-control:focus,.form-select:focus{border-color:#6f42c1;box-shadow:0 0 0 3px rgba(111,66,193,.12)}
  .btn-setup{background:linear-gradient(135deg,#6f42c1,#0d6efd);border:none;border-radius:10px;padding:.75rem 2rem;font-weight:600;color:#fff}
  .btn-setup:hover{opacity:.9;color:#fff}
  .log-item{padding:.35rem .6rem;border-radius:6px;font-size:.82rem;margin-bottom:.25rem;display:flex;gap:.5rem;align-items:center}
  .log-item.ok{background:#d1fae5;color:#065f46}
  .log-item.err{background:#fee2e2;color:#991b1b}
  .log-item.warn{background:#fef3c7;color:#92400e}
  .config-box{background:#1e1e2e;color:#a6e3a1;padding:1rem;border-radius:10px;font-size:.8rem;font-family:monospace;white-space:pre-wrap;max-height:200px;overflow-y:auto}
</style>
</head>
<body>
<div class="setup-card">
  <div class="setup-header">
    <div class="d-flex align-items-center gap-2 mb-2">
      <div style="width:40px;height:40px;background:rgba(255,255,255,.15);border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:1.2rem">
        <i class="fas fa-graduation-cap"></i>
      </div>
      <div>
        <h3>EduTrack Setup</h3>
        <div class="subtitle"><?= $current_title ?></div>
      </div>
    </div>
    <div class="step-bar">
      <?php for ($i=1;$i<=5;$i++): ?>
      <div class="step-dot <?= $step>=$i?'done':'' ?>"></div>
      <?php endfor; ?>
    </div>
  </div>

  <div class="setup-body">

    <?php if ($error): ?>
    <div class="alert alert-danger rounded-3 py-2 small mb-3">
      <i class="fas fa-exclamation-circle me-2"></i><?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>

    <?php if ($step === 1): ?>
    <!-- Auth -->
    <h5 class="fw-bold mb-1">Enter Setup Secret</h5>
    <p class="text-muted small mb-4">This wizard is password-protected. Enter the secret defined in <code>setup/config.php</code>.</p>
    <form method="POST">
      <div class="mb-4">
        <label class="form-label">Setup Secret</label>
        <input type="password" class="form-control" name="secret" required autofocus placeholder="Enter setup secret">
      </div>
      <button type="submit" class="btn btn-setup w-100">Continue <i class="fas fa-arrow-right ms-2"></i></button>
    </form>

    <?php elseif ($step === 2): ?>
    <!-- School Info -->
    <h5 class="fw-bold mb-1">School Information</h5>
    <p class="text-muted small mb-4">Enter the details for the new school installation.</p>
    <form method="POST">
      <div class="row g-3">
        <div class="col-8">
          <label class="form-label">School Name <span class="text-danger">*</span></label>
          <input type="text" class="form-control" name="school_name" required placeholder="Westgate Academy">
        </div>
        <div class="col-4">
          <label class="form-label">School Code <span class="text-danger">*</span></label>
          <input type="text" class="form-control font-monospace text-uppercase" name="school_code" required
                 maxlength="10" placeholder="WGA001">
        </div>
        <div class="col-6">
          <label class="form-label">Contact Name</label>
          <input type="text" class="form-control" name="contact_name" placeholder="Headmaster name">
        </div>
        <div class="col-6">
          <label class="form-label">Contact Phone</label>
          <input type="text" class="form-control" name="contact_phone" placeholder="024XXXXXXX">
        </div>
        <div class="col-6">
          <label class="form-label">Contact Email</label>
          <input type="email" class="form-control" name="contact_email" placeholder="school@email.com">
        </div>
        <div class="col-6">
          <label class="form-label">Plan</label>
          <select class="form-select" name="plan">
            <option value="starter">Starter (GHS 150/mo)</option>
            <option value="growth">Growth (GHS 250/mo)</option>
            <option value="premium">Premium (GHS 400/mo)</option>
          </select>
        </div>
        <div class="col-12"><hr class="my-1"><p class="small fw-semibold text-muted mb-2"><i class="fas fa-database me-1"></i>Database</p></div>
        <div class="col-12">
          <div class="alert alert-info py-2 small mb-2">
            <i class="fas fa-info-circle me-1"></i>
            <strong>Namecheap / shared hosting:</strong> create the database &amp; user in cPanel first, then enter those credentials here. The wizard will connect to the existing database automatically.
          </div>
        </div>
        <div class="col-3">
          <label class="form-label">DB Host <span class="text-danger">*</span></label>
          <input type="text" class="form-control font-monospace" name="db_host" value="localhost" required placeholder="localhost">
        </div>
        <div class="col-3">
          <label class="form-label">DB Name <span class="text-danger">*</span></label>
          <input type="text" class="form-control font-monospace" name="db_name" required placeholder="edutrack_wga001">
        </div>
        <div class="col-3">
          <label class="form-label">DB User <span class="text-danger">*</span></label>
          <input type="text" class="form-control" name="db_user" required placeholder="db_username">
        </div>
        <div class="col-3">
          <label class="form-label">DB Password</label>
          <input type="password" class="form-control" name="db_pass" placeholder="(blank for local root)">
        </div>
        <div class="col-12"><hr class="my-1"><p class="small fw-semibold text-muted mb-2"><i class="fas fa-user-shield me-1"></i>Admin Account</p></div>
        <div class="col-6">
          <label class="form-label">Admin Username</label>
          <input type="text" class="form-control" name="admin_user" value="admin">
        </div>
        <div class="col-6">
          <label class="form-label">Admin Password <span class="text-danger">*</span></label>
          <input type="password" class="form-control" name="admin_pass" required minlength="6">
        </div>
        <div class="col-12">
          <label class="form-label">Site URL</label>
          <input type="url" class="form-control" name="site_url" placeholder="https://school.edutrack.app">
        </div>
      </div>
      <div class="d-flex gap-2 mt-4">
        <a href="?step=1" class="btn btn-outline-secondary rounded-pill px-4">Back</a>
        <button type="submit" class="btn btn-setup flex-fill">Review & Install <i class="fas fa-arrow-right ms-2"></i></button>
      </div>
    </form>

    <?php elseif ($step === 3): ?>
    <!-- Confirm -->
    <?php $d = $_SESSION['setup_data'] ?? []; ?>
    <h5 class="fw-bold mb-1">Review & Confirm</h5>
    <p class="text-muted small mb-3">Review the details below then click Install to proceed.</p>
    <div class="row g-2 mb-4">
      <?php foreach ([
        'School Name'=>$d['school_name'],'Code'=>$d['school_code'],'Plan'=>ucfirst($d['plan']),
        'DB Host'=>$d['db_host'],'DB Name'=>$d['db_name'],'DB User'=>$d['db_user'],
        'Admin User'=>$d['admin_user'],'Site URL'=>$d['site_url']?:'(not set)',
      ] as $lbl=>$val): ?>
      <div class="col-6">
        <div class="small text-muted"><?= $lbl ?></div>
        <div class="fw-semibold"><?= htmlspecialchars($val) ?></div>
      </div>
      <?php endforeach; ?>
    </div>
    <form method="POST" onsubmit="document.getElementById('installBtn').disabled=true;document.getElementById('installBtn').innerHTML='<i class=\'fas fa-spinner fa-spin me-2\'></i>Installing…'">
      <div class="d-flex gap-2">
        <a href="?step=2" class="btn btn-outline-secondary rounded-pill px-4">Back</a>
        <button type="submit" class="btn btn-setup flex-fill" id="installBtn">
          <i class="fas fa-rocket me-2"></i>Run Installation
        </button>
      </div>
    </form>

    <?php elseif ($step === 4): ?>
    <!-- Payment Settlement (Optional) -->
    <h5 class="fw-bold mb-1">Set Up School Payment Settlement <span class="badge bg-secondary ms-2" style="font-size:.7rem">Optional</span></h5>
    <p class="text-muted small mb-4">
        Configure your school's bank account so that online fee payments go directly to your school automatically.
        You can also do this later in <strong>Settings → Online Payment Settlement</strong>.
    </p>

    <div id="settlement-step-body">
        <div class="mb-3">
            <label class="form-label fw-semibold">Paystack Secret Key <span class="text-danger">*</span></label>
            <input type="password" class="form-control" id="setup_paystack_key" placeholder="sk_live_… or sk_test_…" style="border-radius:10px;border:1.5px solid #dee2e6;font-size:.875rem">
            <div class="form-text">Get your key from <strong>paystack.com → Settings → API Keys</strong>. It will be saved to your <code>.env</code> file automatically.</div>
        </div>
        <div class="mb-3">
            <label class="form-label fw-semibold">Bank Name <span class="text-danger">*</span></label>
            <select class="form-select" id="setup_bank_select" onchange="setupLoadBankCode(this)" style="border-radius:10px;border:1.5px solid #dee2e6;font-size:.875rem">
                <option value="">Enter Paystack key above, then click Load Banks</option>
            </select>
            <input type="hidden" id="setup_bank_code" value="">
            <button type="button" class="btn btn-outline-secondary btn-sm mt-1" onclick="loadGhanaBanks()">
                <i class="fas fa-sync me-1"></i>Load Banks
            </button>
        </div>
        <div class="mb-3">
            <label class="form-label fw-semibold">Account Number <span class="text-danger">*</span></label>
            <div class="input-group">
                <input type="text" class="form-control" id="setup_account_number" placeholder="Enter account number" maxlength="20" style="border-radius:10px 0 0 10px;border:1.5px solid #dee2e6">
                <button class="btn btn-outline-secondary" type="button" id="setup_verify_btn" onclick="setupVerifyAccount()">Verify</button>
            </div>
            <div id="setup_verify_result" class="mt-1 small"></div>
        </div>
        <div class="mb-3">
            <label class="form-label fw-semibold">Account Name <span class="text-danger">*</span></label>
            <input type="text" class="form-control" id="setup_account_name" placeholder="Auto-filled after verification — or type manually" style="border-radius:10px;border:1.5px solid #dee2e6">
            <div class="form-text" id="setup_name_hint" style="display:none">
                <i class="fas fa-info-circle me-1 text-warning"></i>
                Verification failed. You can type your account name manually and proceed.
            </div>
        </div>
        <div id="setup_result" class="mb-3"></div>

        <div class="d-flex gap-2">
            <button type="button" class="btn btn-setup flex-fill" id="setup_save_btn" onclick="setupSaveSubaccount()">
                <i class="fas fa-university me-2"></i>Set Up Now
            </button>
        </div>
    </div>

    <div id="settlement-step-success" style="display:none">
        <div class="alert alert-success rounded-3 py-3 mb-3">
            <i class="fas fa-check-circle me-2 fa-lg"></i>
            <strong>Settlement account configured!</strong><br>
            <small id="setup_subaccount_code_display"></small>
        </div>
        <a href="?step=5" class="btn btn-setup w-100">
            Continue to Final Step <i class="fas fa-arrow-right ms-2"></i>
        </a>
    </div>

    <div class="mt-3 pt-2 border-top">
        <a href="?step=5" class="btn btn-outline-secondary w-100 rounded-pill">
            <i class="fas fa-forward me-1"></i>Skip for Now — Configure Later in Settings
        </a>
        <div class="mt-2 small text-muted text-center">
            Without this, online payments go to the Oric Network main account and must be transferred manually.
        </div>
    </div>

    <script>
    (function () {
        var ajaxUrl = '../ajax/paystack_subaccount.php';

        function setupResult(html) {
            document.getElementById('setup_result').innerHTML = html;
        }

        function getPaystackKey() {
            return document.getElementById('setup_paystack_key').value.trim();
        }

        window.loadGhanaBanks = function () {
            var key = getPaystackKey();
            if (!key) {
                document.getElementById('setup_bank_select').innerHTML =
                    '<option value="">Enter your Paystack secret key above first</option>';
                return;
            }
            var select = document.getElementById('setup_bank_select');
            select.innerHTML = '<option value="">Loading…</option>';
            fetch(ajaxUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=get_banks&paystack_key=' + encodeURIComponent(key)
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data.success && data.banks) {
                    select.innerHTML = '<option value="">Select bank…</option>';
                    data.banks.forEach(function (bank) {
                        var opt = document.createElement('option');
                        opt.value = bank.code;
                        opt.textContent = bank.name;
                        opt.dataset.name = bank.name;
                        select.appendChild(opt);
                    });
                } else {
                    select.innerHTML = '<option value="">Could not load banks — check your Paystack key</option>';
                }
            })
            .catch(function () {
                select.innerHTML = '<option value="">Network error loading banks</option>';
            });
        };

        window.setupLoadBankCode = function (select) {
            document.getElementById('setup_bank_code').value = select.value;
            document.getElementById('setup_verify_result').innerHTML = '';
            document.getElementById('setup_account_name').value = '';
            document.getElementById('setup_name_hint').style.display = 'none';
        };

        window.setupVerifyAccount = function () {
            var bankCode = document.getElementById('setup_bank_code').value;
            var accNum   = document.getElementById('setup_account_number').value.trim();
            var key      = getPaystackKey();
            var resultEl = document.getElementById('setup_verify_result');
            var btn      = document.getElementById('setup_verify_btn');
            var hint     = document.getElementById('setup_name_hint');

            if (!key) {
                resultEl.innerHTML = '<span style="color:#f59e0b">Enter your Paystack secret key first.</span>';
                return;
            }
            if (!bankCode || !accNum) {
                resultEl.innerHTML = '<span style="color:#f59e0b">Select a bank and enter an account number first.</span>';
                return;
            }
            btn.disabled = true;
            btn.innerHTML = '…';
            hint.style.display = 'none';

            fetch(ajaxUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'action=verify_account'
                    + '&account_number=' + encodeURIComponent(accNum)
                    + '&bank_code=' + encodeURIComponent(bankCode)
                    + '&paystack_key=' + encodeURIComponent(key)
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                btn.disabled = false;
                btn.innerHTML = 'Verify';
                if (data.success) {
                    document.getElementById('setup_account_name').value = data.account_name;
                    resultEl.innerHTML = '<span style="color:#059669">✓ Confirmed: <strong>' + data.account_name + '</strong></span>';
                    hint.style.display = 'none';
                } else {
                    resultEl.innerHTML = '<span style="color:#dc2626">✗ ' + (data.message || 'Could not verify') + '</span>';
                    hint.style.display = '';
                }
            })
            .catch(function () {
                btn.disabled = false;
                btn.innerHTML = 'Verify';
                resultEl.innerHTML = '<span style="color:#dc2626">Verification failed.</span>';
                hint.style.display = '';
            });
        };

        window.setupSaveSubaccount = function () {
            var bankCode  = document.getElementById('setup_bank_code').value;
            var accNum    = document.getElementById('setup_account_number').value.trim();
            var accName   = document.getElementById('setup_account_name').value.trim();
            var key       = getPaystackKey();
            var select    = document.getElementById('setup_bank_select');
            var bankName  = select.options[select.selectedIndex]?.dataset?.name || '';
            var btn       = document.getElementById('setup_save_btn');

            if (!key) {
                setupResult('<div style="background:#fef3c7;padding:.5rem .75rem;border-radius:8px;font-size:.82rem;color:#92400e">Enter your Paystack secret key before saving.</div>');
                return;
            }
            if (!bankCode || !accNum || !accName) {
                setupResult('<div style="background:#fef3c7;padding:.5rem .75rem;border-radius:8px;font-size:.82rem;color:#92400e">Please select a bank, enter your account number, and provide an account name before saving.</div>');
                return;
            }
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Setting up…';
            setupResult('');

            var params = new URLSearchParams({
                action:            'create_subaccount',
                business_name:     accName,
                settlement_bank:   bankCode,
                account_number:    accNum,
                bank_name:         bankName,
                percentage_charge: '0',
                paystack_key:      key
            });

            fetch(ajaxUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: params
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                btn.disabled = false;
                if (data.success) {
                    document.getElementById('settlement-step-body').style.display = 'none';
                    document.getElementById('setup_subaccount_code_display').textContent =
                        'Subaccount: ' + data.subaccount_code + ' — Bank: ' + bankName;
                    document.getElementById('settlement-step-success').style.display = 'block';
                } else {
                    btn.innerHTML = '<i class="fas fa-university me-2"></i>Set Up Now';
                    setupResult('<div style="background:#fee2e2;padding:.5rem .75rem;border-radius:8px;font-size:.82rem;color:#991b1b">' + (data.message || 'Setup failed') + '</div>');
                }
            })
            .catch(function () {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-university me-2"></i>Set Up Now';
                setupResult('<div style="background:#fee2e2;padding:.5rem .75rem;border-radius:8px;font-size:.82rem;color:#991b1b">Network error. Please try again.</div>');
            });
        };
    })();
    </script>

    <?php elseif ($step === 5): ?>
    <!-- Done -->
    <?php
    $log    = $_SESSION['setup_log']    ?? [];
    $cfg    = $_SESSION['setup_config'] ?? '';
    $d      = $_SESSION['setup_data']   ?? [];
    $has_err = !empty(array_filter($log, fn($l) => $l[0]==='err'));
    // Clear session
    unset($_SESSION['setup_auth'], $_SESSION['setup_step'], $_SESSION['setup_data'],
          $_SESSION['setup_log'], $_SESSION['setup_config']);
    ?>
    <div class="text-center mb-4">
      <div style="width:64px;height:64px;background:<?= $has_err?'#fee2e2':'#d1fae5' ?>;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 1rem;font-size:1.8rem">
        <i class="fas fa-<?= $has_err?'times text-danger':'check text-success' ?>"></i>
      </div>
      <h5 class="fw-bold"><?= $has_err ? 'Setup Completed with Errors' : 'Setup Complete!' ?></h5>
      <p class="text-muted small"><?= $has_err ? 'Review the errors below.' : 'The school has been set up successfully.' ?></p>
    </div>
    <div class="mb-4">
      <?php foreach ($log as [$type, $msg]): ?>
      <div class="log-item <?= $type ?>">
        <i class="fas fa-<?= $type==='ok'?'check-circle':($type==='err'?'times-circle':'exclamation-triangle') ?>"></i>
        <?= htmlspecialchars($msg) ?>
      </div>
      <?php endforeach; ?>
    </div>
    <?php if ($cfg): ?>
    <div class="mb-4">
      <div class="small fw-semibold mb-2"><i class="fas fa-code me-2"></i>Create a <code>.env</code> file in your EduTrack root with:</div>
      <div class="config-box"><?= htmlspecialchars($cfg) ?></div>
    </div>
    <?php endif; ?>
    <div class="d-grid gap-2">
      <a href="../license-server/schools.php" class="btn btn-setup">
        <i class="fas fa-school me-2"></i>View in License Server
      </a>
      <a href="?step=1" class="btn btn-outline-secondary rounded-pill">Setup Another School</a>
    </div>
    <?php endif; ?>

  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
