<?php
session_start();
require_once('common.php');
require_once('checklogin.php');
require_once(__DIR__ . '/credits.php');
require_once(__DIR__ . '/paypal_rest.php');

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Is PayPal configured and turned on? Controls the contest payment options.
$paypal_on = pp_is_enabled($pdo);

$errors = [];
$msg = '';
$poet_id = (int)$cPoet['id'];

// Per-edition submission limit (SUB_LIMIT_REGULAR is defined in credits.php
// so every page agrees on the number).
$per_edition_limit = SUB_LIMIT_REGULAR;

// Allowed file types
$stmt = $pdo->prepare("SELECT value FROM sm_settings WHERE var = 'allowed_file_types'");
$stmt->execute();
$filetypes = $stmt->fetchColumn() ?: '.txt, .doc, .docx';

// Open editions — regular issues + contests; poet picks one.
$stmt = $pdo->prepare("SELECT id, edition, is_contest, fee_normal, description FROM sm_editions WHERE is_open = 1 ORDER BY is_contest ASC, edition ASC");
$stmt->execute();
$open_editions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Index by id for fast lookup
$editions_by_id = [];
foreach ($open_editions as $e) {
    $editions_by_id[(int)$e['id']] = $e;
}

$credit_balance = credits_balance($pdo, $poet_id);

if (isset($_POST['submit']) && isset($_POST['csrf_token']) && hash_equals($_SESSION['csrf_token'], (string)$_POST['csrf_token'])) {
    $picked_edition = isset($_POST['edition']) ? (int)$_POST['edition'] : 0;
    if (count($open_editions) === 1 && $picked_edition === 0) {
        $picked_edition = (int)$open_editions[0]['id'];
    }
    if (!isset($editions_by_id[$picked_edition])) {
        $errors['edition'] = "Please select an open edition.";
    } else {
        // Enforce per-edition submission limit (counts both regular and contest entries).
        try {
            $cnt = $pdo->prepare('SELECT COUNT(*) FROM sm_submissions WHERE poetid = :pid AND editionid = :eid');
            $cnt->bindValue(':pid', $poet_id,        PDO::PARAM_INT);
            $cnt->bindValue(':eid', $picked_edition, PDO::PARAM_INT);
            $cnt->execute();
            $existing = (int)$cnt->fetchColumn();
            if ($existing >= $per_edition_limit) {
                $errors['edition'] = "You've reached the limit of {$per_edition_limit} submission"
                    . ($per_edition_limit === 1 ? '' : 's')
                    . " for this edition.";
            }
        } catch (Throwable $e) {
            error_log('new-submission count: ' . $e->getMessage());
        }
    }

    if (empty($_POST['title'])) {
        $errors['title'] = "Title is required.";
    }

    if (empty($_FILES['attachment']['tmp_name'])) {
        $errors['attachment'] = "Please attach your submission file.";
    } else {
        $file_extension = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $allowed_types = array_map('trim', explode(',', $filetypes));
        $allowed_types = array_map(static fn($t) => ltrim(strtolower($t), '.'), $allowed_types);
        if (!in_array($file_extension, $allowed_types, true)) {
            $errors['attachment'] = "Invalid file type. Allowed types: " . htmlspecialchars($filetypes);
        }
    }

    if (empty($_POST['tos']) || $_POST['tos'] != 1) {
        $errors['tos'] = "You must agree to the guidelines.";
    }

    // ---- Payment logic --------------------------------------------------
    // Contest editions charge a per-entry fee, payable by an editor-granted
    // submission credit or through PayPal. Regular editions are free.
    $is_contest_pick = !empty($errors) ? false : !empty($editions_by_id[$picked_edition]['is_contest']);
    $payment_method  = (string)($_POST['payment_method'] ?? '');
    $applied_credit  = false;

    if ($is_contest_pick) {
        if ($payment_method === 'credit') {
            if ($credit_balance <= 0) {
                $errors['payment'] = "You no longer have an available credit. Please refresh and try again.";
            } else {
                $applied_credit = true;
            }
        } elseif ($payment_method === 'paypal') {
            if (!$paypal_on) {
                $errors['payment'] = "PayPal is not available right now. Please use a submission credit.";
            }
            // else: valid — the PayPal redirect is handled below.
        } else {
            $errors['payment'] = "Please choose how to pay for this contest entry.";
        }
    }

    // How much (if anything) goes through PayPal this submission?
    $contest_fee    = $is_contest_pick ? (float)$editions_by_id[$picked_edition]['fee_normal'] : 0.0;
    $fee_via_paypal = ($is_contest_pick && $payment_method === 'paypal') ? $contest_fee : 0.0;
    $paypal_total   = round($fee_via_paypal, 2);
    $needs_paypal   = $paypal_total > 0;

    if (!count($errors)) {
        $uploadOK = false;
        $attachment_name = '';
        if (is_uploaded_file($_FILES['attachment']['tmp_name'])) {
            $attachment_name = md5(time() . $_SERVER['REMOTE_ADDR'] . $poet_id) . '____' . $_FILES['attachment']['name'];
            $uploadOK = move_uploaded_file($_FILES['attachment']['tmp_name'], 'attachments/' . $attachment_name);
        }
        if ($uploadOK && $needs_paypal) {
            // A contest fee is fulfilled only AFTER PayPal capture (see
            // paypal.php). Stash the pending submission until the buyer returns.
            try {
                $currency = pp_settings($pdo)['currency'] ?? 'USD';
                $ins = $pdo->prepare("INSERT INTO sm_paypal_pending
                    (poet_id, title, attachment, bio_comments, edition_id, ip_address,
                     expected_amount, currency, apply_credit, status, created_at)
                    VALUES (:p, :t, :a, :b, :e, :ip, :amt, :cur, :cr, 'created', NOW())");
                $ins->execute([
                    ':p'   => $poet_id,
                    ':t'   => (string)$_POST['title'],
                    ':a'   => $attachment_name,
                    ':b'   => (string)($_POST['bio_comments'] ?? ''),
                    ':e'   => $picked_edition,
                    ':ip'  => (string)($_SERVER['REMOTE_ADDR'] ?? ''),
                    ':amt' => number_format($paypal_total, 2, '.', ''),
                    ':cur' => $currency,
                    ':cr'  => $applied_credit ? 1 : 0,
                ]);
                $pending_id = (int)$pdo->lastInsertId();

                $desc = $site_name . ' contest entry';

                $return_url = rtrim($site_url, '/') . '/paypal.php?action=return&pending=' . $pending_id;
                $cancel_url = rtrim($site_url, '/') . '/paypal.php?action=cancel&pending=' . $pending_id;
                $order = pp_create_order($pdo, $paypal_total, $currency, (string)$pending_id, $return_url, $cancel_url, $desc);
                $pdo->prepare("UPDATE sm_paypal_pending SET paypal_order_id = :oid WHERE id = :id")
                    ->execute([':oid' => $order['id'], ':id' => $pending_id]);
                header('Location: ' . $order['approve']);
                exit;
            } catch (Throwable $e) {
                error_log('new-submission paypal start: ' . $e->getMessage());
                $errors['payment'] = 'We could not start the PayPal payment. Please try again.';
            }
        } elseif ($uploadOK) {
            try {
                $pdo->beginTransaction();
                $ptype = $is_contest_pick ? 'paid' : 'free';
                // sm_submissions.body, ip_address are NOT NULL with no default;
                // the new attachment-only form has no body input, so write empty strings.
                $stmt = $pdo->prepare("INSERT INTO sm_submissions
                                       (poetid, title, editionid, type, body, attachment, bio_comments, date_submitted, status, ip_address, ptype)
                                       VALUES (:poetid, :title, :editionid, 'Poetry', '', :attachment, :bio_comments, NOW(), 0, :ip, :ptype)");
                $stmt->bindValue(':poetid',       $poet_id,                PDO::PARAM_INT);
                $stmt->bindValue(':title',        (string)$_POST['title'], PDO::PARAM_STR);
                $stmt->bindValue(':editionid',    $picked_edition,         PDO::PARAM_INT);
                $stmt->bindValue(':attachment',   $attachment_name,        PDO::PARAM_STR);
                $stmt->bindValue(':bio_comments', (string)($_POST['bio_comments'] ?? ''), PDO::PARAM_STR);
                $stmt->bindValue(':ip',           (string)($_SERVER['REMOTE_ADDR'] ?? ''), PDO::PARAM_STR);
                $stmt->bindValue(':ptype',        $ptype,                  PDO::PARAM_STR);
                $stmt->execute();
                $new_submission_id = (int)$pdo->lastInsertId();

                if ($applied_credit) {
                    $reason = 'Used on submission #' . $new_submission_id . ' to ' . ($editions_by_id[$picked_edition]['edition'] ?? 'contest');
                    credits_grant($pdo, $poet_id, -1, $reason, null, $new_submission_id);
                }

                $pdo->commit();

                $msg = $applied_credit
                    ? "Submission successful — 1 credit applied. (Remaining balance: " . max(0, $credit_balance - 1) . ")"
                    : "Submission successful!";
                unset($_POST);
                $credit_balance = credits_balance($pdo, $poet_id);
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                error_log('new-submission: ' . $e->getMessage());
                $errors['general'] = "There was an issue with your submission. Please try again.";
            }
        } else {
            $errors['attachment'] = "Failed to upload file.";
        }
    }
}

include_once('header.php');
include_once('poets-menu.php');
?>

<div class="container" style="max-width: 660px;">
  <h2><?= isset($_GET['edit']) ? 'Edit Submission' : 'Submit Your Work' ?></h2>
  <?php if (isset($_GET['cancel-payment'])): ?>
    <p class="error" style="color:#b23b3b;">Payment canceled — your contest entry was not submitted.</p>
  <?php elseif (isset($_GET['payment-failed']) || isset($_GET['payment-error'])): ?>
    <p class="error" style="color:#b23b3b;">We couldn't confirm your payment. If you were charged, please contact us and we'll sort it out right away.</p>
  <?php endif; ?>

  <?php if ($msg): ?>
    <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>
  <?php endif; ?>

  <?php if (count($open_editions) === 0): ?>
    <p style="margin-top: 18px;">Submissions are currently closed. Please check back later for upcoming editions.</p>
  <?php else: ?>
    <form method="post" enctype="multipart/form-data" autocomplete="off">
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">

      <div class="form-group">
        <label for="edition">Edition</label>
        <select id="edition" name="edition" required>
          <?php if (count($open_editions) > 1): ?>
            <option value="">— Select an edition or contest —</option>
          <?php endif; ?>
          <?php foreach ($open_editions as $edition):
            $eid     = (int)$edition['id'];
            $is_c    = !empty($edition['is_contest']);
            $fee     = (float)$edition['fee_normal'];
            $label   = $edition['edition'] . ($is_c ? ' — Contest, $' . number_format($fee, 2) : '');
            $selected = (isset($_POST['edition']) && (int)$_POST['edition'] === $eid) || (count($open_editions) === 1) ? 'selected' : '';
          ?>
            <option value="<?= $eid ?>"
                    data-contest="<?= $is_c ? '1' : '0' ?>"
                    data-fee="<?= number_format($fee, 2) ?>"
                    data-name="<?= htmlspecialchars($edition['edition'], ENT_QUOTES, 'UTF-8') ?>"
                    <?= $selected ?>>
              <?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?>
            </option>
          <?php endforeach; ?>
        </select>
        <span class="error"><?= htmlspecialchars($errors['edition'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
      </div>

      <!-- Contest details (shown when a contest with a description is selected) -->
      <?php foreach ($open_editions as $edition):
        if (empty($edition['is_contest']) || trim((string)($edition['description'] ?? '')) === '') continue; ?>
        <div class="contest-desc" data-eid="<?= (int)$edition['id'] ?>" style="display: none; background: #fbf8f1; border: 1px solid var(--c-rule); border-left: 3px solid var(--c-brass); padding: 14px 20px; margin: 0 0 22px; font-size: 14px; line-height: 1.55;">
          <?= $edition['description'] /* admin-authored HTML from the editors' edition tool */ ?>
        </div>
      <?php endforeach; ?>

      <!-- Contest payment block (shown only for contest editions) -->
      <div id="contest-pay" class="form-group" style="display: none; background: #fdf4e8; border: 1px solid #e6c590; border-left: 3px solid #b08542; padding: 14px 18px; margin: 0 0 22px;">
        <div style="font-family: var(--sans); font-size: 11px; letter-spacing: 0.18em; text-transform: uppercase; color: #8c6532; font-weight: 700; margin-bottom: 8px;">
          Contest Entry Fee
        </div>
        <p style="margin: 0 0 10px; font-size: 14px;">
          <span id="contest-fee-display" style="font-size: 18px; font-weight: 600;"></span>
        </p>
        <?php if ($credit_balance > 0): ?>
          <label style="display: block; margin: 6px 0; font-family: var(--serif); text-transform: none; letter-spacing: 0; font-weight: 400; font-size: 14px; color: var(--c-ink);">
            <input type="radio" name="payment_method" value="credit" style="width: auto; margin-right: 8px;" checked>
            <strong>Use 1 submission credit</strong> (you have <?= $credit_balance ?>)
            <span style="color: #5a7d4f; font-style: italic;">— covers the full fee.</span>
          </label>
        <?php endif; ?>
        <label style="display: block; margin: 6px 0; font-family: var(--serif); text-transform: none; letter-spacing: 0; font-weight: 400; font-size: 14px; color: <?= $paypal_on ? 'var(--c-ink)' : 'var(--c-slate)' ?>;">
          <input type="radio" name="payment_method" value="paypal" style="width: auto; margin-right: 8px;" <?= $paypal_on ? '' : 'disabled' ?> <?= ($paypal_on && $credit_balance === 0) ? 'checked' : '' ?>>
          Pay with PayPal<?= $paypal_on ? '' : ' <em>(coming soon)</em>' ?>
        </label>
        <?php if ($credit_balance === 0 && !$paypal_on): ?>
          <p style="margin: 10px 0 0; font-size: 13px; color: var(--c-burgundy); font-style: italic;">
            You don't have any credits yet, and PayPal payment is not currently enabled. Please contact the editors to request a submission credit.
          </p>
        <?php endif; ?>
        <span class="error" style="margin-top: 8px;"><?= htmlspecialchars($errors['payment'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
      </div>

      <div class="form-group">
        <label for="title">Title</label>
        <input id="title" name="title" type="text" required value="<?= isset($_POST['title']) ? htmlspecialchars($_POST['title'], ENT_QUOTES, 'UTF-8') : '' ?>">
        <span class="error"><?= htmlspecialchars($errors['title'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
      </div>

      <div class="form-group">
        <label for="attachment">Attach your submission</label>
        <input id="attachment" name="attachment" type="file" accept="<?= htmlspecialchars($filetypes, ENT_QUOTES, 'UTF-8') ?>" required>
        <p style="margin: 4px 0 0; font-size: 12px; color: var(--c-slate); font-style: italic;">Accepted file types: <?= htmlspecialchars($filetypes, ENT_QUOTES, 'UTF-8') ?></p>
        <span class="error"><?= htmlspecialchars($errors['attachment'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
      </div>

      <div class="form-group">
        <label for="bio_comments">Comments <span style="color: var(--c-slate); font-weight: 400; text-transform: none; letter-spacing: 0; font-style: italic;">(optional)</span></label>
        <textarea id="bio_comments" name="bio_comments" rows="5"><?= isset($_POST['bio_comments']) ? htmlspecialchars($_POST['bio_comments'], ENT_QUOTES, 'UTF-8') : '' ?></textarea>
      </div>

      <div class="form-group" style="background: var(--c-frost); border: 1px solid var(--c-rule); padding: 14px 18px; margin-top: 24px;">
        <label style="display: flex; align-items: flex-start; gap: 12px; margin: 0; text-transform: none; letter-spacing: 0; color: var(--c-ink); font-family: var(--serif); font-size: 15px; font-weight: 400;">
          <input name="tos" type="checkbox" value="1" required <?= isset($_POST['tos']) && $_POST['tos'] == 1 ? 'checked' : '' ?> style="margin-top: 4px; width: auto;">
          <span>I have read and agree to the <a href="poets-guidelines.php" target="_blank" rel="noopener">submission guidelines</a>.</span>
        </label>
        <span class="error"><?= htmlspecialchars($errors['tos'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
      </div>

      <input name="submit" value="Submit" type="submit" class="button-primary">

      <?php if (!empty($errors['general'])): ?>
        <span class="error"><?= htmlspecialchars($errors['general'], ENT_QUOTES, 'UTF-8') ?></span>
      <?php endif; ?>
    </form>

    <script>
    (function () {
      const sel   = document.getElementById('edition');
      const box   = document.getElementById('contest-pay');
      const fee   = document.getElementById('contest-fee-display');
      const descs = document.querySelectorAll('.contest-desc');
      function update() {
        const opt = sel.options[sel.selectedIndex];
        const isContest = !!opt && opt.dataset.contest === '1';
        descs.forEach(function (d) {
          d.style.display = (isContest && d.dataset.eid === opt.value) ? 'block' : 'none';
        });
        if (!isContest) {
          box.style.display = 'none';
          return;
        }
        box.style.display = 'block';
        fee.textContent = '$' + opt.dataset.fee + ' (' + opt.dataset.name + ')';
      }
      sel.addEventListener('change', update);
      update();
    })();
    </script>
  <?php endif; ?>
</div>

<?php include_once('footer.php'); ?>
