<?php

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

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

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

$editing = null;
if (!empty($_GET['edit'])) {
    $stmt = $pdo->prepare('SELECT * FROM campaigns WHERE id = :id');
    $stmt->execute(['id' => (int) $_GET['edit']]);
    $editing = $stmt->fetch() ?: null;
}

$flash = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Auth::requireEditAccess();
    Csrf::requireValid();
    $action = $_POST['form_action'] ?? '';

    if ($action === 'save') {
        $id = (int) ($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $status = ($_POST['status'] ?? 'active') === 'archived' ? 'archived' : 'active';
        $defaultMaxClaims = max(1, (int) ($_POST['default_max_claims'] ?? 1));

        if ($name === '') {
            $flash = ['type' => 'error', 'message' => I18n::t('campaigns.flash.name_required')];
        } elseif ($id > 0) {
            $stmt = $pdo->prepare('UPDATE campaigns SET name=:name, status=:status, default_max_claims=:dmc WHERE id=:id');
            $stmt->execute(['name' => $name, 'status' => $status, 'dmc' => $defaultMaxClaims, 'id' => $id]);
            AuditLog::log($admin['id'], 'campaign_updated', $name);
            Helpers::redirect('campaigns.php');
        } else {
            $stmt = $pdo->prepare('INSERT INTO campaigns (name, status, default_max_claims, created_at) VALUES (:name,:status,:dmc,NOW())');
            $stmt->execute(['name' => $name, 'status' => $status, 'dmc' => $defaultMaxClaims]);
            AuditLog::log($admin['id'], 'campaign_created', $name);
            Helpers::redirect('campaigns.php');
        }
    } elseif ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $pdo->prepare('DELETE FROM campaigns WHERE id = :id');
        $stmt->execute(['id' => $id]);
        AuditLog::log($admin['id'], 'campaign_deleted', (string) $id);
        Helpers::redirect('campaigns.php');
    }
}

$campaigns = $pdo->query(
    'SELECT c.*,
        (SELECT COUNT(*) FROM `keys` k WHERE k.campaign_id = c.id) AS key_count,
        (SELECT COUNT(*) FROM claim_links l WHERE l.campaign_id = c.id) AS link_count
     FROM campaigns c ORDER BY c.created_at DESC'
)->fetchAll();

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

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

<div class="row-2 row-2-list-form">
  <div class="panel">
    <p class="panel-title"><?= Helpers::e(I18n::t('campaigns.all_campaigns_title')) ?></p>
    <?php if (empty($campaigns)): ?>
      <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('campaigns.empty_state')) ?></p>
    <?php else: ?>
    <table>
      <thead><tr><th><?= Helpers::e(I18n::t('campaigns.col_name')) ?></th><th><?= Helpers::e(I18n::t('campaigns.col_status')) ?></th><th><?= Helpers::e(I18n::t('campaigns.col_default_limit')) ?></th><th><?= Helpers::e(I18n::t('campaigns.col_keys')) ?></th><th><?= Helpers::e(I18n::t('campaigns.col_links')) ?></th><th></th></tr></thead>
      <tbody>
        <?php foreach ($campaigns as $c): ?>
        <tr>
          <td class="creator" data-label="<?= Helpers::e(I18n::t('campaigns.col_name')) ?>"><?= Helpers::e($c['name']) ?></td>
          <td data-label="<?= Helpers::e(I18n::t('campaigns.col_status')) ?>"><span class="plat-tag" style="<?= $c['status'] === 'archived' ? 'background:rgba(136,144,164,0.12); color:var(--text-muted);' : '' ?>"><?= Helpers::e(I18n::t('campaigns.status_' . $c['status'])) ?></span></td>
          <td class="time-cell" data-label="<?= Helpers::e(I18n::t('campaigns.col_default_limit')) ?>"><?= (int) $c['default_max_claims'] ?></td>
          <td class="time-cell" data-label="<?= Helpers::e(I18n::t('campaigns.col_keys')) ?>"><?= (int) $c['key_count'] ?></td>
          <td class="time-cell" data-label="<?= Helpers::e(I18n::t('campaigns.col_links')) ?>"><?= (int) $c['link_count'] ?></td>
          <td>
            <?php if (Auth::canEdit() || $isDemo): ?>
            <?php if (Auth::canEdit()): ?>
            <a href="campaigns.php?edit=<?= (int) $c['id'] ?>" style="color:var(--signal); font-size:12px; text-decoration:none; margin-right:10px;"><?= Helpers::e(I18n::t('campaigns.edit')) ?></a>
            <?php else: ?>
            <span style="color:var(--text-faint); font-size:12px; text-decoration:none; margin-right:10px; cursor:not-allowed;"><?= Helpers::e(I18n::t('campaigns.edit')) ?></span>
            <?php endif; ?>
            <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0; display:inline;">
            <form method="post" style="display:inline;" onsubmit="return confirm(<?= json_encode(I18n::t('campaigns.delete_confirm_js'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
              <?= Csrf::field() ?>
              <input type="hidden" name="form_action" value="delete">
              <input type="hidden" name="id" value="<?= (int) $c['id'] ?>">
              <button type="submit" style="background:none; border:none; color:var(--danger); font-size:12px; cursor:pointer; padding:0;"><?= Helpers::e(I18n::t('campaigns.delete')) ?></button>
            </form>
            </fieldset>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

  <?php if (Auth::canEdit() || $isDemo): ?>
  <div class="panel">
    <p class="panel-title"><?= $editing ? Helpers::e(I18n::t('campaigns.edit_title')) : Helpers::e(I18n::t('campaigns.new_title')) ?></p>
    <form method="post">
      <?= Csrf::field() ?>
      <input type="hidden" name="form_action" value="save">
      <input type="hidden" name="id" value="<?= $editing ? (int) $editing['id'] : 0 ?>">
      <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
      <div class="field">
        <label><?= Helpers::e(I18n::t('campaigns.col_name')) ?></label>
        <input type="text" name="name" value="<?= Helpers::e($editing['name'] ?? '') ?>" required>
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('campaigns.col_status')) ?></label>
        <select name="status">
          <option value="active" <?= (!$editing || $editing['status'] === 'active') ? 'selected' : '' ?>><?= Helpers::e(I18n::t('campaigns.status_active')) ?></option>
          <option value="archived" <?= ($editing && $editing['status'] === 'archived') ? 'selected' : '' ?>><?= Helpers::e(I18n::t('campaigns.status_archived')) ?></option>
        </select>
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('campaigns.field_default_limit')) ?></label>
        <input type="number" name="default_max_claims" min="1" value="<?= (int) ($editing['default_max_claims'] ?? 1) ?>">
      </div>
      <div class="form-actions" style="padding-bottom:0;">
        <?php if ($editing): ?><a href="campaigns.php" class="btn btn-ghost" style="text-decoration:none;"><?= Helpers::e(I18n::t('campaigns.cancel')) ?></a><?php endif; ?>
        <button type="submit" class="btn btn-primary"><?= $editing ? Helpers::e(I18n::t('campaigns.save_changes')) : Helpers::e(I18n::t('campaigns.create_campaign')) ?></button>
      </div>
      </fieldset>
    </form>
  </div>
  <?php endif; ?>
</div>

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