<?php
/**
 * LIS Portal — Web Installer (SQLite edition)
 * Drop this file in public/ then visit  http://YOUR_IP/install.php
 * It will configure .env and verify setup.
 * DELETE THIS FILE after installation is complete.
 */

define('BASE', dirname(__DIR__));
define('VER', '1.1');

// ── Helpers ───────────────────────────────────────────────────────────────────

function req(string $ext): bool   { return extension_loaded($ext); }
function writable(string $p): bool { return is_writable(BASE.'/'.$p); }

function checkReqs(): array {
    return [
        ['PHP >= 8.2',                version_compare(PHP_VERSION,'8.2','>=')],
        ['PDO extension',             req('pdo')],
        ['PDO SQLite',                req('pdo_sqlite')],
        ['OpenSSL',                   req('openssl')],
        ['Mbstring',                  req('mbstring')],
        ['Tokenizer',                 req('tokenizer')],
        ['JSON',                      req('json')],
        ['BCMath / GMP',              req('bcmath') || req('gmp')],
        ['storage/ writable',         writable('storage')],
        ['bootstrap/cache/ writable', writable('bootstrap/cache')],
        ['vendor/ present',           is_dir(BASE.'/vendor')],
        ['database/ writable',        writable('database')],
        ['SQLite file present',       file_exists(BASE.'/database/database.sqlite')],
    ];
}

function generateKey(): string {
    return 'base64:'.base64_encode(random_bytes(32));
}

function writeEnv(string $appUrl, string $dbPath): void {
    $key = generateKey();
    $url = rtrim($appUrl, '/');
    $env = <<<ENV
APP_NAME="LIS Portal"
APP_ENV=production
APP_KEY={$key}
APP_DEBUG=false
APP_URL={$url}

LOG_CHANNEL=daily
LOG_LEVEL=warning

DB_CONNECTION=sqlite
DB_DATABASE={$dbPath}

SESSION_DRIVER=file
SESSION_LIFETIME=120
CACHE_STORE=file
QUEUE_CONNECTION=sync

BROADCAST_CONNECTION=log
MAIL_MAILER=log
ENV;
    file_put_contents(BASE.'/.env', $env);
}

function detectDbPath(): string {
    // Absolute path so SQLite works regardless of working directory
    return BASE.'/database/database.sqlite';
}

// ── Request handling ──────────────────────────────────────────────────────────

$step    = $_POST['step'] ?? 'check';
$errors  = [];
$success = [];

if ($step === 'install' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $appUrl = trim($_POST['app_url'] ?? '');
    $dbPath = detectDbPath();

    if (empty($appUrl)) {
        $errors[] = 'Site URL is required.';
        $step = 'form';
    } elseif (!filter_var($appUrl, FILTER_VALIDATE_URL)) {
        $errors[] = 'Site URL must be a valid URL (e.g. http://192.168.1.10).';
        $step = 'form';
    } else {
        try {
            // Verify SQLite is accessible
            $pdo = new PDO('sqlite:'.$dbPath, null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            $tables = $pdo->query("SELECT name FROM sqlite_master WHERE type='table'")->fetchAll(PDO::FETCH_COLUMN);
            $success[] = '✓ SQLite connection OK ('.count($tables).' tables found)';

            writeEnv($appUrl, $dbPath);
            $success[] = '✓ .env written (APP_KEY generated)';

            // Clear any stale bootstrap cache
            foreach (glob(BASE.'/bootstrap/cache/*.php') as $f) @unlink($f);
            $success[] = '✓ Bootstrap cache cleared';

            // Storage symlink (best-effort — may not work on all shared hosts)
            $link   = BASE.'/public/storage';
            $target = BASE.'/storage/app/public';
            if (!file_exists($link) && !is_link($link)) {
                @symlink($target, $link);
                $success[] = '✓ Storage link created';
            } else {
                $success[] = 'ℹ Storage link already exists';
            }

            $step = 'done';
        } catch (Exception $e) {
            $errors[] = 'Error: '.$e->getMessage();
            $step = 'form';
        }
    }
}

$reqs      = checkReqs();
$allPassed = array_reduce($reqs, fn($c,$r) => $c && $r[1], true);

?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>PLUS SmartLane Lite — Installer v<?= VER ?></title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:system-ui,sans-serif;background:#0d1117;color:#e2e8f0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px}
.card{background:#141820;border:1px solid #1e2433;border-radius:12px;padding:36px;width:100%;max-width:520px}
h1{font-size:1.3rem;font-weight:700;color:#60a5fa;margin-bottom:4px}
.sub{font-size:.85rem;color:#64748b;margin-bottom:28px}
.badge{background:#1e2433;border-radius:99px;padding:3px 12px;font-size:.75rem;font-weight:600;color:#60a5fa;display:inline-block;margin-bottom:16px}
table{width:100%;border-collapse:collapse;margin-bottom:20px}
td{padding:7px 4px;font-size:.83rem;border-bottom:1px solid #1e2433}
td:last-child{text-align:right;font-weight:600}
.ok{color:#4ade80}.fail{color:#f87171}
label{display:block;font-size:.82rem;color:#94a3b8;margin-bottom:4px;margin-top:14px}
input{width:100%;background:#0d1117;border:1px solid #1e2433;border-radius:6px;padding:8px 12px;color:#e2e8f0;font-size:.88rem;outline:none}
input:focus{border-color:#3b82f6}
.hint{font-size:.76rem;color:#475569;margin-top:4px}
.btn{display:block;width:100%;margin-top:24px;padding:11px;background:#2563eb;color:#fff;border:none;border-radius:8px;font-size:.95rem;font-weight:600;cursor:pointer}
.btn:hover{background:#1d4ed8}
.btn:disabled{background:#1e2433;color:#475569;cursor:not-allowed}
.log{background:#0d1117;border:1px solid #1e2433;border-radius:8px;padding:14px;font-size:.8rem;font-family:monospace;margin-bottom:16px;max-height:200px;overflow-y:auto}
.log p{padding:2px 0;color:#94a3b8}
.log p.ok{color:#4ade80}.log p.err{color:#f87171}
.err-box{background:#2d1a1a;border:1px solid #7f1d1d;border-radius:8px;padding:12px;font-size:.82rem;color:#f87171;margin-bottom:14px}
.warn{background:#291900;border:1px solid #78350f;border-radius:8px;padding:12px;font-size:.82rem;color:#fbbf24;margin-bottom:14px}
.delete-note{background:#1a2a1a;border:1px solid #166534;border-radius:8px;padding:12px;font-size:.82rem;color:#4ade80;margin-top:16px}
.done-icon{font-size:3rem;text-align:center;margin-bottom:12px}
</style>
</head>
<body>
<div class="card">
  <h1>🛠 LIS Portal Installer</h1>
  <div class="sub">LDP Northbound Smart Lane Management · v<?= VER ?></div>

<?php if ($step === 'done'): ?>

  <div class="done-icon">✅</div>
  <h2 style="text-align:center;margin-bottom:20px;color:#4ade80">Installation Complete!</h2>
  <div class="log">
    <?php foreach ($success as $l): ?>
    <p class="<?= str_starts_with($l,'✓') ? 'ok' : '' ?>"><?= htmlspecialchars($l) ?></p>
    <?php endforeach; ?>
  </div>
  <div class="delete-note">
    ⚠ <strong>Security:</strong> Delete <code>public/install.php</code> from your server now via File Manager.<br>
    Do not leave the installer accessible.
  </div>
  <a href="<?= htmlspecialchars(rtrim($_POST['app_url'] ?? '', '/')) ?>/lis-portal" style="display:block;margin-top:16px">
    <button class="btn">Open PLUS SmartLane Lite →</button>
  </a>

<?php elseif ($step === 'form' || ($step === 'check' && $allPassed)): ?>

  <span class="badge">Step 2 — Configure</span>

  <?php if ($errors): ?>
  <div class="err-box"><?= implode('<br>', array_map('htmlspecialchars', $errors)) ?></div>
  <?php endif; ?>

  <form method="POST">
    <input type="hidden" name="step" value="install">

    <label>Server IP / Site URL <span style="color:#f87171">*</span></label>
    <input name="app_url"
           value="<?= htmlspecialchars($_POST['app_url'] ?? 'http://') ?>"
           placeholder="http://192.168.1.10">
    <div class="hint">Use the IP address (or hostname) you access this server with. No trailing slash.</div>

    <button class="btn">Run Installation →</button>
  </form>

<?php else: ?>

  <span class="badge">Step 1 — Server Check</span>

  <?php if (!$allPassed): ?>
  <div class="warn">⚠ Some requirements are not met. Fix them before continuing.</div>
  <?php endif; ?>

  <table>
  <?php foreach ($reqs as [$label, $pass]): ?>
    <tr>
      <td><?= htmlspecialchars($label) ?></td>
      <td class="<?= $pass ? 'ok' : 'fail' ?>"><?= $pass ? '✓ OK' : '✗ FAIL' ?></td>
    </tr>
  <?php endforeach; ?>
  </table>

  <?php if (!$allPassed): ?>
    <?php if (!is_dir(BASE.'/vendor')): ?>
    <div class="err-box">
      <strong>vendor/ folder missing</strong><br>
      This folder must be included in the uploaded zip. Contact support if you received a zip without it.
    </div>
    <?php endif; ?>
    <?php if (!file_exists(BASE.'/database/database.sqlite')): ?>
    <div class="err-box">
      <strong>database/database.sqlite missing</strong><br>
      The SQLite database file was not uploaded. Check the zip contents and re-upload.
    </div>
    <?php endif; ?>
    <button class="btn" disabled>Requirements not met — fix above first</button>
  <?php else: ?>
    <form method="POST">
      <input type="hidden" name="step" value="form">
      <button class="btn">Continue →</button>
    </form>
  <?php endif; ?>

<?php endif; ?>

</div>
</body>
</html>
