<?php

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

use KeyLair\ApiToken;
use KeyLair\AuditLog;
use KeyLair\Auth;
use KeyLair\Csrf;
use KeyLair\Database;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\SendySync;
use KeyLair\Settings;

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

$created = null;
$flash = null;
$syncResult = null;

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

    if ($action === 'create') {
        $label = trim($_POST['label'] ?? '');
        $result = ApiToken::create((int) $admin['id'], $label);
        AuditLog::log($admin['id'], 'api_token_created', $result['id'] . ' ' . $label);
        $created = $result['raw'];
    } elseif ($action === 'revoke') {
        $id = (int) ($_POST['id'] ?? 0);
        ApiToken::revoke($id);
        AuditLog::log($admin['id'], 'api_token_revoked', (string) $id);
        $flash = ['type' => 'success', 'message' => I18n::t('api_access.flash.token_revoked')];
    } elseif ($action === 'save_sendy') {
        Settings::set('sendy_url', trim($_POST['sendy_url'] ?? '') ?: null);
        Settings::set('sendy_api_key', trim($_POST['sendy_api_key'] ?? '') ?: null);
        Settings::set('sendy_list_id', trim($_POST['sendy_list_id'] ?? '') ?: null);
        Settings::set('sendy_field_name', trim($_POST['sendy_field_name'] ?? '') ?: null);
        Settings::set('sendy_link_target', trim($_POST['sendy_link_target'] ?? '') ?: null);
        AuditLog::log($admin['id'], 'sendy_settings_updated', null);
        $flash = ['type' => 'success', 'message' => I18n::t('api_access.flash.sendy_saved')];
    } elseif ($action === 'sendy_sync') {
        $syncResult = SendySync::syncAll();
        AuditLog::log($admin['id'], 'sendy_synced', "synced={$syncResult['synced']} skipped={$syncResult['skipped']} failed={$syncResult['failed']}");
    }
}

$tokens = $pdo->query(
    'SELECT t.*, a.username AS created_by_username
     FROM api_tokens t
     LEFT JOIN admin_users a ON a.id = t.created_by
     ORDER BY t.created_at DESC'
)->fetchAll();

$products = $pdo->query("SELECT slug, name FROM products WHERE status != 'archived' ORDER BY name ASC")->fetchAll();

$baseUrl = Helpers::baseUrl();

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

<div class="form-section" style="margin-bottom:16px;">
  <p class="form-section-title"><?= Helpers::e(I18n::t('api_access.lookup_title')) ?></p>
  <p class="form-section-hint">
    <?= Helpers::e(I18n::t('api_access.lookup_hint')) ?>
  </p>
  <?php $codeStyle = 'background:var(--bg-void); padding:2px 6px; border-radius:4px;'; ?>
  <?php $blockStyle = 'display:block; background:var(--bg-void); border:1px solid var(--line); border-radius:8px; padding:10px 12px; margin:6px 0 0; white-space:pre-wrap; overflow-wrap:break-word;'; ?>
  <p style="font-size:12.5px; color:var(--text-muted); margin:0;">
    <code style="<?= $codeStyle ?>">GET <?= Helpers::e($baseUrl) ?>/api/claim_link_lookup.php?email=someone@example.com</code><br>
    <?= Helpers::e(I18n::t('api_access.lookup_with_header')) ?> <code style="<?= $codeStyle ?>">Authorization: Bearer &lt;token&gt;</code>
    — <?= Helpers::e(I18n::t('api_access.lookup_returns_json')) ?>
  </p>
  <details style="margin-top:12px;">
    <summary style="cursor:pointer; font-size:12.5px; color:var(--signal);"><?= Helpers::e(I18n::t('api_access.how_to_use_summary')) ?></summary>
    <div style="margin-top:10px; font-size:12.5px; color:var(--text-muted); line-height:1.6;">
      <p style="margin:0 0 6px;"><?= I18n::t('api_access.step1_html') ?></p>
      <p style="margin:0 0 6px;"><?= I18n::t('api_access.step2_html') ?></p>
      <code style="<?= $blockStyle ?> font-family:var(--font-mono);">curl "<?= Helpers::e($baseUrl) ?>/api/claim_link_lookup.php?email=jane@example.com" \
  -H "Authorization: Bearer kl_your_token_here"</code>
      <p style="margin:10px 0 6px;"><?= I18n::t('api_access.step3_html') ?></p>
      <code style="<?= $blockStyle ?> font-family:var(--font-mono);">{
  "email": "jane@example.com",
  "users": [
    {
      "user_id": 12,
      "name": "Jane Doe",
      "claim_links": [
        {
          "status": "active",
          "campaign": "Summer Sale",
          "expires_at": null,
          "overview_url": "<?= Helpers::e($baseUrl) ?>/claim/&lt;token&gt;",
          "products": [
            { "name": "Family Bowling", "url": "<?= Helpers::e($baseUrl) ?>/claim/&lt;token&gt;/family-bowling", "max_claims": 1, "claims_used": 0 }
          ]
        }
      ]
    }
  ]
}</code>
      <p style="margin:10px 0 0;"><?= I18n::t('api_access.no_match_html') ?></p>
      <p style="margin:10px 0 0;"><?= I18n::t('api_access.sendy_specific_html') ?></p>
    </div>
  </details>
</div>

<?php if ($created): ?>
  <div class="form-section" style="border-color:var(--signal-dim); margin-bottom:16px;">
    <p style="color:var(--signal); font-size:14px; font-weight:600; margin:0 0 10px;"><?= Helpers::e(I18n::t('api_access.token_created_title')) ?></p>
    <p style="font-size:12.5px; color:var(--text-muted); margin:0 0 10px;">
      <?= Helpers::e(I18n::t('api_access.token_created_hint')) ?>
    </p>
    <div style="display:flex; gap:8px; align-items:center;">
      <input type="text" readonly value="<?= Helpers::e($created) ?>" onclick="this.select();"
             style="flex:1; background:var(--bg-void); border:1px solid var(--line); color:var(--text-primary); font-family:var(--font-mono); font-size:12.5px; padding:9px 12px; border-radius:8px;">
      <button type="button" class="btn btn-primary" onclick="navigator.clipboard.writeText('<?= Helpers::e($created) ?>'); this.textContent=<?= json_encode(I18n::t('api_access.copied_button'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>;"><?= Helpers::e(I18n::t('api_access.copy_button')) ?></button>
    </div>
  </div>
<?php elseif ($flash): ?>
  <div class="form-section" 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="form-section" style="margin-bottom:16px;">
  <p class="form-section-title"><?= Helpers::e(I18n::t('api_access.create_token_title')) ?></p>
  <form method="post">
    <?= Csrf::field() ?>
    <input type="hidden" name="form_action" value="create">
    <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('api_access.label_field_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('api_access.label_field_hint')) ?></span></label>
        <input type="text" name="label" placeholder="Sendy" required>
      </div>
    </div>
    <div class="form-actions" style="padding-bottom:0;"><button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('api_access.create_token_button')) ?></button></div>
    </fieldset>
  </form>
</div>

<div class="panel">
  <?php if (empty($tokens)): ?>
    <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('api_access.no_tokens')) ?></p>
  <?php else: ?>
  <table>
    <thead><tr><th><?= Helpers::e(I18n::t('api_access.table.label')) ?></th><th><?= Helpers::e(I18n::t('api_access.table.created_by')) ?></th><th><?= Helpers::e(I18n::t('api_access.table.created')) ?></th><th><?= Helpers::e(I18n::t('api_access.table.last_used')) ?></th><th><?= Helpers::e(I18n::t('api_access.table.status')) ?></th><th></th></tr></thead>
    <tbody>
      <?php foreach ($tokens as $t): ?>
      <tr>
        <td data-label="<?= Helpers::e(I18n::t('api_access.table.label')) ?>"><?= Helpers::e($t['label']) ?></td>
        <td data-label="<?= Helpers::e(I18n::t('api_access.table.created_by')) ?>"><?= $t['created_by_username'] !== null ? Helpers::e($t['created_by_username']) : '<span style="color:var(--text-faint);">—</span>' ?></td>
        <td class="time-cell" data-label="<?= Helpers::e(I18n::t('api_access.table.created')) ?>"><?= Helpers::e($t['created_at']) ?></td>
        <td class="time-cell" data-label="<?= Helpers::e(I18n::t('api_access.table.last_used')) ?>"><?= $t['last_used_at'] !== null ? Helpers::e($t['last_used_at']) : '<span style="color:var(--text-faint);">' . Helpers::e(I18n::t('api_access.never')) . '</span>' ?></td>
        <td data-label="<?= Helpers::e(I18n::t('api_access.table.status')) ?>">
          <?php if ($t['revoked_at'] !== null): ?>
            <span class="plat-tag" style="background:rgba(136,144,164,0.12); color:var(--text-muted);"><?= Helpers::e(I18n::t('api_access.status_revoked')) ?></span>
          <?php else: ?>
            <span class="plat-tag"><?= Helpers::e(I18n::t('api_access.status_active')) ?></span>
          <?php endif; ?>
        </td>
        <td style="white-space:nowrap;">
          <?php if (!$isDemo && $t['revoked_at'] === null): ?>
          <form method="post" style="display:inline;" onsubmit="return confirm(<?= json_encode(I18n::t('api_access.revoke_confirm_js'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
            <?= Csrf::field() ?>
            <input type="hidden" name="form_action" value="revoke">
            <input type="hidden" name="id" value="<?= (int) $t['id'] ?>">
            <button type="submit" style="background:none; border:none; color:var(--danger); font-size:12px; cursor:pointer; padding:0;"><?= Helpers::e(I18n::t('api_access.revoke_button')) ?></button>
          </form>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
  <?php endif; ?>
</div>

<div class="form-section" style="margin-top:24px; margin-bottom:16px;">
  <p class="form-section-title"><?= Helpers::e(I18n::t('api_access.sendy_sync_title')) ?></p>
  <p class="form-section-hint">
    <?= I18n::t('api_access.sendy_sync_hint_html') ?>
  </p>
  <form method="post">
    <?= Csrf::field() ?>
    <input type="hidden" name="form_action" value="save_sendy">
    <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('api_access.sendy_url_label')) ?></label>
        <input type="url" name="sendy_url" value="<?= Helpers::e(Settings::sendyUrl() ?? '') ?>" placeholder="https://sendy.example.com">
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('api_access.sendy_api_key_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('api_access.sendy_api_key_hint')) ?></span></label>
        <input type="text" name="sendy_api_key" value="<?= Helpers::e(Settings::sendyApiKey() ?? '') ?>" placeholder="Sendy API key">
      </div>
    </div>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('api_access.sendy_list_id_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('api_access.sendy_list_id_hint')) ?></span></label>
        <input type="text" name="sendy_list_id" value="<?= Helpers::e(Settings::sendyListId() ?? '') ?>" placeholder="Sendy list id">
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('api_access.sendy_field_name_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('api_access.sendy_field_name_hint')) ?></span></label>
        <input type="text" name="sendy_field_name" value="<?= Helpers::e(Settings::sendyFieldName()) ?>" placeholder="ClaimLink">
      </div>
    </div>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('api_access.sendy_link_target_label')) ?></label>
        <select name="sendy_link_target">
          <option value="overview" <?= Settings::sendyLinkTarget() === 'overview' ? 'selected' : '' ?>><?= Helpers::e(I18n::t('api_access.sendy_link_overview_option')) ?></option>
          <?php foreach ($products as $p): ?>
            <option value="<?= Helpers::e($p['slug']) ?>" <?= Settings::sendyLinkTarget() === $p['slug'] ? 'selected' : '' ?>><?= Helpers::e(sprintf(I18n::t('api_access.sendy_link_product_option'), $p['name'])) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="form-actions" style="padding-bottom:0;"><button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('api_access.save_sendy_button')) ?></button></div>
    </fieldset>
  </form>

  <?php if ($syncResult): ?>
    <div class="form-section" style="border-color:<?= $syncResult['failed'] > 0 || !empty($syncResult['errors']) ? 'var(--danger)' : 'var(--signal-dim)' ?>; margin-top:16px;">
      <p style="font-size:13px; margin:0 0 8px;">
        <?= sprintf(I18n::t('api_access.sync_result_summary'), (int) $syncResult['synced'], (int) $syncResult['skipped'], (int) $syncResult['failed']) ?>
      </p>
      <?php if (!empty($syncResult['errors'])): ?>
        <pre style="background:var(--bg-void); border:1px solid var(--line); border-radius:8px; padding:10px 12px; font-size:11.5px; color:var(--text-muted); white-space:pre-wrap; overflow-wrap:break-word; margin:0; max-height:200px; overflow-y:auto;"><?= Helpers::e(implode("\n", $syncResult['errors'])) ?></pre>
      <?php endif; ?>
    </div>
  <?php endif; ?>

  <?php if (!$isDemo): ?>
  <form method="post" style="margin-top:16px;" onsubmit="return confirm(<?= json_encode(I18n::t('api_access.sync_confirm_js'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
    <?= Csrf::field() ?>
    <input type="hidden" name="form_action" value="sendy_sync">
    <button type="submit" class="btn btn-ghost" <?= Settings::sendyConfigured() ? '' : 'disabled title="' . Helpers::e(I18n::t('api_access.sync_disabled_title')) . '"' ?>><?= Helpers::e(I18n::t('api_access.sync_now_button')) ?></button>
  </form>
  <?php endif; ?>
</div>

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