<?php
// Simple installer to generate .env for cPanel/shared hosting
// After successful install, DELETE this file for security.

function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $baseUrl = trim($_POST['base_url'] ?? '');
    $dbHost  = trim($_POST['db_host'] ?? 'localhost');
    $dbName  = trim($_POST['db_name'] ?? '');
    $dbUser  = trim($_POST['db_user'] ?? '');
    $dbPass  = trim($_POST['db_pass'] ?? '');
    $dbPort  = trim($_POST['db_port'] ?? '3306');

    if (!filter_var($baseUrl, FILTER_VALIDATE_URL)) {
        $errors[] = 'Valid Base URL is required (e.g., https://example.com/).';
    }
    if ($dbName === '') { $errors[] = 'Database name is required.'; }
    if ($dbUser === '') { $errors[] = 'Database username is required.'; }
    if ($dbPort === '' || !preg_match('/^\\d+$/', $dbPort)) { $errors[] = 'Database port must be a number.'; }

    // Try basic DB connection check (optional)
    if (empty($errors)) {
        mysqli_report(MYSQLI_REPORT_OFF);
        $conn = @mysqli_connect($dbHost, $dbUser, $dbPass, $dbName, (int)$dbPort);
        if (!$conn) {
            $errors[] = 'Could not connect to MySQL with provided credentials. Please verify and try again.';
        } else {
            @mysqli_close($conn);
        }
    }

    if (empty($errors)) {
        // Generate a random encryption key (32 hex chars)
        $encKey = bin2hex(random_bytes(16));

        $env = "CI_ENVIRONMENT = production\n"
             . "app.baseURL = '" . $baseUrl . "'\n"
             . "app.indexPage = ''\n"
             . "database.default.hostname = '" . $dbHost . "'\n"
             . "database.default.database = '" . $dbName . "'\n"
             . "database.default.username = '" . $dbUser . "'\n"
             . "database.default.password = '" . $dbPass . "'\n"
             . "database.default.DBDriver = MySQLi\n"
             . "database.default.port = " . (int)$dbPort . "\n"
             . "encryption.key = '" . $encKey . "'\n";

        $envPath = __DIR__ . '/../.env';
        if (@file_put_contents($envPath, $env) === false) {
            $errors[] = 'Failed to write .env file. Ensure the project root is writable.';
        } else {
            $success = 'Configuration saved to .env successfully.';

            // Attempt to run CodeIgniter migrations and prepare directories
            try {
                require __DIR__ . '/../app/Config/Paths.php';
                $paths = new Config\Paths();
                require $paths->systemDirectory . '/Boot.php';
                \CodeIgniter\Boot::bootConsole($paths);

                // Ensure uploads directories exist
                @mkdir(__DIR__ . '/../writable/uploads', 0775, true);
                @mkdir(__DIR__ . '/../writable/uploads/logo', 0775, true);

                // Run migrations to create/update database schema
                $migrations = \Config\Services::migrations();
                $migrations->latest();
                $success .= ' Migrations ran successfully.';
            } catch (\Throwable $e) {
                $errors[] = 'Saved .env, but failed to run migrations: ' . $e->getMessage();
            }
        }
    }
}

?><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>School JAS Installer</title>
  <style>
    body { font-family: ui-sans-serif, system-ui, sans-serif; margin: 0; background:#f6f7fb; }
    .wrap { max-width: 720px; margin: 40px auto; background:#fff; padding:24px; border-radius:12px; box-shadow:0 8px 20px rgba(0,0,0,0.06); }
    h1 { margin:0 0 16px; font-size:24px; }
    .desc { color:#555; margin-bottom:16px; }
    .row { display:flex; gap:16px; }
    .field { margin-bottom:14px; }
    label { display:block; font-weight:600; margin-bottom:6px; }
    input[type=text], input[type=url], input[type=password] { width:100%; padding:10px; border:1px solid #d1d5db; border-radius:8px; }
    .btn { background:#2563eb; color:#fff; border:none; padding:10px 16px; border-radius:8px; cursor:pointer; }
    .btn:disabled { background:#9bb7ff; cursor:not-allowed; }
    .alert { padding:12px 14px; border-radius:8px; margin:10px 0; }
    .error { background:#fee2e2; color:#7f1d1d; border:1px solid #fecaca; }
    .success { background:#dcfce7; color:#14532d; border:1px solid #bbf7d0; }
    .note { color:#374151; font-size:14px; }
    ul { margin:8px 0 0; }
  </style>
</head>
<body>
<div class="wrap">
  <h1>School JAS Installer</h1>
  <p class="desc">Fill in your domain and MySQL credentials. This writes the <code>.env</code> file for production on cPanel/shared hosting.</p>

  <?php if (!empty($errors)): ?>
    <div class="alert error">
      <strong>There were issues:</strong>
      <ul>
        <?php foreach ($errors as $e): ?><li><?php echo h($e); ?></li><?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>

  <?php if ($success): ?>
    <div class="alert success">
      <?php echo h($success); ?>
    </div>
    <p class="note">Next steps:</p>
    <ul>
      <li>Point your domain/subdomain document root to the <code>public/</code> folder.</li>
      <li>Log in to your app at the Base URL you provided.</li>
      <li>If migrations failed, import schema via phpMyAdmin or re-run later.</li>
      <li>For security, delete <code>public/install.php</code> after installation.</li>
    </ul>
  <?php endif; ?>

  <form method="post">
    <div class="field">
      <label for="base_url">Base URL</label>
      <input type="url" id="base_url" name="base_url" placeholder="https://yourdomain.com/" value="<?php echo h($_POST['base_url'] ?? ''); ?>" required>
    </div>

    <div class="row">
      <div class="field" style="flex:1;">
        <label for="db_host">DB Host</label>
        <input type="text" id="db_host" name="db_host" placeholder="localhost" value="<?php echo h($_POST['db_host'] ?? 'localhost'); ?>">
      </div>
      <div class="field" style="flex:1;">
        <label for="db_port">DB Port</label>
        <input type="text" id="db_port" name="db_port" placeholder="3306" value="<?php echo h($_POST['db_port'] ?? '3306'); ?>">
      </div>
    </div>

    <div class="row">
      <div class="field" style="flex:1;">
        <label for="db_name">DB Name</label>
        <input type="text" id="db_name" name="db_name" placeholder="school_db" value="<?php echo h($_POST['db_name'] ?? ''); ?>" required>
      </div>
      <div class="field" style="flex:1;">
        <label for="db_user">DB Username</label>
        <input type="text" id="db_user" name="db_user" placeholder="db_user" value="<?php echo h($_POST['db_user'] ?? ''); ?>" required>
      </div>
    </div>

    <div class="field">
      <label for="db_pass">DB Password</label>
      <input type="password" id="db_pass" name="db_pass" placeholder="Your DB password" value="<?php echo h($_POST['db_pass'] ?? ''); ?>">
    </div>

    <button class="btn" type="submit">Save Configuration</button>
  </form>

  <p class="note" style="margin-top:16px;">Tip: If you cannot set the document root to <code>public/</code>, create a subdomain (e.g., <code>app.yourdomain.com</code>) and point it to <code>public/</code>. This is the simplest and most secure way to deploy CodeIgniter 4 on cPanel.</p>
</div>
</body>
</html>
