<?php
declare(strict_types=1);

$config = require __DIR__ . '/lib/config.php';
require __DIR__ . '/lib/helpers.php';
require __DIR__ . '/lib/i18n.php';
require __DIR__ . '/lib/db.php';
require __DIR__ . '/lib/auth.php';
require __DIR__ . '/lib/layout.php';

$lang = px_lang();
$t = px_strings($lang);
$db = paxelle_db($config);

px_require_user('/upload');          // uploading requires a viewer account
$user = px_current_user($db);

$errors = [];
$done = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!px_csrf_check($_POST['csrf'] ?? null)) {
        $errors[] = $t['err_csrf'];
    }

    $town = trim((string) ($_POST['town'] ?? ($user['town'] ?? '')));
    $consent = !empty($_POST['consent']);

    if ($town === '') {
        $errors[] = $t['err_town'];
    }
    if (!$consent) {
        $errors[] = $t['err_consent'];
    }

    $file = $_FILES['clip'] ?? null;
    if (!$file || ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        $errors[] = $t['err_file'];
    } elseif ($file['error'] === UPLOAD_ERR_INI_SIZE || $file['error'] === UPLOAD_ERR_FORM_SIZE) {
        $errors[] = $t['err_size'];
    } elseif ($file['error'] !== UPLOAD_ERR_OK) {
        $errors[] = $t['err_generic'];
    } elseif ($file['size'] > $config['max_bytes']) {
        $errors[] = $t['err_size'];
    } else {
        $ext = strtolower(pathinfo((string) $file['name'], PATHINFO_EXTENSION));
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($file['tmp_name']) ?: '';
        if (!in_array($ext, $config['allowed_ext'], true)
            || !in_array($mime, $config['allowed_mime'], true)) {
            $errors[] = $t['err_type'];
        }
    }

    if (!$errors) {
        $stmt = $db->prepare(
            "SELECT COUNT(*) FROM submissions WHERE user_id = ? AND created_at > datetime('now','-1 hour')"
        );
        $stmt->execute([(int) $user['id']]);
        if ((int) $stmt->fetchColumn() >= $config['rate_per_hour']) {
            $errors[] = $t['err_rate'];
        }
    }

    if (!$errors) {
        if (!is_dir($config['quarantine'])) {
            mkdir($config['quarantine'], 0750, true);
        }
        $stored = date('Ymd-His') . '-' . bin2hex(random_bytes(6)) . '.' . $ext;
        $dest = $config['quarantine'] . '/' . $stored;
        if (!move_uploaded_file($file['tmp_name'], $dest)) {
            $errors[] = $t['err_generic'];
        } else {
            @chmod($dest, 0640);
            $ins = $db->prepare(
                "INSERT INTO submissions
                   (created_at, user_id, name, town, stored_name, orig_name, mime, bytes, ip, status)
                 VALUES (datetime('now'), ?, ?, ?, ?, ?, ?, ?, ?, 'pending')"
            );
            $ins->execute([
                (int) $user['id'],
                $user['name'] ?? null,
                $town,
                $stored,
                substr((string) $file['name'], 0, 255),
                $mime,
                (int) $file['size'],
                px_client_ip(),
            ]);
            // Remember their town for next time.
            if (empty($user['town'])) {
                $db->prepare("UPDATE users SET town = ? WHERE id = ?")
                   ->execute([$town, (int) $user['id']]);
            }
            $done = true;
        }
    }
}

px_header($t, $lang, $config, 'upload', $user);
?>
<section class="up-hero">
  <div class="wrap up-hero-grid">
    <div>
      <h1 class="glitch" data-text="<?= e($t['up_title']) ?>"><?= e($t['up_title']) ?></h1>
      <p class="hero-sub"><?= e($t['up_sub']) ?></p>
    </div>
    <img class="up-avatar" src="/assets/img/paxelle-avatar-512.png" alt="" width="200" height="200">
  </div>
</section>

<section class="how">
  <div class="wrap">
    <h2><?= e($t['how_h']) ?></h2>
    <ol class="steps">
      <li><span class="num">1</span><h3><?= e($t['how1_h']) ?></h3><p><?= e($t['how1_p']) ?></p></li>
      <li><span class="num">2</span><h3><?= e($t['how2_h']) ?></h3><p><?= e($t['how2_p']) ?></p></li>
      <li><span class="num">3</span><h3><?= e($t['how3_h']) ?></h3><p><?= e($t['how3_p']) ?></p></li>
    </ol>
  </div>
</section>

<section class="form-wrap">
  <div class="wrap narrow">
  <?php if ($done): ?>
    <div class="card thanks">
      <h2><?= e($t['thanks_h']) ?></h2>
      <p><?= e($t['thanks_p']) ?></p>
      <div class="hero-cta" style="justify-content:center">
        <a class="btn btn-primary" href="/upload"><?= e($t['send_another']) ?></a>
        <a class="btn btn-ghost" href="/account/"><?= e($t['nav_myuploads']) ?></a>
      </div>
    </div>
  <?php else: ?>
    <?php if ($errors): ?>
      <div class="errors"><?php foreach ($errors as $err): ?><p><?= e($err) ?></p><?php endforeach; ?></div>
    <?php endif; ?>
    <p class="signed-as muted"><?= e($t['my_hi']) ?>, <strong><?= e($user['name'] ?: $user['email']) ?></strong>.</p>
    <form class="card upload-form" method="post" action="/upload" enctype="multipart/form-data">
      <input type="hidden" name="csrf" value="<?= e(px_csrf_token()) ?>">
      <label class="field">
        <span><?= e($t['f_town']) ?> *</span>
        <input type="text" name="town" maxlength="120" required
               value="<?= e($_POST['town'] ?? ($user['town'] ?? '')) ?>">
      </label>
      <label class="field file">
        <span><?= e($t['f_file']) ?> *</span>
        <input type="file" name="clip" accept="video/*,image/*" required>
      </label>
      <label class="consent">
        <input type="checkbox" name="consent" value="1" required>
        <span><?= e($t['f_consent']) ?></span>
      </label>
      <button class="btn btn-primary big" type="submit"><?= e($t['f_submit']) ?></button>
      <p class="micro"><?= e($t['f_consent_micro']) ?></p>
    </form>
  <?php endif; ?>
  </div>
</section>
<?php
px_footer($t, $config);
