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

// Changing a submission's edition is an editor/admin action.
if (!in_array($_SESSION['editor_type'] ?? '', ['editor', 'admin', 'superadmin'], true)) {
    http_response_code(403);
    exit('Access denied.');
}
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}

// Include database connection
require_once('../config.php'); // Ensure this file defines the `$pdo` object for PDO

// Include PHPMailer via the autoload file
require_once('./../phpmailer/src/Exception.php');
require_once('./../phpmailer/src/PHPMailer.php');
require_once('./../phpmailer/src/SMTP.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

include_once('header.php');
include_once('editors-menu.php');
?>
<style>
    .container {
        max-width: 800px;
        margin: 20px auto;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 8px;
        background-color: #f9f9f9;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .container h2 {
        text-align: center;
        font-size: 24px;
        margin-bottom: 20px;
    }

    .container a {
        text-decoration: none;
        color: #007bff;
    }

    .container a:hover {
        text-decoration: underline;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 20px;
    }

    table th, table td {
        padding: 12px;
        text-align: left;
        border: 1px solid #ddd;
    }

    table th {
        background-color: #007bff;
        color: white;
        text-align: center;
    }

    table td {
        background-color: #fff;
        color: #333;
    }

    table tr:nth-child(even) {
        background-color: #f2f2f2;
    }

    input[type="submit"] {
        display: block;
        width: 100%;
        padding: 10px;
        font-size: 16px;
        color: white;
        background-color: #007bff;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        text-align: center;
    }

    input[type="submit"]:hover {
        background-color: #0056b3;
    }
</style>

<div class="container">
    <p><a href="./editors-subs.php">&lt;&lt; Go Back to Slush Pile</a></p>
    <h2>Update Submission Edition</h2>
    <?php
    // Updating edition of all checked poems
    $msg = "";
    if (isset($_POST['up_submit'])
        && isset($_POST['token']) && hash_equals($_SESSION['token'], (string)$_POST['token'])) {
        $checked_sub_ids = $_POST['sub_id'] ?? [];

        foreach ($checked_sub_ids as $submission_id) {
            $submission_id = (int) $submission_id;
            $edt = "edition_" . $submission_id;
            $editionid = (int) $_POST[$edt];

            // Use PDO to avoid SQL injection
            $query = "UPDATE sm_submissions SET editionid = :editionid WHERE id = :id";
            $stmt = $pdo->prepare($query);
            $stmt->execute(['editionid' => $editionid, 'id' => $submission_id]);
        }

        echo $msg = "<span class='msg'>Edition has been updated successfully.</span>";
    } else {
        ?>
        <form method="post" action="">
            <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>">
            <table>
                <tr>
                    <th>Title</th>
                    <th>Edition</th>
                </tr>
            <?php
            $total_checked = count($_POST['checked']);
            $all_checked = $_POST['checked'];

            if ($total_checked > 0) {
                foreach ($all_checked as $checked) {
                    $submission_edition_id = explode('_', $checked);
                    $edition_id = (int) $submission_edition_id[0];
                    $submission_id = (int) $submission_edition_id[1];

                    // Use PDO for selecting the submission
                    $sel_query = "SELECT title FROM sm_submissions WHERE id = :id";
                    $stmt = $pdo->prepare($sel_query);
                    $stmt->execute(['id' => $submission_id]);
                    $row_submission = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($row_submission) {
                        echo "<tr><td>" . htmlspecialchars($row_submission['title'], ENT_QUOTES, 'UTF-8') . "</td>";

                        $add_select = "<td><input type='hidden' name='sub_id[]' value='" . $submission_id . "'>";
                        $add_select .= "<select name='edition_" . $submission_id . "'>";

                        // Use PDO to select editions
                        $query = "SELECT id, edition FROM sm_editions";
                        $result_editions = $pdo->query($query);

                        while ($row = $result_editions->fetch(PDO::FETCH_ASSOC)) {
                            $selected = ($edition_id == (int) $row['id']) ? 'selected' : '';
                            $add_select .= "<option value='" . (int) $row['id'] . "' " . $selected . ">" . htmlspecialchars($row['edition'], ENT_QUOTES, 'UTF-8') . "</option>";
                        }

                        $add_select .= "</select>";
                        echo $add_select .= "</td></tr>";
                    }
                }
            }
            ?>
            </table>
            <input name="up_submit" type="submit" value="Update Edition" />
        </form>
    <?php
    }
    ?>
</div>
<?php include_once('footer.php'); ?>
