<?php

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

use KeyLair\Auth;
use KeyLair\Csrf;
use KeyLair\Database;
use KeyLair\Helpers;
use KeyLair\ClaimLinkFactory;
use KeyLair\I18n;
use KeyLair\UserFactory;

// Always creates a brand new user -- picking an existing one instead
// belongs on New Claim Link (see its own User picker), and editing an
// existing user's name/email is done inline, straight in the table, on
// the Users page itself (mass-editable there, several at once). This
// page exists for the opposite direction: starting from "I have a new
// creator", not "I have a link to hand out".
Auth::requireEditAccess();
$pdo = Database::connection();

$campaigns = $pdo->query('SELECT * FROM campaigns WHERE status = "active" ORDER BY name ASC')->fetchAll();
$creatorGroups = $pdo->query('SELECT * FROM creator_groups ORDER BY name ASC')->fetchAll();
$products = $pdo->query('SELECT * FROM products WHERE status = "active" ORDER BY name ASC')->fetchAll();

$created = null;
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::requireValid();

    $campaignId = !empty($_POST['campaign_id']) ? (int) $_POST['campaign_id'] : null;
    $creatorGroupId = !empty($_POST['creator_group_id']) ? (int) $_POST['creator_group_id'] : null;
    $expiresAtRaw = trim($_POST['expires_at'] ?? '');
    $expiresAt = null;
    if ($expiresAtRaw !== '') {
        $parsedExpiry = DateTime::createFromFormat('Y-m-d', $expiresAtRaw);
        if (!$parsedExpiry || $parsedExpiry->format('Y-m-d') !== $expiresAtRaw) {
            $errors[] = I18n::t('user_form.error_expires_invalid');
        } else {
            $expiresAt = $expiresAtRaw . ' 23:59:59';
        }
    }
    $selectedProducts = $_POST['products'] ?? [];
    $overrides = $_POST['max_claims_override'] ?? [];
    if (empty($selectedProducts)) {
        $errors[] = I18n::t('user_form.error_select_product');
    }

    // Validated before UserFactory::create() runs below -- a failed
    // product selection shouldn't leave a stray user row with no link.
    if (empty($errors)) {
        $productOverrides = [];
        foreach ($selectedProducts as $productId => $checked) {
            $productId = (int) $productId;
            $overrideRaw = trim($overrides[$productId] ?? '');
            $productOverrides[$productId] = $overrideRaw === '' ? null : max(1, (int) $overrideRaw);
        }

        $newUserId = UserFactory::create($_POST['name'] ?? null, $_POST['email'] ?? null);
        $result = ClaimLinkFactory::create($campaignId, $newUserId, $creatorGroupId, $expiresAt, $productOverrides);
        if ($result['ok']) {
            $created = Helpers::baseUrl() . '/claim/' . $result['token'];
        } else {
            // The user row still exists at this point (see the comment
            // above the User picker on claim_link_form.php for why
            // UserFactory never rolls back) -- it just has no claim link
            // yet, same as any other user created without one.
            $errors[] = $result['error'];
        }
    }
}

$pageTitle = $editingUser ? I18n::t('user_form.title_edit') : I18n::t('user_form.title_new');
$activeNav = 'users';
$extraAdminCss = 'admin-product-editor';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar"><h1><?= $editingUser ? Helpers::e(I18n::t('user_form.heading_edit')) : Helpers::e(I18n::t('user_form.heading_new')) ?></h1></div>

<?php if (!empty($errors)): ?>
  <div class="form-section" style="border-color:var(--danger); margin-bottom:16px;">
    <?php foreach ($errors as $err): ?><p style="color:var(--danger); font-size:13px; margin:0;"><?= Helpers::e($err) ?></p><?php endforeach; ?>
  </div>
<?php endif; ?>

<?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('user_form.success_created')) ?></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('user_form.copy_button_copied'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>;"><?= Helpers::e(I18n::t('user_form.copy_button')) ?></button>
    </div>
    <p style="margin:12px 0 0;"><a href="users.php" style="color:var(--signal); font-size:13px;"><?= Helpers::e(I18n::t('user_form.view_all_users')) ?></a> · <a href="user_form.php" style="color:var(--signal); font-size:13px;"><?= Helpers::e(I18n::t('user_form.create_another')) ?></a></p>
  </div>
<?php elseif ($editingUser): ?>
<form method="post" class="form-shell">
  <?= Csrf::field() ?>
  <input type="hidden" name="id" value="<?= (int) $userId ?>">
  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('user_form.section_user')) ?></p>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('user_form.name_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('user_form.optional_suffix')) ?></span></label>
        <input type="text" name="name" placeholder="<?= Helpers::e(I18n::t('user_form.name_placeholder')) ?>" value="<?= Helpers::e($editingUser['name'] ?? '') ?>">
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('user_form.email_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('user_form.optional_suffix')) ?></span></label>
        <input type="email" name="email" placeholder="<?= Helpers::e(I18n::t('user_form.email_placeholder')) ?>" value="<?= Helpers::e($editingUser['email'] ?? '') ?>">
      </div>
    </div>
  </div>
  <div class="form-actions">
    <a href="users.php" class="btn btn-ghost" style="text-decoration:none;"><?= Helpers::e(I18n::t('user_form.cancel')) ?></a>
    <button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('user_form.save_changes')) ?></button>
  </div>
</form>
<?php elseif (empty($products)): ?>
  <div class="panel">
    <p style="color:var(--text-muted); font-size:13px;">
      <?= sprintf(Helpers::e(I18n::t('user_form.no_active_product')), '<a href="product_form.php" style="color:var(--signal);">' . Helpers::e(I18n::t('user_form.create_product_link')) . '</a>') ?>
    </p>
  </div>
<?php else: ?>
<form method="post" class="form-shell">
  <?= Csrf::field() ?>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('user_form.section_user')) ?></p>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('user_form.name_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('user_form.optional_suffix')) ?></span></label>
        <input type="text" name="name" placeholder="<?= Helpers::e(I18n::t('user_form.name_placeholder')) ?>">
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('user_form.email_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('user_form.optional_suffix')) ?></span></label>
        <input type="email" name="email" placeholder="<?= Helpers::e(I18n::t('user_form.email_placeholder')) ?>">
      </div>
    </div>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('user_form.section_claim_link')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('user_form.claim_link_hint')) ?></p>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('user_form.campaign_label')) ?> <span style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('user_form.optional_suffix')) ?></span></label>
        <select name="campaign_id">
          <option value=""><?= Helpers::e(I18n::t('user_form.no_campaign_option')) ?></option>
          <?php foreach ($campaigns as $c): ?>
            <option value="<?= (int) $c['id'] ?>"><?= Helpers::e($c['name']) ?> <?= Helpers::e(sprintf(I18n::t('user_form.campaign_default_limit'), (int) $c['default_max_claims'])) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('user_form.creator_group_label')) ?></label>
        <select name="creator_group_id">
          <option value=""><?= Helpers::e(I18n::t('user_form.none_option')) ?></option>
          <?php foreach ($creatorGroups as $g): ?>
            <option value="<?= (int) $g['id'] ?>"><?= Helpers::e($g['name']) ?><?= $g['default_max_claims'] !== null ? Helpers::e(sprintf(I18n::t('user_form.group_limit_suffix'), (int) $g['default_max_claims'])) : '' ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('user_form.expires_label')) ?></label>
        <div style="display:flex; gap:8px; align-items:center;">
          <input type="date" name="expires_at" id="expires-at-input" style="-webkit-appearance:none; appearance:none; height:41px !important; box-sizing:border-box; flex:1;">
          <button type="button" class="btn btn-ghost" style="flex-shrink:0; padding:10px 14px;" onclick="document.getElementById('expires-at-input').value='';"><?= Helpers::e(I18n::t('user_form.clear_button')) ?></button>
        </div>
      </div>
    </div>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('user_form.section_products')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('user_form.products_hint')) ?></p>
    <?php foreach ($products as $p): ?>
      <div style="display:flex; align-items:center; gap:12px; padding:10px 0; border-bottom:1px solid var(--line);">
        <label style="display:flex; align-items:center; gap:8px; flex:1; cursor:pointer; margin:0;">
          <input type="checkbox" name="products[<?= (int) $p['id'] ?>]" value="1" style="width:auto;">
          <span style="font-size:13.5px; color:var(--text-primary);"><?= Helpers::e($p['name']) ?></span>
        </label>
        <input type="number" name="max_claims_override[<?= (int) $p['id'] ?>]" min="1" placeholder="<?= Helpers::e(I18n::t('user_form.max_claims_placeholder')) ?>" style="width:100px; margin:0;">
      </div>
    <?php endforeach; ?>
  </div>

  <div class="form-actions">
    <a href="users.php" class="btn btn-ghost" style="text-decoration:none;"><?= Helpers::e(I18n::t('user_form.cancel')) ?></a>
    <button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('user_form.create_button')) ?></button>
  </div>
</form>
<?php endif; ?>

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