<?php
require_once('../common.php');
require_once('checklogin.php');
require_once('../functions.php'); // Include the file that has countPoemByEdition function

// CSRF protection: Generate token if not set
if (!isset($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}

// Managing editions is an administrator action.
$is_admin = in_array($_SESSION['editor_type'] ?? '', ['admin', 'superadmin'], true);

// Handle form submission for adding/editing an edition
if ($is_admin && isset($_POST['submit']) && isset($_POST['token']) && $_POST['token'] === $_SESSION['token']) {
    $edition     = isset($_POST['edition']) ? $_POST['edition'] : '';
    $description = isset($_POST['description']) ? $_POST['description'] : '';
    $is_open     = isset($_POST['is_open']) ? 1 : 0;
    $is_contest  = isset($_POST['is_contest']) ? 1 : 0;
    $fee_normal  = $is_contest ? max(0, (float)($_POST['fee_normal'] ?? 0)) : 0.00;
    $id          = isset($_POST['id']) ? (int)$_POST['id'] : 0;

    if ($id === 0) {
        $query = "INSERT INTO sm_editions (editorid, edition, description, is_open, is_contest, fee_normal, date_added)
                  VALUES (:editorid, :edition, :description, :is_open, :is_contest, :fee_normal, NOW())";
        $stmt = $pdo->prepare($query);
        $stmt->bindValue(':editorid',    (int)$_SESSION['editor_id'], PDO::PARAM_INT);
        $stmt->bindValue(':edition',     $edition,     PDO::PARAM_STR);
        $stmt->bindValue(':description', $description, PDO::PARAM_STR);
        $stmt->bindValue(':is_open',     $is_open,     PDO::PARAM_INT);
        $stmt->bindValue(':is_contest',  $is_contest,  PDO::PARAM_INT);
        $stmt->bindValue(':fee_normal',  number_format($fee_normal, 2, '.', ''), PDO::PARAM_STR);
        if ($stmt->execute()) { $msg = 'Successfully Saved the Edition'; }
    } else {
        $query = "UPDATE sm_editions SET edition = :edition, description = :description,
                  is_open = :is_open, is_contest = :is_contest,
                  fee_normal = :fee_normal WHERE id = :id";
        $stmt = $pdo->prepare($query);
        $stmt->bindValue(':edition',     $edition,     PDO::PARAM_STR);
        $stmt->bindValue(':description', $description, PDO::PARAM_STR);
        $stmt->bindValue(':is_open',     $is_open,     PDO::PARAM_INT);
        $stmt->bindValue(':is_contest',  $is_contest,  PDO::PARAM_INT);
        $stmt->bindValue(':fee_normal',  number_format($fee_normal, 2, '.', ''), PDO::PARAM_STR);
        $stmt->bindValue(':id',          $id, PDO::PARAM_INT);
        if ($stmt->execute()) { $msg = 'Successfully Edited the Edition'; }
    }
}

// Handle deletion of edition (admin-only, POST + CSRF token)
if ($is_admin && isset($_POST['delete']) && is_numeric($_POST['delete'])
    && isset($_POST['token']) && hash_equals($_SESSION['token'], (string)$_POST['token'])) {
    $delete_id = (int)$_POST['delete'];

    // Delete edition
    $query = "DELETE FROM sm_editions WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':id', $delete_id, PDO::PARAM_INT);
    $stmt->execute();

    // Delete related submissions
    $query = "DELETE FROM sm_submissions WHERE editionid = :id";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':id', $delete_id, PDO::PARAM_INT);
    $stmt->execute();

    $msg = 'Successfully Deleted the Edition and all poems under it!';
}

// Retrieve edition data for editing
$row = [];
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $query = "SELECT * FROM sm_editions WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':id', $edit_id, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Include the header and editors menu at the top
include_once('header.php'); 
include_once('editors-menu.php'); 
?>
<link rel="stylesheet" href="../styles.css"> <!-- Link to external CSS -->

<div class="container" style="max-width: 800px; margin: 20px auto; padding: 20px;">
    <h2>Editions</h2>
    <span class="msg"><?= isset($msg) ? htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') : ''; ?></span>

    <div class="card" style="padding: 20px; margin-bottom: 20px;">
        <h3><?= isset($row['id']) ? 'Edit Edition' : 'Add New Edition' ?></h3>
        <form method="post">
            <input name="id" type="hidden" value="<?= isset($row['id']) ? (int)$row['id'] : ''; ?>" />
            <!-- CSRF token for form security -->
            <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8'); ?>" />

            <p>Edition:<br /><input name="edition" value="<?= isset($row['edition']) ? htmlspecialchars($row['edition'], ENT_QUOTES, 'UTF-8') : ''; ?>" type="text" size="43" /></p>

            <p>Description:<br /><textarea name="description" cols="40" rows="4" style="width: 100%; box-sizing: border-box; padding: 10px;"><?= isset($row['description']) ? htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8') : ''; ?></textarea></p>

            <p><label><input name="is_open" type="checkbox" value="1" <?= isset($row['is_open']) && $row['is_open'] ? 'checked="checked"' : ''; ?> /> Open for Submissions <small>(check this to accept submissions for this edition)</small></label></p>

            <p><label><input id="is_contest" name="is_contest" type="checkbox" value="1" <?= !empty($row['is_contest']) ? 'checked="checked"' : ''; ?> /> This is a contest <small>(charges a per-submission fee)</small></label></p>

            <div id="contest-fees" style="display: <?= !empty($row['is_contest']) ? 'block' : 'none' ?>; padding: 12px 16px; background: #fdf4e8; border-left: 3px solid #b08542; margin: 8px 0 16px;">
              <p style="margin: 0;"><label>Entry fee (USD):<br>
                <input name="fee_normal" type="number" step="0.01" min="0" value="<?= isset($row['fee_normal']) ? htmlspecialchars(number_format((float)$row['fee_normal'], 2, '.', ''), ENT_QUOTES, 'UTF-8') : '20.00' ?>" style="width: 120px;">
              </label></p>
              <p style="margin: 8px 0 0; font-size: 12px; color: #555; font-style: italic;">A submission credit covers the full fee.</p>
            </div>
            <script>
              (function () {
                var cb = document.getElementById('is_contest');
                var box = document.getElementById('contest-fees');
                if (!cb || !box) return;
                cb.addEventListener('change', function () { box.style.display = cb.checked ? 'block' : 'none'; });
              })();
            </script>

            <input name="submit" value="<?= isset($row['id']) ? 'Update Edition' : 'Create Edition' ?>" type="submit" class="button-primary" />
            <?php if (isset($_GET['edit'])) { ?>
                <input onclick="location.href = 'editors-editions.php?action=new'" value="Create New Edition" type="button" class="button-secondary" />
                <input onclick="location.href = 'editors-editions.php'" value="Cancel" type="button" class="button-secondary" />
            <?php } ?>
        </form>
    </div>

    <?php
    // Newest first, open before closed.
    $query = "SELECT * FROM sm_editions ORDER BY is_open DESC, date_added DESC";
    $stmt = $pdo->query($query);
    $all_editions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $open_rows   = array_values(array_filter($all_editions, fn($r) => !empty($r['is_open'])));
    $closed_rows = array_values(array_filter($all_editions, fn($r) => empty($r['is_open'])));

    $is_admin = ($_SESSION['editor_type'] == 'superadmin' || $_SESSION['editor_type'] == 'admin');

    $render_table = function (array $rows) use ($is_admin) {
        if (empty($rows)) {
            echo '<p style="color: #888; font-style: italic; padding: 12px 0;">None.</p>';
            return;
        }
        ?>
        <table class="list" style="width: 100%;">
            <tr>
                <th>Edition</th>
                <th>Type / Fees</th>
                <th>Added On</th>
                <th>Status</th>
                <th>Count</th>
                <?php if ($is_admin): ?><th>Actions</th><?php endif; ?>
            </tr>
            <?php foreach ($rows as $row): ?>
                <tr>
                    <td><a href="editors-edition.php?id=<?= (int)$row['id']; ?>"><?= htmlspecialchars(stripslashes($row['edition']), ENT_QUOTES, 'UTF-8'); ?></a></td>
                    <td>
                      <?php if (!empty($row['is_contest'])): ?>
                        <span style="background: #fdf4e8; border: 1px solid #b08542; color: #8c6532; padding: 2px 8px; border-radius: 2px; font-size: 11px; letter-spacing: 0.1em;">CONTEST</span>
                        <small style="color: #555; display: block; margin-top: 4px;">$<?= number_format((float)($row['fee_normal'] ?? 0), 2) ?> entry fee</small>
                      <?php else: ?>
                        <small style="color: #888;">Regular issue</small>
                      <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars(date('M. d, Y h:ia', strtotime($row['date_added'])), ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?= $row['is_open'] ? 'Open' : 'Closed'; ?></td>
                    <td><a href="editors-edition.php?id=<?= (int)$row['id']; ?>"><?= countPoemByEdition((int)$row['id']); ?></a></td>
                    <?php if ($is_admin): ?>
                        <td>
                            [<a href="editors-editions.php?edit=<?= (int)$row['id']; ?>">EDIT</a>]
                            [<form method="post" style="display:inline" onsubmit="return confirm('Are you sure you want to delete this edition AND all poems under it?');"><input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8'); ?>"><input type="hidden" name="delete" value="<?= (int)$row['id']; ?>"><button type="submit" style="background:none;border:none;color:#06c;cursor:pointer;padding:0;font:inherit">DELETE</button></form>]
                        </td>
                    <?php endif; ?>
                </tr>
            <?php endforeach; ?>
        </table>
        <?php
    };
    ?>

    <h3 style="margin-top: 28px;">Open Editions <small style="color: #888; font-weight: 400;">(<?= count($open_rows) ?>)</small></h3>
    <?php $render_table($open_rows); ?>

    <details style="margin-top: 28px;" <?= count($open_rows) === 0 ? 'open' : '' ?>>
      <summary style="cursor: pointer; padding: 8px 0; font-weight: 600; color: #444;">
        Closed Editions <small style="color: #888; font-weight: 400;">(<?= count($closed_rows) ?>)</small>
      </summary>
      <div style="margin-top: 12px;">
        <?php $render_table($closed_rows); ?>
      </div>
    </details>
</div>
<?php if ($_SESSION['editor_type'] == 'superadmin' || $_SESSION['editor_type'] == 'admin'): ?>
    <div class="container" style="max-width: 800px; margin-top: 20px;">
        <small><font color="red">WARNING: Deleting the edition will also delete any submissions under it.</font></small>
    </div>
<?php endif; ?>
<?php
include_once('footer.php');
?>
