<?php

require_once('../common.php');
require_once('checklogin.php');

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

include_once('header.php');
include_once('editors-menu.php');

// The edition currently being viewed
$edition_id = (int)($_GET['id'] ?? 0);

// Whether the contributor final-confirmation ("print") column should be shown
$finalcheck = settingGet('finalcheck') ?: 'no';

// Handle the "move" action securely with prepared statements
if (isset($_POST['move']) && isset($_POST['token']) && $_POST['token'] === $_SESSION['token']) {

    // Check if any submissions were selected
    if (isset($_POST['move_id']) && is_array($_POST['move_id']) && ($_POST['target_edition'] ?? '0') != '0') {

        $target_edition = (int)$_POST['target_edition'];

        // Prepare the update statement once and reuse it
        $stmt = $pdo->prepare("UPDATE sm_submissions SET editionid = :target_edition WHERE id = :move_id");
        foreach ($_POST['move_id'] as $move_id) {
            $move_id = (int)$move_id;
            $stmt->bindValue(':target_edition', $target_edition, PDO::PARAM_INT);
            $stmt->bindValue(':move_id',        $move_id,        PDO::PARAM_INT);
            $stmt->execute();
        }

        $msg = '&bull; Successfully Moved The Selected Submissions to <b>' . htmlspecialchars(getEditionName($target_edition), ENT_QUOTES, 'UTF-8') . '</b><br /><br />';
    } else {
        $error = '&bull; You need to select a submission to move or a target edition!<br /><br />';
    }
} else if (isset($_POST['move']) && ($_POST['token'] ?? '') !== $_SESSION['token']) {
    $error = 'Invalid CSRF token. Please try again.';
}

// Reset CSRF token after use
$_SESSION['token'] = bin2hex(random_bytes(32));

?>
<p><a href="editors-editions.php">&lt;&lt;Back to Previous Page</a></p>
<center><h2>Edition: <?= htmlspecialchars(getEditionName($edition_id), ENT_QUOTES, 'UTF-8') ?></h2></center>
<span class="msg"><?= isset($msg) ? htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') : ''; ?></span>
<span class="error"><?= isset($error) ? htmlspecialchars($error, ENT_QUOTES, 'UTF-8') : ''; ?></span>
<center>
<form method="POST" onsubmit="if (document.getElementById('target_edition').value == '0') { alert('You need to select an edition!'); return false; }">
    <!-- CSRF token for protection -->
    <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>" />

    Move Selected Poems to:
    <select id="target_edition" name="target_edition">
        <option value="0">---Select Edition---</option>
        <?php
        $n_stmt = $pdo->prepare("SELECT * FROM sm_editions WHERE id <> :edition_id ORDER BY id");
        $n_stmt->bindValue(':edition_id', $edition_id, PDO::PARAM_INT);
        $n_stmt->execute();
        while ($n_row = $n_stmt->fetch(PDO::FETCH_ASSOC)) {
            echo '<option value="' . (int)$n_row['id'] . '">' . htmlspecialchars($n_row['edition'], ENT_QUOTES, 'UTF-8') . '</option>';
        }
        ?>
    </select>
    <input type="submit" name="move" value="Move Submissions!"><br />
    <small>You are currently viewing all accepted poems for this edition</small>
    <table width="1000" align="center" cellpadding="15" border="5">
        <tr>
            <th>Submission Title</th>
            <th>Contributor</th>
            <th>Email</th>
            <th>Added on</th>
            <?php if ($finalcheck == "yes"): ?>
            <th>Print</th>
            <?php endif ?>
        </tr>
        <?php
        $stmt = $pdo->prepare("SELECT a.*, a.id AS sid
                  FROM sm_submissions AS a
                  INNER JOIN sm_poets AS b ON a.poetid = b.id
                  WHERE a.editionid = :edition_id AND a.status = 1");
        $stmt->bindValue(':edition_id', $edition_id, PDO::PARAM_INT);
        $stmt->execute();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            foreach ($row as $k => $v) {
                $row[$k] = stripslashes((string)($v ?? ''));
            }
            ?>
            <tr>
                <td><input type="checkbox" name="move_id[]" value="<?= (int)$row['sid'] ?>"><a href="view-submission.php?id=<?= (int)$row['sid'] ?>"><?= htmlspecialchars(stripslashes($row['title']), ENT_QUOTES, 'UTF-8'); ?></a></td>
                <td><?= htmlspecialchars($row['author_name'], ENT_QUOTES, 'UTF-8'); ?> <?= htmlspecialchars($row['author_lastname'], ENT_QUOTES, 'UTF-8'); ?></td>
                <td><a href="mailto:<?= htmlspecialchars($row['email'], ENT_QUOTES, 'UTF-8'); ?>"><?= htmlspecialchars($row['email'], ENT_QUOTES, 'UTF-8'); ?></a></td>
                <td><?= htmlspecialchars(date('M. d, Y h:ia', strtotime($row['date_submitted'])), ENT_QUOTES, 'UTF-8'); ?></td>
                <?php if ($finalcheck == "yes"): ?>
                <td align="center">
                    <?php
                    if ($row['printconfirmation'] == 2)
                        echo '<span style="color:red;">NO</span>';
                    elseif ($row['printconfirmation'] == 1)
                        echo '<span style="color:green;">YES</span>';
                    else
                        echo '<b>?</b>';
                    ?>
                </td>
                <?php endif ?>
            </tr>
            <?php
        }
        ?>
    </table>
</form></center>
<?php
include_once('footer.php');
?>
