<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\Auth;
use KeyLair\AuditLog;
use KeyLair\Csrf;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\Migrator;

$admin = Auth::requireAdminTierView();
$isDemo = $admin['role'] === 'demo';

$flash = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($isDemo) {
        http_response_code(403);
        die(I18n::t('migrations.demo_readonly'));
    }
    Csrf::requireValid();
    $filename = basename($_POST['filename'] ?? '');
    $action = $_POST['form_action'] ?? 'run';

    if ($action === 'mark_applied') {
        $result = Migrator::markApplied($filename);
        if ($result['ok']) {
            AuditLog::log($admin['id'], 'migration_marked_applied', $filename);
            $flash = ['type' => 'success', 'message' => sprintf(I18n::t('migrations.flash.marked_applied'), $filename)];
        } else {
            $flash = ['type' => 'error', 'message' => sprintf(I18n::t('migrations.flash.mark_failed'), $filename) . ' ' . $result['error']];
        }
    } else {
        $result = Migrator::run($filename);
        if ($result['ok']) {
            AuditLog::log($admin['id'], 'migration_applied', $filename);
            $flash = ['type' => 'success', 'message' => sprintf(I18n::t('migrations.flash.applied'), $filename)];
        } else {
            $flash = ['type' => 'error', 'message' => sprintf(I18n::t('migrations.flash.apply_failed'), $filename) . ' ' . $result['error']];
        }
    }
}

$pending = Migrator::pending();
$applied = Migrator::applied();

$pageTitle = I18n::t('migrations.page_title');
$activeNav = 'migrations';
$extraAdminCss = 'admin-product-editor';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar"><h1><?= Helpers::e(I18n::t('migrations.page_title')) ?></h1></div>

<?php if ($flash): ?>
  <div class="panel" style="border-color:<?= $flash['type'] === 'success' ? 'var(--signal-dim)' : 'var(--danger)' ?>; margin-bottom:16px;">
    <span style="color:<?= $flash['type'] === 'success' ? 'var(--signal)' : 'var(--danger)' ?>; font-size:13px;"><?= Helpers::e($flash['message']) ?></span>
  </div>
<?php endif; ?>

<div class="panel" style="margin-bottom:16px;">
  <p class="panel-title"><?= Helpers::e(I18n::t('migrations.pending_title')) ?></p>
  <?php if (empty($pending)): ?>
    <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('migrations.pending_empty')) ?></p>
  <?php else: ?>
    <p style="color:var(--text-muted); font-size:12.5px; margin:0 0 14px;">
      <?= I18n::t('migrations.pending_hint_html') ?>
    </p>
    <table>
      <thead><tr><th><?= Helpers::e(I18n::t('migrations.table.file')) ?></th><th></th></tr></thead>
      <tbody>
        <?php foreach ($pending as $file): ?>
        <tr>
          <td class="creator" data-label="<?= Helpers::e(I18n::t('migrations.table.file')) ?>" style="font-family:var(--font-mono); font-size:12.5px;"><?= Helpers::e($file) ?></td>
          <td style="white-space:nowrap;">
            <?php if ($isDemo): ?>
              <button type="button" class="btn btn-primary" disabled style="padding:6px 14px; font-size:12px;"><?= Helpers::e(I18n::t('migrations.run_button')) ?></button>
              <button type="button" class="btn btn-ghost" disabled style="padding:6px 14px; font-size:12px;"><?= Helpers::e(I18n::t('migrations.mark_applied_button')) ?></button>
            <?php else: ?>
            <form method="post" style="display:inline;" onsubmit="return confirm(<?= json_encode(I18n::t('migrations.run_confirm_js'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
              <?= Csrf::field() ?>
              <input type="hidden" name="form_action" value="run">
              <input type="hidden" name="filename" value="<?= Helpers::e($file) ?>">
              <button type="submit" class="btn btn-primary" style="padding:6px 14px; font-size:12px;"><?= Helpers::e(I18n::t('migrations.run_button')) ?></button>
            </form>
            <form method="post" style="display:inline;" onsubmit="return confirm(<?= json_encode(I18n::t('migrations.mark_applied_confirm_js'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
              <?= Csrf::field() ?>
              <input type="hidden" name="form_action" value="mark_applied">
              <input type="hidden" name="filename" value="<?= Helpers::e($file) ?>">
              <button type="submit" class="btn btn-ghost" style="padding:6px 14px; font-size:12px;"><?= Helpers::e(I18n::t('migrations.mark_applied_button')) ?></button>
            </form>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</div>

<div class="panel">
  <?php if (empty($applied)): ?>
    <p class="panel-title"><?= Helpers::e(I18n::t('migrations.applied_title')) ?></p>
    <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('migrations.applied_empty')) ?></p>
  <?php else: ?>
    <details>
      <summary class="panel-title" style="cursor:pointer; display:inline-block;"><?= Helpers::e(sprintf(I18n::t('migrations.applied_summary'), count($applied))) ?></summary>
      <table style="margin-top:12px;">
        <thead><tr><th><?= Helpers::e(I18n::t('migrations.table.file')) ?></th><th><?= Helpers::e(I18n::t('migrations.table.applied_at')) ?></th></tr></thead>
        <tbody>
          <?php foreach ($applied as $file => $appliedAt): ?>
          <tr>
            <td class="creator" data-label="<?= Helpers::e(I18n::t('migrations.table.file')) ?>" style="font-family:var(--font-mono); font-size:12.5px;"><?= Helpers::e($file) ?></td>
            <td class="time-cell" data-label="<?= Helpers::e(I18n::t('migrations.table.applied_at')) ?>"><?= Helpers::e($appliedAt) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </details>
  <?php endif; ?>
</div>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>
