<?php
// Ensure session is started if not already done in checklogin.php
// Consider adding session_start(); here if checklogin.php doesn't handle it reliably.
// ini_set('session.use_strict_mode', 1); // Good practice

require_once('common.php');
require_once('checklogin.php'); // Assumes this starts session and checks if logged in

// Validate and sanitize the poem ID input
$poem_id = null; // Initialize variable
if (isset($_GET['id'])) {
    // Filter_var is a more robust way to validate integers
    $filtered_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    if ($filtered_id !== false && $filtered_id > 0) { // Ensure positive integer
        $poem_id = $filtered_id;
    }
}

// If poem_id is not a valid positive integer, handle the error
if ($poem_id === null) {
    // Log the error for administrators
    // error_log("Invalid poem ID requested: " . print_r($_GET, true));
    // Show a generic error page or message
    die('Error: Invalid poem identifier provided.'); // Or redirect
}

// Fetch poem using prepared statements to prevent SQL injection
try {
    $connect = db(); // Assuming db() returns a secure PDO connection object
    // Set error mode to exceptions for better error handling
    $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query = "SELECT id, poetid, title, body, attachment, bio_comments FROM sm_submissions WHERE id = :id"; // Be explicit about columns
    $stmt = $connect->prepare($query);
    $stmt->bindParam(':id', $poem_id, PDO::PARAM_INT);
    $stmt->execute();
    $poem = $stmt->fetch(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    // Log the detailed database error (don't show to user)
    // error_log("Database error fetching poem ID {$poem_id}: " . $e->getMessage());
    // Show generic error
    die("An error occurred while retrieving poem details. Please try again later.");
}

// Check if the poem was found
if (!$poem) {
    // It's better to treat "not found" differently than a general error
    // You could show a 404 page or a specific message
    die("Error: The requested poem could not be found.");
}

// Verify if the current logged-in poet matches the poet who submitted the poem
// Ensure $_SESSION['poet_id'] is set by checklogin.php
if (!isset($_SESSION['poet_id']) || $_SESSION['poet_id'] != $poem['poetid']) {
    // Optional: Log unauthorized access attempt
    // error_log("Unauthorized attempt to access poem ID {$poem_id} by user ID {$_SESSION['poet_id'] ?? 'guest'}");
    // Redirect to login or an access denied page
    header('Location: login.php?loginrequired');
    exit;
}

// Include header and poet's menu
include_once('header.php');
// include_once('poets-menu.php'); // Included within header.php perhaps? Or place appropriately

?>

<style>
    body { /* Basic styling reset/defaults */
        font-family: Arial, sans-serif;
        line-height: 1.6;
        background-color: #f4f4f4;
        margin: 0;
        padding: 0;
    }
    .poem-view-container {
        max-width: 800px; /* Responsive width */
        margin: 2em auto; /* Centering and spacing */
        padding: 2em; /* Internal spacing */
        border: 1px solid #ddd; /* Subtle border */
        background-color: #fff; /* White background */
        box-shadow: 0 2px 5px rgba(0,0,0,0.1); /* Subtle shadow */
        border-radius: 5px; /* Slightly rounded corners */
    }
    .poem-back-link {
        display: inline-block;
        margin-bottom: 1.5em;
        padding: 0.6em 1.2em;
        background-color: #e9e9e9;
        border: 1px solid #ccc;
        color: #333;
        text-decoration: none;
        border-radius: 4px;
        transition: background-color 0.2s ease;
    }
    .poem-back-link:hover {
        background-color: #d0d0d0;
        border-color: #bbb;
    }
    .poem-title {
        margin-top: 0;
        margin-bottom: 1em;
        font-size: 2em; /* Larger title */
        color: #333;
        border-bottom: 2px solid #eee; /* Underline */
        padding-bottom: 0.5em;
    }
    .poem-body {
        margin-bottom: 1.5em;
        white-space: pre-wrap; /* Preserves line breaks and wraps text */
        color: #444; /* Slightly lighter text */
    }
    .poem-attachment {
        margin-bottom: 1.5em;
        padding: 1em;
        background-color: #f9f9f9;
        border: 1px solid #eee;
        border-left: 3px solid #007bff; /* Accent color */
        border-radius: 4px;
        color: #555;
    }
    .poem-attachment strong {
        /* Style for the "Attachment:" label if needed */
        color: #333;
    }
    .submitted-comments {
        margin-top: 2em;
        padding-top: 1em;
        border-top: 1px dashed #ccc; /* Dashed separator */
    }
    .submitted-comments-label {
        display: block; /* Label on its own line */
        margin-bottom: 0.5em;
        font-size: 1.2em; /* Slightly larger label */
        font-weight: bold;
        color: #333;
    }
    .submitted-comments-text {
        white-space: pre-wrap; /* Preserves line breaks and wraps text */
        color: #555; /* Slightly lighter text for comments */
        font-style: italic; /* Italicize comments */
        padding: 0.8em 1em; /* Add some padding */
        margin-left: 1em; /* Indent comment text slightly */
        border-left: 3px solid #ffc107; /* Different accent color */
        background-color: #fffaf0; /* Very light background for comments */
        border-radius: 0 4px 4px 0; /* Rounded corners matching border */
    }
</style>

<article class="poem-view-container">

    <a href="javascript:history.back();" class="poem-back-link">&lt;&lt; Go Back</a>

    <h2 class="poem-title"><?php echo htmlspecialchars($poem['title'] ?? 'Untitled', ENT_QUOTES, 'UTF-8'); ?></h2>

    <?php if (!empty($poem['body'])): ?>
        <div class="poem-body"><?php echo htmlspecialchars($poem['body'], ENT_QUOTES, 'UTF-8'); ?></div>
        <?php /* Note: Using white-space: pre-wrap in CSS instead of nl2br() */ ?>
    <?php endif; ?>

    <?php if (!empty($poem['attachment'])): ?>
        <?php
        $attachmentParts = explode('____', $poem['attachment'], 2);
        $displayAttachmentName = isset($attachmentParts[1]) ? $attachmentParts[1] : 'Attachment';
        ?>
        <div class="poem-attachment">
            <strong>Attachment:</strong> <?php echo htmlspecialchars($displayAttachmentName, ENT_QUOTES, 'UTF-8'); ?>
        </div>
    <?php endif; ?>

    <?php // Display the actual comments if they exist, properly escaped ?>
    <?php if (!empty($poem['bio_comments'])): ?>
        <section class="submitted-comments">
            <strong class="submitted-comments-label">Comments You Sent with this Submission:</strong> <?php /* <<< UPDATED HEADING TEXT */ ?>
            <div class="submitted-comments-text">
                <?php echo htmlspecialchars($poem['bio_comments'], ENT_QUOTES, 'UTF-8'); ?>
                <?php /* Note: Using white-space: pre-wrap in CSS instead of nl2br() */ ?>
            </div>
        </section>
    <?php endif; ?>

</article>

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