<?php
/**
 * AI Vision Attendance — Turbify preflight check.
 *
 * STANDALONE pure-PHP script. Does NOT bootstrap Laravel (must run even if
 * Laravel itself cannot boot, e.g. before vendor/ exists correctly or before
 * .env is configured). Upload this file to the docroot FIRST, browse to it,
 * and confirm every row is PASS before uploading/unzipping the rest of the app.
 *
 * SECURITY: delete this file from the server once the install is complete —
 * it reveals PHP version/extension details to anyone who requests it.
 */

// ---- Configuration: what this app actually needs -------------------------

// Hard requirements — the app cannot run correctly without these.
$requiredExtensions = [
    'pdo'          => 'Database access (PDO core)',
    'pdo_mysql'    => 'MySQL database driver',
    'mbstring'     => 'Multi-byte string handling (Laravel core)',
    'openssl'      => 'Encryption / APP_KEY / hashing (Laravel core)',
    'tokenizer'    => 'Laravel core (route/blade compilation)',
    'ctype'        => 'Laravel core (validation)',
    'json'         => 'Laravel core (config, API payloads)',
    'fileinfo'     => 'MIME detection for CSV import / file uploads',
];

// Soft/optional — nice to have, do not fail the overall verdict if missing.
$optionalExtensions = [
    'bcmath'  => 'Not currently used by this app; harmless if missing',
    'dom'     => 'XML handling; not currently used by this app at runtime',
    'simplexml' => 'XML handling; not currently used by this app at runtime',
    'curl'    => 'Not currently used by this app (no outbound HTTP calls); useful if you add integrations later',
    'gd'      => 'Image processing; not currently used (snapshots are stored as-is, no resizing)',
];

$minPhpVersion = '8.2.0';

// ---- Run checks ------------------------------------------------------------

$rows = [];       // each: [label, ok(bool|null), detail, blocking(bool)]
$overallOk = true;

function av_row(string $label, ?bool $ok, string $detail, bool $blocking = true): array
{
    return compact('label', 'ok', 'detail', 'blocking');
}

// PHP version
$phpOk = version_compare(PHP_VERSION, $minPhpVersion, '>=');
$rows[] = av_row('PHP version', $phpOk, PHP_VERSION.' (need >= '.$minPhpVersion.')');
if (! $phpOk) {
    $overallOk = false;
}

// Required extensions
foreach ($requiredExtensions as $ext => $why) {
    $loaded = extension_loaded($ext);
    $rows[] = av_row("Extension: {$ext}", $loaded, ($loaded ? 'loaded' : 'MISSING').' — '.$why);
    if (! $loaded) {
        $overallOk = false;
    }
}

// Optional extensions (never block overall verdict)
foreach ($optionalExtensions as $ext => $why) {
    $loaded = extension_loaded($ext);
    $rows[] = av_row("Extension: {$ext} (optional)", true, ($loaded ? 'loaded' : 'not installed').' — '.$why, false);
}

// storage/ and bootstrap/cache writability (paths relative to this file in public/)
$appRoot = dirname(__DIR__);
$storagePath = $appRoot.'/storage';
$bootstrapCachePath = $appRoot.'/bootstrap/cache';

$storageExists = is_dir($storagePath);
$storageWritable = $storageExists && is_writable($storagePath);
$rows[] = av_row(
    'storage/ writable',
    $storageExists ? $storageWritable : null,
    $storageExists
        ? ($storageWritable ? 'writable' : 'NOT writable — chmod 755 (or 775) storage/ and its subfolders recursively')
        : 'storage/ not found next to public/ — check you uploaded the full app, not just public/'
);
if ($storageExists && ! $storageWritable) {
    $overallOk = false;
}

$bootstrapExists = is_dir($bootstrapCachePath);
$bootstrapWritable = $bootstrapExists && is_writable($bootstrapCachePath);
$rows[] = av_row(
    'bootstrap/cache writable',
    $bootstrapExists ? $bootstrapWritable : null,
    $bootstrapExists
        ? ($bootstrapWritable ? 'writable' : 'NOT writable — chmod 755 (or 775) bootstrap/cache/')
        : 'bootstrap/cache not found next to public/ — check you uploaded the full app, not just public/'
);
if ($bootstrapExists && ! $bootstrapWritable) {
    $overallOk = false;
}

// mod_rewrite / .htaccess likelihood
$hasHtaccess = is_file(__DIR__.'/.htaccess');
$modRewriteDetected = null;
if (function_exists('apache_get_modules')) {
    $modRewriteDetected = in_array('mod_rewrite', apache_get_modules(), true);
}
$rewriteDetail = $hasHtaccess ? '.htaccess present in public/' : '.htaccess MISSING in public/ (should have been uploaded with the app)';
if ($modRewriteDetected === true) {
    $rewriteDetail .= '; Apache reports mod_rewrite is loaded.';
} elseif ($modRewriteDetected === false) {
    $rewriteDetail .= '; Apache reports mod_rewrite is NOT loaded — pretty URLs will 404. Ask Turbify support to enable it, or check their control panel.';
} else {
    $rewriteDetail .= ' Could not query Apache modules directly (normal on many hosts/PHP-FPM setups) — the real test is browsing to /install after upload: if you get a Laravel page you are fine, if you get a raw directory listing or 404, mod_rewrite/.htaccess overrides are not being honoured (ask Turbify to allow ".htaccess overrides" / enable mod_rewrite for the domain).';
}
$rows[] = av_row('.htaccess / mod_rewrite', $hasHtaccess ? null : false, $rewriteDetail, $hasHtaccess);
if (! $hasHtaccess) {
    $overallOk = false;
}

// Informational: server software, memory limit, upload limits
$rows[] = av_row('Server software', true, $_SERVER['SERVER_SOFTWARE'] ?? 'unknown', false);
$rows[] = av_row('memory_limit', true, ini_get('memory_limit'), false);
$rows[] = av_row('upload_max_filesize', true, ini_get('upload_max_filesize'), false);
$rows[] = av_row('post_max_size', true, ini_get('post_max_size'), false);
$rows[] = av_row('max_execution_time', true, ini_get('max_execution_time').'s (migrations run during /install need at least ~30s)', false);

// ---- Render ------------------------------------------------------------

header('Content-Type: text/html; charset=utf-8');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AI Vision Attendance — Preflight Check</title>
<style>
  body { font-family: -apple-system, Segoe UI, Roboto, Arial, sans-serif; background:#0f172a; color:#e2e8f0; margin:0; padding:2rem; }
  .wrap { max-width: 860px; margin: 0 auto; }
  h1 { font-size: 1.4rem; margin-bottom: .25rem; }
  p.sub { color:#94a3b8; margin-top:0; }
  table { width:100%; border-collapse: collapse; margin-top: 1.5rem; background:#1e293b; border-radius:8px; overflow:hidden; }
  th, td { text-align:left; padding: .6rem .9rem; border-bottom: 1px solid #334155; font-size:.92rem; }
  th { background:#0f172a; color:#94a3b8; font-weight:600; text-transform:uppercase; font-size:.72rem; letter-spacing:.04em; }
  tr:last-child td { border-bottom:none; }
  .pass { color:#4ade80; font-weight:600; }
  .fail { color:#f87171; font-weight:600; }
  .info { color:#94a3b8; font-weight:600; }
  .verdict { margin-top:1.5rem; padding:1rem 1.25rem; border-radius:8px; font-weight:600; font-size:1.05rem; }
  .verdict.ok { background:#052e1a; color:#4ade80; border:1px solid #14532d; }
  .verdict.bad { background:#2e0505; color:#f87171; border:1px solid #7f1d1d; }
  .note { margin-top:1.5rem; font-size:.85rem; color:#94a3b8; line-height:1.5; }
  code { background:#0f172a; padding:.1rem .35rem; border-radius:4px; }
</style>
</head>
<body>
<div class="wrap">
  <h1>AI Vision Attendance — Turbify Preflight Check</h1>
  <p class="sub">Standalone check, no Laravel required. Run this first after uploading the app.</p>

  <table>
    <thead><tr><th style="width:40%">Check</th><th style="width:12%">Result</th><th>Detail</th></tr></thead>
    <tbody>
    <?php foreach ($rows as $row): ?>
      <tr>
        <td><?= htmlspecialchars($row['label']) ?></td>
        <td>
          <?php if ($row['ok'] === true): ?>
            <span class="pass">PASS</span>
          <?php elseif ($row['ok'] === false): ?>
            <span class="fail">FAIL</span>
          <?php else: ?>
            <span class="info">CHECK</span>
          <?php endif; ?>
        </td>
        <td><?= htmlspecialchars($row['detail']) ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>

  <?php if ($overallOk): ?>
    <div class="verdict ok">OVERALL: PASS — this host can run AI Vision Attendance. Proceed to upload the rest of the app and browse to /install.</div>
  <?php else: ?>
    <div class="verdict bad">OVERALL: FAIL — fix the red rows above before installing (usually: ask Turbify support to enable a missing PHP extension, or chmod the storage/bootstrap-cache folders via the file manager/FTP).</div>
  <?php endif; ?>

  <p class="note">
    Once the app passes here and <code>/install</code> has completed successfully, <strong>delete this file
    (<code>check.php</code>) from the server</strong> — it is a diagnostic tool only and should not be left
    reachable in production.
  </p>
</div>
</body>
</html>
