<?php

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

use KeyLair\Auth;
use KeyLair\AuditLog;
use KeyLair\CannyReport;
use KeyLair\Csrf;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\ImageUpload;
use KeyLair\Mailer;

// Where to reach the person who submitted a report, if they chose to share
// contact details -- goes to the vendor by email only, never onto the
// public Canny board (see CannyReport::submit(), which never receives it).
const FEEDBACK_CONTACT_EMAIL = 'weber@secret-item-games.com';

Auth::requireEditAccess();
$admin = Auth::user();
$uploadDir = ROOT_PATH . '/public/uploads/feedback';

$errors = [];
$submitted = false;

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

    $type = ($_POST['type'] ?? '') === 'feature' ? 'feature' : 'bug';
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $contactName = trim($_POST['contact_name'] ?? '');
    $contactEmail = trim($_POST['contact_email'] ?? '');

    if ($title === '') {
        $errors[] = I18n::t('bug_reporting.errors.title_required');
    }
    if ($description === '') {
        $errors[] = I18n::t('bug_reporting.errors.description_required');
    }
    if ($contactEmail !== '' && !filter_var($contactEmail, FILTER_VALIDATE_EMAIL)) {
        $errors[] = I18n::t('bug_reporting.errors.invalid_email');
    }
    if (!CannyReport::isConfigured()) {
        $errors[] = I18n::t('bug_reporting.errors.not_configured');
    }

    $screenshotUrls = [];
    if (empty($errors) && !empty($_FILES['screenshots']) && is_array($_FILES['screenshots']['name'])) {
        $count = count($_FILES['screenshots']['name']);
        for ($i = 0; $i < $count; $i++) {
            if ($_FILES['screenshots']['error'][$i] === UPLOAD_ERR_NO_FILE) {
                continue;
            }
            $singleFile = [
                'name' => $_FILES['screenshots']['name'][$i],
                'type' => $_FILES['screenshots']['type'][$i],
                'tmp_name' => $_FILES['screenshots']['tmp_name'][$i],
                'error' => $_FILES['screenshots']['error'][$i],
                'size' => $_FILES['screenshots']['size'][$i],
            ];
            $result = ImageUpload::save($singleFile, $uploadDir);
            if ($result['ok']) {
                $screenshotUrls[] = Helpers::baseUrl() . '/uploads/feedback/' . $result['filename'];
            } else {
                $errors[] = sprintf(I18n::t('bug_reporting.errors.screenshot_prefix'), $result['error']);
            }
        }
    }

    if (empty($errors)) {
        $result = CannyReport::submit($type, $title, $description, $screenshotUrls, $admin['username']);
        if ($result['ok']) {
            AuditLog::log($admin['id'], 'feedback_submitted', "type={$type} title=\"{$title}\"");
            $submitted = true;

            // Contact details are deliberately never sent to CannyReport::submit()
            // above (public board) -- they only ever go here, by email, straight
            // to the vendor. Best-effort: a failed send doesn't fail the report,
            // which already succeeded on the public board.
            if ($contactName !== '' || $contactEmail !== '') {
                $version = \KeyLair\Deployer::currentVersion() ?? 'unknown';
                $channel = \KeyLair\Settings::installedChannel();
                $versionLabel = ($channel !== null && $channel !== 'stable') ? "{$version}-{$channel}" : $version;
                $body = "New Key Lair bug report with contact details.\n\n"
                    . "Type: " . ($type === 'feature' ? 'Feature request' : 'Bug') . "\n"
                    . "Title: {$title}\n"
                    . "Version: {$versionLabel}\n"
                    . "From: " . Helpers::baseUrl() . " (admin: {$admin['username']})\n"
                    . "Contact name: " . ($contactName !== '' ? $contactName : '(not given)') . "\n"
                    . "Contact email: " . ($contactEmail !== '' ? $contactEmail : '(not given)') . "\n\n"
                    . "Description:\n{$description}";
                Mailer::send(FEEDBACK_CONTACT_EMAIL, "[Key Lair Bug Report] {$title}", $body);
            }
        } else {
            $errors[] = $result['error'];
        }
    }
}

$pageTitle = I18n::t('bug_reporting.page_title');
$activeNav = 'bug_reporting';
$extraAdminCss = 'admin-product-editor';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar">
  <h1><?= Helpers::e(I18n::t('bug_reporting.page_title')) ?></h1>
  <a href="https://secret-item-games.canny.io/key-lair" target="_blank" rel="noopener noreferrer" class="btn btn-ghost"><?= Helpers::e(I18n::t('bug_reporting.view_board_button')) ?> &#8599;</a>
</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 ($submitted): ?>
  <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;"><?= Helpers::e(I18n::t('bug_reporting.success.title')) ?></p>
    <p style="color:var(--text-muted); font-size:12.5px; margin:4px 0 0;"><?= Helpers::e(I18n::t('bug_reporting.success.hint')) ?></p>
  </div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data">
  <?= Csrf::field() ?>
  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('bug_reporting.section.report_title')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('bug_reporting.section.report_hint')) ?></p>
    <div class="field">
      <label><?= Helpers::e(I18n::t('bug_reporting.field.type_label')) ?></label>
      <select name="type">
        <option value="bug"><?= Helpers::e(I18n::t('bug_reporting.field.type_bug')) ?></option>
        <option value="feature"><?= Helpers::e(I18n::t('bug_reporting.field.type_feature')) ?></option>
      </select>
    </div>
    <div class="field">
      <label><?= Helpers::e(I18n::t('bug_reporting.field.title_label')) ?></label>
      <input type="text" name="title" maxlength="120" placeholder="<?= Helpers::e(I18n::t('bug_reporting.field.title_placeholder')) ?>" required value="<?= Helpers::e($_POST['title'] ?? '') ?>">
    </div>
    <div class="field">
      <label><?= Helpers::e(I18n::t('bug_reporting.field.description_label')) ?></label>
      <textarea name="description" rows="8" style="width:100%; background:var(--bg-void); border:1px solid var(--line); color:var(--text-primary); font-family:var(--font-body); font-size:13px; padding:10px 12px; border-radius:8px;" placeholder="<?= Helpers::e(I18n::t('bug_reporting.field.description_placeholder')) ?>" required><?= Helpers::e($_POST['description'] ?? '') ?></textarea>
    </div>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('bug_reporting.section.contact_title')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('bug_reporting.section.contact_hint')) ?></p>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('bug_reporting.field.contact_name_label')) ?></label>
        <input type="text" name="contact_name" maxlength="120" placeholder="<?= Helpers::e(I18n::t('bug_reporting.field.optional_placeholder')) ?>" value="<?= Helpers::e($_POST['contact_name'] ?? '') ?>">
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('bug_reporting.field.contact_email_label')) ?></label>
        <input type="email" name="contact_email" maxlength="190" placeholder="<?= Helpers::e(I18n::t('bug_reporting.field.optional_placeholder')) ?>" value="<?= Helpers::e($_POST['contact_email'] ?? '') ?>">
      </div>
    </div>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('bug_reporting.section.screenshots_title')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('bug_reporting.section.screenshots_hint')) ?></p>
    <label class="cover-upload" style="aspect-ratio:auto; padding:16px; cursor:pointer;">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="9" cy="10" r="2"/><path d="M21 16l-5.5-5.5L7 19"/></svg>
      <span id="fb-shots-filename"><?= Helpers::e(I18n::t('bug_reporting.field.screenshots_cta')) ?></span>
      <input type="file" name="screenshots[]" accept="image/jpeg,image/png,image/webp" multiple style="display:none;" onchange="document.getElementById('fb-shots-filename').textContent = <?= json_encode(I18n::t('bug_reporting.js.files_selected'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>.replace('%d', this.files.length);">
    </label>
  </div>

  <div class="form-actions">
    <button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('bug_reporting.field.submit_button')) ?></button>
  </div>
</form>

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