<?php
// Auth and DB must run BEFORE any output so checklogin's redirect works.
require_once('../common.php');
require_once('checklogin.php');
require_once('../config.php'); // Ensure this file defines the $pdo object for PDO
include_once('header.php');

// Function to sanitize user input and prevent XSS
function sanitize_input($input) {
    return htmlspecialchars(trim($input ?? ''), ENT_QUOTES, 'UTF-8');
}

// Function to generate a CSRF token
function generate_csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Function to validate CSRF token
function validate_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Start session safely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$msg = '';
$errors = [];

// Check if poem ID is present
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: editors-search.php');
    exit;
}

$poem_id = intval($_GET['id']); // Ensure ID is an integer

// Handle form submission for adding a note
if (isset($_POST['submit'])) {
    // Validate CSRF token
    if (!validate_csrf_token($_POST['csrf_token'])) {
        die('Invalid CSRF token');
    }

    // Validate the note input
    $note = trim($_POST['note'] ?? '');
    if (empty($note)) {
        $errors['note'] = 'You cannot add a blank note.';
    }

    // If no errors, insert the note into the database securely
    if (empty($errors)) {
        $stmt = $pdo->prepare("INSERT INTO sm_notes (poemid, editorid, note, date_added) VALUES (:poemid, :editorid, :note, :date_added)");
        $date_added = date('Y-m-d H:i:s');
        $stmt->execute([
            'poemid' => $poem_id,
            'editorid' => $_SESSION['editor_id'],
            'note' => $note,
            'date_added' => $date_added,
        ]);
        $msg = 'Successfully Added a Private Note.'; // Updated message
    }
}

include_once('editors-menu.php');
?>

<center>
    <h2>View Submission</h2>
    <div style="max-width: 800px; margin: auto;">
        <table width="100%" cellpadding="15" align="center" border="5">
            <tr>
                <td>
                    <?php $poem = getPoem($poem_id); ?>
                    <p><a href="./editors-subs.php">&lt;&lt; Return to Slush Pile</a></p> <!-- Updated link -->

                    <h2><?= sanitize_input($poem['title']) ?></h2>

                    <span class="msg"><?php if (isset($msg)) { echo sanitize_input($msg); } ?></span>
                    
                    <?php if (!empty($poem['body'])): ?>
                        <p><?= nl2br(sanitize_input($poem['body'])) ?></p>
                    <?php endif; ?>

                    <?php if (!empty($poem['attachment'])): 
                        $attachmentName = explode('____', $poem['attachment']);
                    ?>
                        <p>Attachment: <br /><?= sanitize_input($attachmentName[1]) ?> [<a href="downloadfile.php?filename=<?= sanitize_input($poem['attachment']) ?>">Download File</a>]</p>
                    <?php endif; ?>

                    <?php if ($_SESSION['editor_type'] == 'admin'): ?>
                        <p>Contributor comments: <br /><?= sanitize_input($poem['bio_comments']) ?></p>
                    <?php endif; ?>

                    <?php if ($_SESSION['editor_type'] == 'editor'): ?>
                        <?php if ($blindeditor == "no"): ?>
                            <p>Contributor comments: <br /><?= sanitize_input($poem['bio_comments']) ?></p>
                        <?php else: ?>
                            <p>Contributor comments are off in blind reading mode.</p>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php if ($_SESSION['editor_type'] == 'reader'): ?>
                        <?php if ($blindreadercomments == "no"): ?>
                            <p>Contributor comments: <br /><?= sanitize_input($poem['bio_comments']) ?></p>
                        <?php else: ?>
                            <p>Contributor comments are off in blind reading mode.</p>
                        <?php endif; ?>
                    <?php endif; ?>

                    <p>Status: <br /><?= sanitize_input($submission_status[$poem['status']] ?? 'Unknown Status') ?></p>

                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?= generate_csrf_token() ?>">
                        Leave a staff note:<br />
                        <textarea name="note" cols="50" rows="5" required></textarea><br />
                        <input name="submit" type="submit" value="Add Note" />
                    </form>

                    <br />
                    <?php
                    // Retrieve staff notes securely
                    $stmt = $pdo->prepare("SELECT * FROM sm_notes WHERE poemid = :poemid");
                    $stmt->execute(['poemid' => $poem_id]);
                    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                        if ($_SESSION['editor_type'] == 'admin' || $_SESSION['editor_type'] == 'editor' || ($_SESSION['editor_type'] == 'reader' && $readernotes == "yes" && $row['editorid'] == $_SESSION['editor_id'])) {
                    ?>
                            <br /><br /><b>Private Staff Notes</b><br />
                            <small>Added on <?= date('M. d, Y h:ia', strtotime($row['date_added'])) ?> By Staff ID: <?= sanitize_input($row['editorid']) ?></small><br />
                            <p><?= nl2br(sanitize_input($row['note'])) ?></p>
                    <?php
                        }
                    }
                    ?>
                </td>
            </tr>
        </table>
    </div>
</center>

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