<?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 creator_groups WHERE id = :id');
    $stmt->execute(['id' => (int) $_GET['edit']]);
    $editing = $stmt->fetch() ?: 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'] ?? '');
        $defaultRaw = trim($_POST['default_max_claims'] ?? '');
        $default = $defaultRaw === '' ? null : max(1, (int) $defaultRaw);

        if ($name !== '') {
            if ($id > 0) {
                $stmt = $pdo->prepare('UPDATE creator_groups SET name=:name, default_max_claims=:d WHERE id=:id');
                $stmt->execute(['name' => $name, 'd' => $default, 'id' => $id]);
                AuditLog::log($admin['id'], 'creator_group_updated', $name);
            } else {
                $stmt = $pdo->prepare('INSERT INTO creator_groups (name, default_max_claims, created_at) VALUES (:name,:d,NOW())');
                $stmt->execute(['name' => $name, 'd' => $default]);
                AuditLog::log($admin['id'], 'creator_group_created', $name);
            }
        }
        Helpers::redirect('creator_groups.php');
    } elseif ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        $pdo->prepare('DELETE FROM creator_groups WHERE id = :id')->execute(['id' => $id]);
        AuditLog::log($admin['id'], 'creator_group_deleted', (string) $id);
        Helpers::redirect('creator_groups.php');
    }
}

$groups = $pdo->query(
    'SELECT g.*, (SELECT COUNT(*) FROM claim_links l WHERE l.creator_group_id = g.id) AS link_count
     FROM creator_groups g ORDER BY g.name ASC'
)->fetchAll();

$pageTitle = I18n::t('creator_groups.page_title');
$activeNav = 'creator_groups';
$extraAdminCss = 'admin-product-editor';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar"><h1><?= Helpers::e(I18n::t('creator_groups.page_title')) ?></h1></div>
<p style="color:var(--text-muted); font-size:13px; max-width:600px; margin:-8px 0 20px;">
  <?= Helpers::e(I18n::t('creator_groups.intro_hint')) ?>
</p>

<div class="row-2 row-2-list-form">
  <div class="panel">
    <p class="panel-title"><?= Helpers::e(I18n::t('creator_groups.panel_all_groups')) ?></p>
    <?php if (empty($groups)): ?>
      <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('creator_groups.empty_state')) ?></p>
    <?php else: ?>
    <table>
      <thead><tr><th><?= Helpers::e(I18n::t('creator_groups.col_name')) ?></th><th><?= Helpers::e(I18n::t('creator_groups.col_default_limit')) ?></th><th><?= Helpers::e(I18n::t('creator_groups.col_links_using')) ?></th><th></th></tr></thead>
      <tbody>
        <?php foreach ($groups as $g): ?>
        <tr>
          <td class="creator" data-label="<?= Helpers::e(I18n::t('creator_groups.col_name')) ?>"><?= Helpers::e($g['name']) ?></td>
          <td class="time-cell" data-label="<?= Helpers::e(I18n::t('creator_groups.col_default_limit')) ?>"><?= $g['default_max_claims'] !== null ? (int) $g['default_max_claims'] : Helpers::e(I18n::t('creator_groups.no_limit_fallback')) ?></td>
          <td class="time-cell" data-label="<?= Helpers::e(I18n::t('creator_groups.col_links_using')) ?>"><?= (int) $g['link_count'] ?></td>
          <td>
            <?php if (Auth::canEdit() || $isDemo): ?>
            <?php if (Auth::canEdit()): ?>
            <a href="creator_groups.php?edit=<?= (int) $g['id'] ?>" style="color:var(--signal); font-size:12px; text-decoration:none; margin-right:10px;"><?= Helpers::e(I18n::t('creator_groups.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('creator_groups.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('creator_groups.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) $g['id'] ?>">
              <button type="submit" style="background:none; border:none; color:var(--danger); font-size:12px; cursor:pointer; padding:0;"><?= Helpers::e(I18n::t('creator_groups.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('creator_groups.panel_edit_group')) : Helpers::e(I18n::t('creator_groups.panel_new_group')) ?></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('creator_groups.col_name')) ?></label>
        <input type="text" name="name" value="<?= Helpers::e($editing['name'] ?? '') ?>" required placeholder="<?= Helpers::e(I18n::t('creator_groups.name_placeholder')) ?>">
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('creator_groups.default_limit_label')) ?></label>
        <input type="number" name="default_max_claims" min="1" value="<?= Helpers::e($editing['default_max_claims'] ?? '') ?>" placeholder="<?= Helpers::e(I18n::t('creator_groups.default_limit_placeholder')) ?>">
      </div>
      <div class="form-actions" style="padding-bottom:0;">
        <?php if ($editing): ?><a href="creator_groups.php" class="btn btn-ghost" style="text-decoration:none;"><?= Helpers::e(I18n::t('creator_groups.cancel')) ?></a><?php endif; ?>
        <button type="submit" class="btn btn-primary"><?= $editing ? Helpers::e(I18n::t('creator_groups.save_changes')) : Helpers::e(I18n::t('creator_groups.create_group')) ?></button>
      </div>
      </fieldset>
    </form>
  </div>
  <?php endif; ?>
</div>

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