<?php

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

use KeyLair\Auth;
use KeyLair\AuditLog;
use KeyLair\Csrf;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\ImageUpload;
use KeyLair\Platform;

Auth::requireLogin();
$admin = Auth::user();
$isDemo = $admin['role'] === 'demo';
$uploadDir = ROOT_PATH . '/public/uploads/platforms';

$flash = null;

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

    if ($action === 'create') {
        $label = trim($_POST['label'] ?? '');

        if ($label === '') {
            $flash = ['type' => 'error', 'message' => I18n::t('platforms.flash.name_required')];
        } else {
            try {
                Platform::create($label);
                AuditLog::log($admin['id'], 'platform_created', $label);
                Helpers::redirect('platforms.php');
            } catch (\PDOException $e) {
                $flash = ['type' => 'error', 'message' => I18n::t('platforms.flash.duplicate_name')];
            }
        }
    } elseif ($action === 'delete') {
        $slug = $_POST['slug'] ?? '';
        if (count(Platform::all()) <= 1) {
            $flash = ['type' => 'error', 'message' => I18n::t('platforms.flash.need_at_least_one')];
        } elseif (Platform::exists($slug)) {
            $label = Platform::label($slug);
            $oldIcon = Platform::iconPath($slug);
            Platform::delete($slug);
            if ($oldIcon) {
                @unlink(ROOT_PATH . '/public' . $oldIcon);
            }
            AuditLog::log($admin['id'], 'platform_deleted', $label);
            Helpers::redirect('platforms.php');
        }
    } elseif ($action === 'upload_icon') {
        $slug = $_POST['slug'] ?? '';
        if (!Platform::exists($slug)) {
            $flash = ['type' => 'error', 'message' => I18n::t('platforms.flash.unknown_platform')];
        } else {
            $result = ImageUpload::save($_FILES['icon_file'] ?? [], $uploadDir);
            if ($result['ok']) {
                $old = Platform::iconPath($slug);
                Platform::setIcon($slug, '/uploads/platforms/' . $result['filename']);
                if ($old) {
                    @unlink(ROOT_PATH . '/public' . $old);
                }
                AuditLog::log($admin['id'], 'platform_icon_uploaded', $slug);
                Helpers::redirect('platforms.php');
            } else {
                $flash = ['type' => 'error', 'message' => I18n::t('platforms.flash.icon_error_prefix') . $result['error']];
            }
        }
    } elseif ($action === 'delete_icon') {
        $slug = $_POST['slug'] ?? '';
        if (Platform::exists($slug)) {
            $old = Platform::iconPath($slug);
            Platform::clearIcon($slug);
            if ($old) {
                @unlink(ROOT_PATH . '/public' . $old);
            }
            AuditLog::log($admin['id'], 'platform_icon_removed', $slug);
            Helpers::redirect('platforms.php');
        }
    } elseif ($action === 'update_key_format') {
        $slug = $_POST['slug'] ?? '';
        $pattern = trim($_POST['key_format_pattern'] ?? '');
        if (!Platform::exists($slug)) {
            $flash = ['type' => 'error', 'message' => I18n::t('platforms.flash.unknown_platform')];
        } elseif (!Platform::isValidKeyFormatPattern($pattern)) {
            $flash = ['type' => 'error', 'message' => I18n::t('platforms.flash.invalid_regex')];
        } else {
            Platform::setKeyFormatPattern($slug, $pattern);
            AuditLog::log($admin['id'], 'platform_key_format_updated', $slug);
            Helpers::redirect('platforms.php');
        }
    }
}

$platforms = Platform::all();

$pageTitle = I18n::t('platforms.page_title');
$activeNav = 'platforms';
$extraAdminCss = 'admin-product-editor';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar"><h1><?= Helpers::e(I18n::t('platforms.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="panel">
    <p class="panel-title"><?= Helpers::e(I18n::t('platforms.all_platforms_title')) ?></p>
    <table>
      <thead><tr><th><?= Helpers::e(I18n::t('platforms.col_icon')) ?></th><th><?= Helpers::e(I18n::t('platforms.col_name')) ?></th><th><?= Helpers::e(I18n::t('platforms.col_slug')) ?></th><th><?= Helpers::e(I18n::t('platforms.col_keys')) ?></th><th><?= Helpers::e(I18n::t('platforms.col_key_format')) ?></th><th></th></tr></thead>
      <tbody>
        <?php foreach ($platforms as $p): $keyCount = Platform::keyCount($p['slug']); ?>
        <tr>
          <td style="width:32px;">
            <span style="display:inline-flex; width:22px; height:22px; color:var(--text-muted);"><?= Platform::icon($p['slug']) ?></span>
          </td>
          <td class="creator" data-label="<?= Helpers::e(I18n::t('platforms.col_name')) ?>"><?= Helpers::e($p['label']) ?></td>
          <td class="time-cell" data-label="<?= Helpers::e(I18n::t('platforms.col_slug')) ?>"><?= Helpers::e($p['slug']) ?></td>
          <td class="time-cell" data-label="<?= Helpers::e(I18n::t('platforms.col_keys')) ?>"><?= $keyCount ?></td>
          <td data-label="<?= Helpers::e(I18n::t('platforms.col_key_format')) ?>">
            <?php if (Auth::canEdit() || $isDemo): ?>
            <form method="post" style="display:flex; gap:6px; align-items:center;">
              <?= Csrf::field() ?>
              <input type="hidden" name="form_action" value="update_key_format">
              <input type="hidden" name="slug" value="<?= Helpers::e($p['slug']) ?>">
              <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0; display:flex; gap:6px; align-items:center; flex:1;">
                <input type="text" name="key_format_pattern" value="<?= Helpers::e($p['key_format_pattern'] ?? '') ?>" placeholder="<?= Helpers::e(I18n::t('platforms.any_format_accepted')) ?>" class="key-format-input" style="width:170px; max-width:100%; background:var(--bg-void); border:1px solid var(--line); color:var(--text-primary); font-family:var(--font-mono); font-size:11.5px; padding:5px 8px; border-radius:6px;">
                <button type="submit" class="key-format-save" style="background:none; border:none; color:var(--signal); font-size:12px; cursor:pointer; padding:0; flex-shrink:0;"><?= Helpers::e(I18n::t('platforms.save')) ?></button>
              </fieldset>
            </form>
            <?php else: ?>
              <span class="time-cell"><?= $p['key_format_pattern'] ? Helpers::e($p['key_format_pattern']) : Helpers::e(I18n::t('platforms.any_format_accepted')) ?></span>
            <?php endif; ?>
          </td>
          <td style="white-space:nowrap;">
            <?php if (Auth::canEdit() || $isDemo): ?>
            <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0; display:contents;">
            <label class="icon-upload-label" style="color:var(--text-muted); font-size:12px; cursor:pointer; margin-right:10px;">
              <?= $p['icon_path'] ? Helpers::e(I18n::t('platforms.replace_icon')) : Helpers::e(I18n::t('platforms.upload_icon')) ?>
              <input type="file" accept="image/jpeg,image/png,image/webp" style="display:none;" onchange="document.getElementById('icon-upload-slug').value='<?= Helpers::e($p['slug']) ?>'; document.getElementById('icon-upload-file').files=this.files; document.getElementById('icon-upload-form').submit();">
            </label>
            <?php if ($p['icon_path']): ?>
            <form method="post" style="display:inline;">
              <?= Csrf::field() ?>
              <input type="hidden" name="form_action" value="delete_icon">
              <input type="hidden" name="slug" value="<?= Helpers::e($p['slug']) ?>">
              <button type="submit" style="background:none; border:none; color:var(--text-muted); font-size:12px; cursor:pointer; padding:0; margin-right:10px;"><?= Helpers::e(I18n::t('platforms.remove_icon')) ?></button>
            </form>
            <?php endif; ?>
            <form method="post" style="display:inline;" onsubmit="return confirm(<?= json_encode(sprintf(I18n::t('platforms.delete_confirm_js'), $keyCount), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
              <?= Csrf::field() ?>
              <input type="hidden" name="form_action" value="delete">
              <input type="hidden" name="slug" value="<?= Helpers::e($p['slug']) ?>">
              <button type="submit" style="background:none; border:none; color:var(--danger); font-size:12px; cursor:pointer; padding:0;"><?= Helpers::e(I18n::t('platforms.delete')) ?></button>
            </form>
            </fieldset>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <div style="margin-top:14px; background:var(--bg-panel-2); border:1px solid var(--line); border-left:3px solid var(--signal-dim); border-radius:var(--radius-md); padding:14px 16px;">
      <p style="display:flex; align-items:center; gap:7px; font-size:12.5px; font-weight:600; color:var(--text-primary); margin:0 0 8px;">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--signal)" stroke-width="2" style="flex-shrink:0;"><circle cx="12" cy="12" r="9"/><path d="M12 16v-5"/><circle cx="12" cy="8" r="0.5" fill="var(--signal)"/></svg>
        <?= Helpers::e(I18n::t('platforms.reference_title')) ?>
      </p>
      <p style="color:var(--text-muted); font-size:12px; line-height:1.6; margin:0 0 12px;">
        <?= Helpers::e(I18n::t('platforms.reference_intro')) ?>
      </p>
      <div style="display:flex; flex-direction:column; gap:10px;">
        <div>
          <p style="margin:0 0 3px; font-size:11.5px; font-weight:600; color:var(--text-primary);"><?= Helpers::e(I18n::t('platforms.reference_xbox_title')) ?></p>
          <code style="display:block; font-size:11.5px; color:var(--signal); background:var(--bg-void); border:1px solid var(--line); border-radius:6px; padding:6px 9px; white-space:pre-wrap; word-break:break-all;">[BCDFGHJKMNPQRTVWXYZ2346789]{5}(-[BCDFGHJKMNPQRTVWXYZ2346789]{5}){4}</code>
          <p style="margin:3px 0 0; font-size:11px; color:var(--text-faint);"><?= Helpers::e(I18n::t('platforms.reference_xbox_desc')) ?></p>
        </div>
        <div>
          <p style="margin:0 0 3px; font-size:11.5px; font-weight:600; color:var(--text-primary);"><?= Helpers::e(I18n::t('platforms.reference_playstation_title')) ?></p>
          <code style="display:block; font-size:11.5px; color:var(--signal); background:var(--bg-void); border:1px solid var(--line); border-radius:6px; padding:6px 9px; white-space:pre-wrap; word-break:break-all;">[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}</code>
          <p style="margin:3px 0 0; font-size:11px; color:var(--text-faint);"><?= Helpers::e(I18n::t('platforms.reference_playstation_desc')) ?></p>
        </div>
        <div>
          <p style="margin:0 0 3px; font-size:11.5px; font-weight:600; color:var(--text-primary);"><?= Helpers::e(I18n::t('platforms.reference_nintendo_title')) ?></p>
          <code style="display:block; font-size:11.5px; color:var(--signal); background:var(--bg-void); border:1px solid var(--line); border-radius:6px; padding:6px 9px; white-space:pre-wrap; word-break:break-all;">[A-HJ-NP-Y0-9]{16}</code>
          <p style="margin:3px 0 0; font-size:11px; color:var(--text-faint);"><?= Helpers::e(I18n::t('platforms.reference_nintendo_desc')) ?></p>
        </div>
        <div>
          <p style="margin:0 0 3px; font-size:11.5px; font-weight:600; color:var(--text-primary);"><?= Helpers::e(I18n::t('platforms.reference_steam_title')) ?></p>
          <p style="margin:0; font-size:11px; color:var(--text-faint);"><?= Helpers::e(I18n::t('platforms.reference_steam_desc')) ?></p>
        </div>
      </div>
    </div>
  </div>

  <?php if (Auth::canEdit() || $isDemo): ?>
  <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
  <form method="post" enctype="multipart/form-data" id="icon-upload-form" style="display:none;">
    <?= Csrf::field() ?>
    <input type="hidden" name="form_action" value="upload_icon">
    <input type="hidden" name="slug" id="icon-upload-slug">
    <input type="file" name="icon_file" id="icon-upload-file">
  </form>
  </fieldset>
  <?php endif; ?>

  <?php if (Auth::canEdit() || $isDemo): ?>
  <div class="panel" style="max-width:480px;">
    <p class="panel-title"><?= Helpers::e(I18n::t('platforms.new_platform_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">
        <label><?= Helpers::e(I18n::t('platforms.field_template')) ?></label>
        <select id="platform-template" onchange="
          var v = this.value;
          var input = document.getElementById('platform-label');
          if (v === '__custom__') {
            input.value = '';
            input.readOnly = false;
            input.focus();
          } else if (v !== '') {
            input.value = v;
            input.readOnly = true;
          }
        ">
          <option value=""><?= Helpers::e(I18n::t('platforms.choose_template')) ?></option>
          <optgroup label="PC">
            <option value="Steam">Steam</option>
            <option value="GOG">GOG</option>
            <option value="Epic Games Store">Epic Games Store</option>
            <option value="Itch">Itch</option>
          </optgroup>
          <optgroup label="Xbox">
            <option value="Xbox/Microsoft Store">Xbox/Microsoft Store</option>
          </optgroup>
          <optgroup label="Nintendo Switch">
            <option value="Nintendo Switch US">Nintendo Switch US</option>
            <option value="Nintendo Switch EU">Nintendo Switch EU</option>
            <option value="Nintendo Switch AU">Nintendo Switch AU</option>
            <option value="Nintendo Switch SE">Nintendo Switch SE</option>
            <option value="Nintendo Switch JP">Nintendo Switch JP</option>
            <option value="Nintendo Switch KR">Nintendo Switch KR</option>
            <option value="Nintendo Switch HK">Nintendo Switch HK</option>
            <option value="Nintendo Switch TW">Nintendo Switch TW</option>
          </optgroup>
          <optgroup label="Nintendo Switch 2">
            <option value="Nintendo Switch 2 US">Nintendo Switch 2 US</option>
            <option value="Nintendo Switch 2 EU">Nintendo Switch 2 EU</option>
            <option value="Nintendo Switch 2 AU">Nintendo Switch 2 AU</option>
            <option value="Nintendo Switch 2 SE">Nintendo Switch 2 SE</option>
            <option value="Nintendo Switch 2 JP">Nintendo Switch 2 JP</option>
            <option value="Nintendo Switch 2 KR">Nintendo Switch 2 KR</option>
            <option value="Nintendo Switch 2 HK">Nintendo Switch 2 HK</option>
            <option value="Nintendo Switch 2 TW">Nintendo Switch 2 TW</option>
          </optgroup>
          <optgroup label="PlayStation 4">
            <option value="PlayStation 4 SIEA">PlayStation 4 SIEA</option>
            <option value="PlayStation 4 SIEE">PlayStation 4 SIEE</option>
            <option value="PlayStation 4 SIEJA-Asia">PlayStation 4 SIEJA-Asia</option>
            <option value="PlayStation 4 SIEJA-Japan">PlayStation 4 SIEJA-Japan</option>
            <option value="PlayStation 4 Korea">PlayStation 4 Korea</option>
          </optgroup>
          <optgroup label="PlayStation 5">
            <option value="PlayStation 5 SIEA">PlayStation 5 SIEA</option>
            <option value="PlayStation 5 SIEE">PlayStation 5 SIEE</option>
            <option value="PlayStation 5 SIEJA-Asia">PlayStation 5 SIEJA-Asia</option>
            <option value="PlayStation 5 SIEJA-Japan">PlayStation 5 SIEJA-Japan</option>
            <option value="PlayStation 5 Korea">PlayStation 5 Korea</option>
          </optgroup>
          <option value="__custom__"><?= Helpers::e(I18n::t('platforms.custom_option')) ?></option>
        </select>
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('platforms.col_name')) ?></label>
        <input type="text" name="label" id="platform-label" placeholder="<?= Helpers::e(I18n::t('platforms.name_placeholder')) ?>" maxlength="64" required>
      </div>
      <div class="form-actions" style="padding-bottom:0;">
        <button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('platforms.add_platform')) ?></button>
      </div>
      </fieldset>
    </form>
  </div>
  <?php endif; ?>

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