<?php
// ============================================================
// MetLAB Setup / Installer
// Run once after deploying: http://localhost/metlab/setup.php
// Creates all required directories and verifies write access.
// DELETE THIS FILE after setup is complete.
// ============================================================

// Basic security — only run from localhost or with a token
$allowedIps = ['127.0.0.1', '::1', '::ffff:127.0.0.1'];
$token      = 'metlab_setup_2025'; // change this
$inputToken = $_GET['token'] ?? '';

if (!in_array($_SERVER['REMOTE_ADDR'] ?? '', $allowedIps) && $inputToken !== $token) {
    http_response_code(403);
    die('Forbidden. Access from localhost only, or provide ?token=' . $token);
}

require_once __DIR__ . '/config/config.php';

$checks = [];

// ── Create required directories ───────────────────────────────
$dirs = [
    CERT_PATH       => 'Certificate output directory',
    SIGNATURE_PATH  => 'Signature uploads directory',
];

foreach ($dirs as $path => $label) {
    if (!is_dir($path)) {
        if (mkdir($path, 0755, true)) {
            $checks[] = ['✅', $label, "Created: $path"];
        } else {
            $checks[] = ['❌', $label, "FAILED to create: $path — check parent directory permissions"];
        }
    } else {
        $checks[] = ['✅', $label, "Exists: $path"];
    }

    // Check writability
    if (is_dir($path)) {
        $testFile = $path . '.write_test_' . time();
        if (file_put_contents($testFile, 'test') !== false) {
            unlink($testFile);
            $checks[] = ['✅', $label . ' (writable)', $path];
        } else {
            $checks[] = ['❌', $label . ' (NOT writable)', "Run: chmod 755 $path  or  chown www-data:www-data $path"];
        }
    }
}

// ── Check PHP extensions ──────────────────────────────────────
foreach (['pdo_mysql', 'json', 'openssl', 'mbstring'] as $ext) {
    $checks[] = extension_loaded($ext)
        ? ['✅', "PHP extension: $ext", 'Loaded']
        : ['❌', "PHP extension: $ext", 'MISSING — install php-' . $ext];
}

// ── Check Node.js (for DOCX generation) ──────────────────────
$node = trim((string)shell_exec('which node nodejs 2>/dev/null | head -1'));
$checks[] = $node
    ? ['✅', 'Node.js (for DOCX)', $node . ' — ' . trim((string)shell_exec($node . ' --version 2>/dev/null'))]
    : ['⚠️', 'Node.js (for DOCX)', 'Not found — DOCX certificates will be skipped (HTML/PDF still work)'];

// ── Check wkhtmltopdf (for PDF generation) ───────────────────
$wk = trim((string)shell_exec('which wkhtmltopdf 2>/dev/null'));
$checks[] = $wk
    ? ['✅', 'wkhtmltopdf (for PDF)', $wk]
    : ['⚠️', 'wkhtmltopdf (for PDF)', 'Not found — certificates will be HTML format (downloadable). Install wkhtmltopdf for true PDF output.'];

// ── Check DB connection ───────────────────────────────────────
try {
    $db = Database::getInstance();
    $db->query('SELECT 1');
    $checks[] = ['✅', 'Database connection', DB_HOST . ' / ' . DB_NAME];

    // Check all required tables exist
    $tables = ['users','laboratories','companies','equipment','contact_persons',
               'requests','lab_work_forms','balance_lab_forms','humidity_lab_forms',
               'certificates','activity_logs','user_lab_assignments'];
    foreach ($tables as $t) {
        $stmt = $db->prepare("SHOW TABLES LIKE ?");
        $stmt->execute([$t]);
        $checks[] = $stmt->fetch()
            ? ['✅', "Table: $t", 'Exists']
            : ['❌', "Table: $t", "MISSING — run the appropriate schema SQL file"];
    }
} catch (Exception $e) {
    $checks[] = ['❌', 'Database connection', $e->getMessage()];
}

// ── Run migration 001 if needed ───────────────────────────────
try {
    $db = Database::getInstance();
    // Check if form_id FK still exists (if it does, migration hasn't run yet)
    $stmt = $db->query("
        SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS
        WHERE TABLE_SCHEMA = '" . DB_NAME . "'
        AND TABLE_NAME = 'certificates'
        AND CONSTRAINT_TYPE = 'FOREIGN KEY'
        AND CONSTRAINT_NAME LIKE '%form%'
    ");
    $fkRow = $stmt->fetch();
    if ($fkRow) {
        // Run migration
        $migrationSql = file_get_contents(__DIR__ . '/database/migrations/001_fix_certificates_form_id.sql');
        $statements   = array_filter(array_map('trim', explode(';', $migrationSql)));
        foreach ($statements as $sql) {
            if ($sql && !str_starts_with(ltrim($sql), '--') && !str_starts_with(ltrim($sql), 'USE')) {
                try { $db->exec($sql); } catch (PDOException $e2) { /* ignore DROP IF EXISTS errors */ }
            }
        }
        $checks[] = ['✅', 'Migration 001', 'certificates.form_id FK removed — cross-lab certificates now work'];
    } else {
        $checks[] = ['✅', 'Migration 001', 'Already applied (no FK on form_id)'];
    }
} catch (Exception $e) {
    $checks[] = ['⚠️', 'Migration 001', 'Could not check: ' . $e->getMessage()];
}

// ── Render ────────────────────────────────────────────────────
$allOk = !in_array('❌', array_column($checks, 0));
?>
<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>MetLAB Setup</title>
<style>
  body{font-family:Arial,sans-serif;max-width:800px;margin:40px auto;padding:0 20px;color:#333}
  h1{color:#003366}
  table{width:100%;border-collapse:collapse}
  th,td{padding:8px 12px;border:1px solid #ddd;text-align:left;font-size:13px}
  thead th{background:#003366;color:#fff}
  tr:nth-child(even){background:#f9f9f9}
  .ok{color:green}.warn{color:orange}.err{color:red}
  .banner{padding:16px 20px;border-radius:8px;margin-bottom:20px;font-weight:bold}
  .banner.ok{background:#d4edda;color:#155724}
  .banner.err{background:#f8d7da;color:#721c24}
  .delete-note{background:#fff3cd;border:1px solid #ffc107;padding:12px 16px;border-radius:6px;margin-top:20px;font-size:13px}
</style>
</head><body>
<h1>MetLAB Setup Verification</h1>
<div class="banner <?= $allOk ? 'ok' : 'err' ?>">
  <?= $allOk ? '✅ All checks passed — MetLAB is ready to use.' : '❌ Some checks failed — review the table below.' ?>
</div>

<table>
  <thead><tr><th>Status</th><th>Check</th><th>Details</th></tr></thead>
  <tbody>
  <?php foreach ($checks as [$icon, $label, $detail]): ?>
    <tr>
      <td><?= $icon ?></td>
      <td><?= htmlspecialchars($label) ?></td>
      <td style="font-size:12px;color:#555;"><?= htmlspecialchars($detail) ?></td>
    </tr>
  <?php endforeach; ?>
  </tbody>
</table>

<div class="delete-note">
  ⚠️ <strong>Security:</strong> Delete or rename <code>setup.php</code> after confirming everything works.
  It exposes server paths and should not remain accessible in production.
</div>

<p style="margin-top:20px;font-size:12px;color:#888;">
  MetLAB v<?= APP_VERSION ?> &mdash;
  BASE_PATH: <?= htmlspecialchars(BASE_PATH) ?> &mdash;
  CERT_PATH: <?= htmlspecialchars(CERT_PATH) ?>
</p>
</body></html>
