<?php
require_once __DIR__ . '/functions.php';

// Cek apakah sudah terinstall
if (isLocked() && !isset($_GET['force'])) {
    die('<!DOCTYPE html><html><head><title>Already Installed</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head><body class="bg-light">
    <div class="container py-5"><div class="alert alert-warning text-center">
    <h3>🔒 Installer Sudah Dinonaktifkan</h3>
    <p>Sistem sudah terinstall. Untuk keamanan, installer telah dikunci.</p>
    <p>Jika ingin reinstall, hapus file <code>install.lock</code> di root folder.</p>
    <a href="/login.php" class="btn btn-primary">Ke Login</a>
    </div></div></body></html>');
}

// Determine current step
$step = (int)($_GET['step'] ?? ($_POST['step'] ?? 1));
$step = max(1, min(6, $step));

$errors   = [];
$success  = [];
$warnings = [];

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // STEP 2: Database Configuration
    if ($action === 'test_db') {
        $result = testDatabaseConnection(
            $_POST['db_host'],
            $_POST['db_port'] ?? 3306,
            $_POST['db_user'],
            $_POST['db_pass']
        );
        
        if ($result['success']) {
            // Save to session
            $_SESSION['install']['db_host'] = $_POST['db_host'];
            $_SESSION['install']['db_port'] = $_POST['db_port'] ?? 3306;
            $_SESSION['install']['db_user'] = $_POST['db_user'];
            $_SESSION['install']['db_pass'] = $_POST['db_pass'];
            $_SESSION['install']['db_name'] = $_POST['db_name'];
            $_SESSION['install']['db_version'] = $result['version'];
            
            // Try to create database if not exists
            try {
                $pdo = new PDO(
                    "mysql:host={$_POST['db_host']};port={$_POST['db_port']}",
                    $_POST['db_user'],
                    $_POST['db_pass']
                );
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$_POST['db_name']}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
                $success[] = "Database '{$_POST['db_name']}' berhasil dibuat/diverifikasi.";
            } catch (PDOException $e) {
                $warnings[] = "Gagal auto-create database: " . $e->getMessage() . ". Pastikan database sudah ada.";
            }
            
            header('Location: ?step=3');
            exit;
        } else {
            $errors[] = "Koneksi gagal: " . $result['error'];
        }
    }
    
    // STEP 3: App Settings
    if ($action === 'save_settings') {
        $_SESSION['install'] = array_merge($_SESSION['install'] ?? [], [
            'app_name'            => $_POST['app_name'],
            'app_url'             => rtrim($_POST['app_url'], '/'),
            'ipaymu_mode'         => $_POST['ipaymu_mode'],
            'ipaymu_sandbox_va'   => $_POST['ipaymu_sandbox_va'],
            'ipaymu_sandbox_key'  => $_POST['ipaymu_sandbox_key'],
            'ipaymu_prod_va'      => $_POST['ipaymu_prod_va'],
            'ipaymu_prod_key'     => $_POST['ipaymu_prod_key'],
            'ipaymu_notify_url'   => $_POST['ipaymu_notify_url'],
            'ipaymu_return_url'   => $_POST['ipaymu_return_url'],
            'ipaymu_cancel_url'   => $_POST['ipaymu_cancel_url'],
            'wablas_token'        => $_POST['wablas_token'],
            'wablas_url'          => $_POST['wablas_url'],
            'mt_host'             => $_POST['mt_host'],
            'mt_user'             => $_POST['mt_user'],
            'mt_pass'             => $_POST['mt_pass'],
            'mt_port'             => $_POST['mt_port'] ?? 8728,
            'mt_pppoe_service'    => $_POST['mt_pppoe_service'],
        ]);
        header('Location: ?step=4');
        exit;
    }
    
    // STEP 4: Admin Account
    if ($action === 'save_admin') {
        if (empty($_POST['admin_username']) || empty($_POST['admin_password'])) {
            $errors[] = 'Username dan password wajib diisi';
        } elseif (strlen($_POST['admin_password']) < 6) {
            $errors[] = 'Password minimal 6 karakter';
        } elseif ($_POST['admin_password'] !== $_POST['admin_password2']) {
            $errors[] = 'Konfirmasi password tidak cocok';
        } else {
            $_SESSION['install']['admin_username'] = $_POST['admin_username'];
            $_SESSION['install']['admin_password'] = $_POST['admin_password'];
            $_SESSION['install']['admin_name']     = $_POST['admin_name'];
            $_SESSION['install']['admin_email']    = $_POST['admin_email'];
            header('Location: ?step=5');
            exit;
        }
    }
    
    // STEP 5: Execute Installation
    if ($action === 'install') {
        $installData = $_SESSION['install'] ?? [];
        
        if (empty($installData)) {
            $errors[] = 'Data instalasi tidak ditemukan. Mulai dari step 1.';
            $step = 1;
        } else {
            try {
                // 1. Connect to database
                $pdo = new PDO(
                    "mysql:host={$installData['db_host']};port={$installData['db_port']};dbname={$installData['db_name']};charset=utf8mb4",
                    $installData['db_user'],
                    $installData['db_pass'],
                    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                );
                
                // 2. Execute schema
                $schemaResult = executeSchema($pdo, __DIR__ . '/schema.sql');
                if (!$schemaResult['success']) {
                    throw new Exception('Schema execution failed: ' . $schemaResult['error']);
                }
                
                // 3. Create/update admin user
                $adminHash = hashPassword($installData['admin_password']);
                $stmt = $pdo->prepare("INSERT INTO users (username, password, name, email, role, status) 
                                       VALUES (?, ?, ?, ?, 'super_admin', 'active')
                                       ON DUPLICATE KEY UPDATE password=VALUES(password), name=VALUES(name), email=VALUES(email)");
                $stmt->execute([
                    $installData['admin_username'],
                    $adminHash,
                    $installData['admin_name'] ?: 'Administrator',
                    $installData['admin_email']
                ]);
                
                // 4. Update app_name setting
                $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'app_name'")
                    ->execute([$installData['app_name']]);
                
                // 5. Write config files
                $configs = [
                    'database.php' => generateDatabaseConfig($installData),
                    'ipaymu.php'   => generateIpaymuConfig($installData),
                    'wablas.php'   => generateWablasConfig($installData),
                    'mikrotik.php' => generateMikrotikConfig($installData),
                    'app.php'      => generateAppConfig($installData),
                ];
                
                foreach ($configs as $file => $content) {
                    if (!writeConfigFile($file, $content)) {
                        throw new Exception("Gagal menulis file config/$file. Pastikan folder config writable.");
                    }
                }
                
                // 6. Create logs directory
                @mkdir(INSTALL_PATH . '/logs', 0755, true);
                
                // 7. Lock installer
                lockInstaller();
                
                // 8. Clear session
                unset($_SESSION['install']);
                
                $_SESSION['install_success'] = true;
                header('Location: ?step=6');
                exit;
                
            } catch (Exception $e) {
                $errors[] = 'Instalasi gagal: ' . $e->getMessage();
            }
        }
    }
}

// Get current data from session
$data = $_SESSION['install'] ?? [];
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Installer - RT/RW Net Management System</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
<link href="assets/style.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container py-4">
  <div class="text-center mb-4">
    <h2>🌐 RT/RW Net Management System</h2>
    <p class="text-muted">Installer Wizard v1.0</p>
  </div>

  <!-- Progress Bar -->
  <div class="card mb-4">
    <div class="card-body p-3">
      <div class="d-flex justify-content-between mb-2">
        <?php 
        $steps = [
            1 => ['icon'=>'check-circle', 'label'=>'Requirements'],
            2 => ['icon'=>'database', 'label'=>'Database'],
            3 => ['icon'=>'gear', 'label'=>'Settings'],
            4 => ['icon'=>'person-lock', 'label'=>'Admin'],
            5 => ['icon'=>'rocket', 'label'=>'Install'],
            6 => ['icon'=>'check2-all', 'label'=>'Finish'],
        ];
        foreach ($steps as $i => $s): 
            $class = $i < $step ? 'completed' : ($i === $step ? 'active' : '');
        ?>
          <div class="step-indicator <?= $class ?>">
            <i class="bi bi-<?= $s['icon'] ?>"></i>
            <div class="small"><?= $s['label'] ?></div>
          </div>
        <?php endforeach; ?>
      </div>
      <div class="progress" style="height: 5px;">
        <div class="progress-bar" style="width: <?= ($step / 6) * 100 ?>%"></div>
      </div>
    </div>
  </div>

  <!-- Messages -->
  <?php if ($errors): ?>
    <div class="alert alert-danger">
      <strong><i class="bi bi-exclamation-triangle"></i> Error:</strong>
      <ul class="mb-0 mt-2">
      <?php foreach ($errors as $e): ?><li><?= clean($e) ?></li><?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>
  
  <?php if ($success): ?>
    <div class="alert alert-success">
      <strong><i class="bi bi-check-circle"></i> Success:</strong>
      <ul class="mb-0 mt-2">
      <?php foreach ($success as $s): ?><li><?= clean($s) ?></li><?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>
  
  <?php if ($warnings): ?>
    <div class="alert alert-warning">
      <strong><i class="bi bi-exclamation-circle"></i> Warning:</strong>
      <ul class="mb-0 mt-2">
      <?php foreach ($warnings as $w): ?><li><?= clean($w) ?></li><?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>

  <!-- STEP CONTENT -->
  <div class="card">
    <div class="card-body p-4">

    <?php if ($step === 1): ?>
      <!-- ============ STEP 1: REQUIREMENTS ============ -->
      <h4 class="mb-3"><i class="bi bi-check-circle text-primary"></i> Step 1: System Requirements</h4>
      <p class="text-muted">Memeriksa requirement sistem sebelum instalasi.</p>
      
      <?php $requirements = checkRequirements(); ?>
      <table class="table">
        <thead>
          <tr><th>Component</th><th>Required</th><th>Current</th><th>Status</th></tr>
        </thead>
        <tbody>
        <?php foreach ($requirements as $r): ?>
          <tr>
            <td><?= clean($r['name']) ?></td>
            <td><?= clean($r['required']) ?></td>
            <td><code><?= clean($r['current']) ?></code></td>
            <td>
              <?php if ($r['status']): ?>
                <span class="badge bg-success"><i class="bi bi-check"></i> OK</span>
              <?php else: ?>
                <span class="badge bg-<?= $r['critical'] ? 'danger' : 'warning' ?>">
                  <i class="bi bi-x"></i> <?= $r['critical'] ? 'Required' : 'Recommended' ?>
                </span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>

      <?php
      $allCritical = array_reduce($requirements, function($carry, $r) {
          return $carry && $r['status'];
      }, true);
      ?>
      
      <div class="d-flex justify-content-between mt-4">
        <div></div>
        <?php if ($allCritical): ?>
          <a href="?step=2" class="btn btn-primary">Lanjut <i class="bi bi-arrow-right"></i></a>
        <?php else: ?>
          <button class="btn btn-secondary" disabled>Perbaiki requirement di atas dulu</button>
        <?php endif; ?>
      </div>

    <?php elseif ($step === 2): ?>
      <!-- ============ STEP 2: DATABASE ============ -->
      <h4 class="mb-3"><i class="bi bi-database text-primary"></i> Step 2: Database Configuration</h4>
      <p class="text-muted">Masukkan informasi koneksi database MySQL/MariaDB.</p>
      
      <form method="POST">
        <input type="hidden" name="action" value="test_db">
        
        <div class="row">
          <div class="col-md-8 mb-3">
            <label class="form-label">Database Host *</label>
            <input type="text" name="db_host" class="form-control" required 
                   value="<?= clean($data['db_host'] ?? 'localhost') ?>">
          </div>
          <div class="col-md-4 mb-3">
            <label class="form-label">Port</label>
            <input type="number" name="db_port" class="form-control" 
                   value="<?= clean($data['db_port'] ?? 3306) ?>">
          </div>
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Database Username *</label>
            <input type="text" name="db_user" class="form-control" required 
                   value="<?= clean($data['db_user'] ?? 'root') ?>">
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">Database Password</label>
            <input type="password" name="db_pass" class="form-control" 
                   value="<?= clean($data['db_pass'] ?? '') ?>">
          </div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Database Name *</label>
          <input type="text" name="db_name" class="form-control" required 
                 value="<?= clean($data['db_name'] ?? 'rtrw_net') ?>"
                 pattern="[a-zA-Z0-9_]+">
          <small class="text-muted">Database akan dibuat otomatis jika belum ada.</small>
        </div>
        
        <div class="d-flex justify-content-between mt-4">
          <a href="?step=1" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Kembali</a>
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-plug"></i> Test Koneksi & Lanjut
          </button>
        </div>
      </form>

    <?php elseif ($step === 3): ?>
      <!-- ============ STEP 3: SETTINGS ============ -->
      <h4 class="mb-3"><i class="bi bi-gear text-primary"></i> Step 3: Application Settings</h4>
      <p class="text-muted">Konfigurasi aplikasi, payment gateway, WhatsApp, dan MikroTik.</p>
      
      <form method="POST">
        <input type="hidden" name="action" value="save_settings">
        
        <h5 class="mt-3 mb-3 text-primary"><i class="bi bi-building"></i> Informasi Aplikasi</h5>
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Nama Perusahaan *</label>
            <input type="text" name="app_name" class="form-control" required 
                   value="<?= clean($data['app_name'] ?? 'PT Lintas Fiber Nusantara') ?>">
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">URL Aplikasi *</label>
            <input type="url" name="app_url" class="form-control" required 
                   value="<?= clean($data['app_url'] ?? 'https://') ?>"
                   placeholder="https://yourdomain.com">
          </div>
        </div>
        
        <hr>
        <h5 class="mb-3 text-primary"><i class="bi bi-credit-card"></i> iPaymu Payment Gateway</h5>
        <div class="mb-3">
          <label class="form-label">Mode</label>
          <select name="ipaymu_mode" class="form-select">
            <option value="sandbox" <?= ($data['ipaymu_mode'] ?? 'sandbox') === 'sandbox' ? 'selected' : '' ?>>Sandbox (Testing)</option>
            <option value="production" <?= ($data['ipaymu_mode'] ?? '') === 'production' ? 'selected' : '' ?>>Production</option>
          </select>
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Sandbox VA</label>
            <input type="text" name="ipaymu_sandbox_va" class="form-control" 
                   value="<?= clean($data['ipaymu_sandbox_va'] ?? '') ?>">
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">Sandbox API Key</label>
            <input type="text" name="ipaymu_sandbox_key" class="form-control" 
                   value="<?= clean($data['ipaymu_sandbox_key'] ?? '') ?>">
          </div>
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Production VA</label>
            <input type="text" name="ipaymu_prod_va" class="form-control" 
                   value="<?= clean($data['ipaymu_prod_va'] ?? '') ?>">
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">Production API Key</label>
            <input type="text" name="ipaymu_prod_key" class="form-control" 
                   value="<?= clean($data['ipaymu_prod_key'] ?? '') ?>">
          </div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Notify URL (Webhook)</label>
          <input type="url" name="ipaymu_notify_url" class="form-control" 
                 value="<?= clean($data['ipaymu_notify_url'] ?? (($data['app_url'] ?? 'https://yourdomain.com') . '/webhook/ipaymu_callback.php')) ?>">
          <small class="text-muted">Daftarkan URL ini di dashboard iPaymu sebagai Notify URL.</small>
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Return URL</label>
            <input type="url" name="ipaymu_return_url" class="form-control" 
                   value="<?= clean($data['ipaymu_return_url'] ?? (($data['app_url'] ?? 'https://yourdomain.com') . '/public/pay.php?status=success')) ?>">
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">Cancel URL</label>
            <input type="url" name="ipaymu_cancel_url" class="form-control" 
                   value="<?= clean($data['ipaymu_cancel_url'] ?? (($data['app_url'] ?? 'https://yourdomain.com') . '/public/pay.php?status=cancel')) ?>">
          </div>
        </div>
        
        <hr>
        <h5 class="mb-3 text-primary"><i class="bi bi-whatsapp"></i> Wablas (WhatsApp)</h5>
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Wablas Token *</label>
            <input type="text" name="wablas_token" class="form-control" required 
                   value="<?= clean($data['wablas_token'] ?? '') ?>">
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">Wablas Base URL</label>
            <input type="url" name="wablas_url" class="form-control" 
                   value="<?= clean($data['wablas_url'] ?? 'https://tegal.wablas.com/api') ?>">
          </div>
        </div>
        
        <hr>
        <h5 class="mb-3 text-primary"><i class="bi bi-router"></i> MikroTik</h5>
        <div class="row">
          <div class="col-md-4 mb-3">
            <label class="form-label">IP/Host *</label>
            <input type="text" name="mt_host" class="form-control" required 
                   value="<?= clean($data['mt_host'] ?? '192.168.88.1') ?>">
          </div>
          <div class="col-md-4 mb-3">
            <label class="form-label">Username *</label>
            <input type="text" name="mt_user" class="form-control" required 
                   value="<?= clean($data['mt_user'] ?? 'admin') ?>">
          </div>
          <div class="col-md-4 mb-3">
            <label class="form-label">Password</label>
            <input type="password" name="mt_pass" class="form-control" 
                   value="<?= clean($data['mt_pass'] ?? '') ?>">
          </div>
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">API Port</label>
            <input type="number" name="mt_port" class="form-control" 
                   value="<?= clean($data['mt_port'] ?? 8728) ?>">
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">PPPoE Service Name</label>
            <input type="text" name="mt_pppoe_service" class="form-control" 
                   value="<?= clean($data['mt_pppoe_service'] ?? 'pppoe-service') ?>">
          </div>
        </div>
        
        <div class="d-flex justify-content-between mt-4">
          <a href="?step=2" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Kembali</a>
          <button type="submit" class="btn btn-primary">Lanjut <i class="bi bi-arrow-right"></i></button>
        </div>
      </form>

    <?php elseif ($step === 4): ?>
      <!-- ============ STEP 4: ADMIN ACCOUNT ============ -->
      <h4 class="mb-3"><i class="bi bi-person-lock text-primary"></i> Step 4: Admin Account</h4>
      <p class="text-muted">Buat akun Super Administrator untuk akses pertama kali.</p>
      
      <form method="POST">
        <input type="hidden" name="action" value="save_admin">
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Username *</label>
            <input type="text" name="admin_username" class="form-control" required 
                   value="<?= clean($data['admin_username'] ?? 'admin') ?>"
                   pattern="[a-zA-Z0-9_]+" minlength="3">
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">Nama Lengkap</label>
            <input type="text" name="admin_name" class="form-control" 
                   value="<?= clean($data['admin_name'] ?? 'Super Administrator') ?>">
          </div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Email</label>
          <input type="email" name="admin_email" class="form-control" 
                 value="<?= clean($data['admin_email'] ?? '') ?>">
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Password *</label>
            <input type="password" name="admin_password" class="form-control" required minlength="6">
            <small class="text-muted">Minimal 6 karakter</small>
          </div>
          <div class="col-md-6 mb-3">
            <label class="form-label">Konfirmasi Password *</label>
            <input type="password" name="admin_password2" class="form-control" required minlength="6">
          </div>
        </div>
        
        <div class="alert alert-warning">
          <i class="bi bi-shield-exclamation"></i> <strong>PENTING:</strong> Simpan kredensial ini dengan aman! 
          Anda tidak bisa mengubahnya melalui installer setelah instalasi selesai.
        </div>
        
        <div class="d-flex justify-content-between mt-4">
          <a href="?step=3" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Kembali</a>
          <button type="submit" class="btn btn-primary">Lanjut <i class="bi bi-arrow-right"></i></button>
        </div>
      </form>

    <?php elseif ($step === 5): ?>
      <!-- ============ STEP 5: EXECUTE INSTALL ============ -->
      <h4 class="mb-3"><i class="bi bi-rocket-takeoff text-primary"></i> Step 5: Execute Installation</h4>
      <p class="text-muted">Review konfigurasi sebelum eksekusi instalasi.</p>
      
      <div class="alert alert-info">
        <i class="bi bi-info-circle"></i> <strong>Ringkasan Instalasi:</strong>
      </div>
      
      <table class="table table-sm">
        <tr><th width="40%">Database</th><td><?= clean($data['db_name'] ?? '') ?> @ <?= clean($data['db_host'] ?? '') ?>:<?= clean($data['db_port'] ?? 3306) ?></td></tr>
        <tr><th>Aplikasi</th><td><?= clean($data['app_name'] ?? '') ?></td></tr>
        <tr><th>URL</th><td><code><?= clean($data['app_url'] ?? '') ?></code></td></tr>
        <tr><th>iPaymu Mode</th><td><span class="badge bg-<?= ($data['ipaymu_mode'] ?? '') === 'production' ? 'danger' : 'info' ?>"><?= clean($data['ipaymu_mode'] ?? 'sandbox') ?></span></td></tr>
        <tr><th>Wablas URL</th><td><?= clean($data['wablas_url'] ?? '') ?></td></tr>
        <tr><th>MikroTik</th><td><?= clean($data['mt_host'] ?? '') ?>:<?= clean($data['mt_port'] ?? 8728) ?></td></tr>
        <tr><th>Admin Username</th><td><code><?= clean($data['admin_username'] ?? '') ?></code></td></tr>
      </table>
      
      <div class="alert alert-warning">
        <i class="bi bi-exclamation-triangle"></i> <strong>Yang akan dilakukan:</strong>
        <ul class="mb-0 mt-2">
          <li>Membuat/mengupdate tabel database</li>
          <li>Menyimpan data default (paket, settings, admin)</li>
          <li>Menulis file konfigurasi di folder <code>config/</code></li>
          <li>Mengunci installer untuk keamanan</li>
        </ul>
      </div>
      
      <form method="POST" onsubmit="return confirm('Yakin ingin memulai instalasi?')">
        <input type="hidden" name="action" value="install">
        
        <div class="d-flex justify-content-between mt-4">
          <a href="?step=4" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Kembali</a>
          <button type="submit" class="btn btn-success btn-lg">
            <i class="bi bi-rocket-takeoff"></i> Mulai Instalasi
          </button>
        </div>
      </form>

    <?php elseif ($step === 6): ?>
      <!-- ============ STEP 6: SUCCESS ============ -->
      <?php if (!($_SESSION['install_success'] ?? false)): ?>
        <script>window.location.href='?step=1';</script>
      <?php endif; ?>
      
      <div class="text-center py-4">
        <div class="mb-4">
          <i class="bi bi-check-circle-fill text-success" style="font-size: 5rem;"></i>
        </div>
        <h2 class="text-success">🎉 Instalasi Berhasil!</h2>
        <p class="lead">Sistem RT/RW Net Management siap digunakan.</p>
      </div>
      
      <div class="alert alert-danger">
        <i class="bi bi-shield-lock"></i> <strong>KEAMANAN:</strong>
        <ul class="mb-0 mt-2">
          <li>Installer telah dikunci otomatis (file <code>install.lock</code> dibuat)</li>
          <li>Untuk keamanan maksimal, <strong>HAPUS folder <code>/install</code></strong> dari server</li>
          <li>Pastikan folder <code>/config</code> tidak bisa diakses langsung dari browser</li>
          <li>Ganti password admin secara berkala</li>
        </ul>
      </div>
      
      <div class="card bg-light">
        <div class="card-body">
          <h5>📋 Langkah Selanjutnya:</h5>
          <ol class="mb-0">
            <li>Login ke dashboard dengan akun yang baru dibuat</li>
            <li>Setup MikroTik PPPoE Server (lihat dokumentasi)</li>
            <li>Daftarkan webhook URL di dashboard iPaymu</li>
            <li>Setup cron jobs untuk tagihan otomatis</li>
            <li>Tambah data cabang, paket, dan pelanggan</li>
          </ol>
        </div>
      </div>
      
      <div class="card mt-3">
        <div class="card-body">
          <h5>⏰ Setup Cron Jobs:</h5>
          <pre class="bg-dark text-light p-3 rounded mb-0" style="font-size: 0.85rem;"># Edit crontab: crontab -e

# Generate tagihan bulanan (tgl 1 jam 00:00)
0 0 1 * * /usr/bin/php <?= INSTALL_PATH ?>/cron/generate_monthly_bills.php

# Kirim reminder H-3 (setiap hari jam 08:00)
0 8 * * * /usr/bin/php <?= INSTALL_PATH ?>/cron/send_reminder_h3.php

# Suspend pelanggan telat (setiap hari jam 01:00)
0 1 * * * /usr/bin/php <?= INSTALL_PATH ?>/cron/disable_overdue_customers.php</pre>
        </div>
      </div>
      
      <div class="text-center mt-4">
        <a href="/login.php" class="btn btn-primary btn-lg">
          <i class="bi bi-box-arrow-in-right"></i> Login ke Dashboard
        </a>
      </div>
      
      <?php unset($_SESSION['install_success']); ?>

    <?php endif; ?>

    </div>
  </div>

  <p class="text-center text-muted mt-3 small">
    &copy; <?= date('Y') ?> RT/RW Net Management System - PT Lintas Fiber Nusantara
  </p>
</div>

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