<?php
// [2025-04-14] Disabled user requested full code reprint on changes.
session_start(); // Must be called before accessing $_SESSION

// --- Flash Message Handling ---
$flash_success = null;
if (isset($_SESSION['flash_success'])) {
    $flash_success = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}
// --- End Flash Message Handling ---

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

if (!isset($pdo)) {
    error_log("Database connection (\$pdo) not found in config.php");
    die('A configuration error occurred. Please contact support.');
}

// --- Fetch Allowed File Types from DB ---
// Default Fallback (ensure lowercase array)
$db_allowed_types_string = 'pdf, doc, docx, txt';
$allowed_extensions_array = ['pdf', 'doc', 'docx', 'txt']; // Lowercase array

try {
    $stmt_types = $pdo->prepare("SELECT value FROM sm_settings WHERE var = 'allowed_file_types'");
    $stmt_types->execute();
    $fetched_types = $stmt_types->fetchColumn();

    if ($fetched_types) {
        $db_allowed_types_string = $fetched_types;
        // Build validation array - ensuring elements are lowercase, trimmed, and not empty
        $allowed_extensions_array = array_map('strtolower', array_filter(array_map('trim', explode(',', $db_allowed_types_string))));
    } else {
        error_log("Setting 'allowed_file_types' not found or empty in sm_settings table. Using default: " . $db_allowed_types_string);
    }
} catch (PDOException $e) {
    error_log("Database error fetching allowed_file_types: " . $e->getMessage() . ". Using default: " . $db_allowed_types_string);
}
// --- End Fetch Allowed File Types ---


// --- CSRF Token Generation ---
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];
// --- End CSRF Token Generation ---


if (isset($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
    $submission_id = (int)$_GET['id'];
} else {
    die('Invalid submission ID provided.');
}

try {
    $stmt = $pdo->prepare("SELECT * FROM sm_submissions WHERE id = :id");
    $stmt->bindParam(':id', $submission_id, PDO::PARAM_INT);
    $stmt->execute();
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Database error fetching submission: " . $e->getMessage());
    die('Error retrieving submission data.');
}

if (!$submission) {
    die('Error: Submission not found.');
}

if (!isset($_SESSION['poet_id']) || $_SESSION['poet_id'] != $submission['poetid']) {
    header('Location: login.php?error=unauthorized');
    exit;
}

function getUserName(int $sender_id, string $sender_type, PDO $db_connection): string {
    $name = 'Unknown User';
    try {
        if ($sender_type === 'poet') {
            $stmt = $db_connection->prepare("SELECT CONCAT(author_name, ' ', author_lastname) AS name FROM sm_poets WHERE id = :id");
            $stmt->bindParam(':id', $sender_id, PDO::PARAM_INT);
            $stmt->execute();
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            $name = $user ? $user['name'] : 'Unknown Poet';
        } elseif ($sender_type === 'editor') {
            $stmt = $db_connection->prepare("SELECT first_name, last_name FROM sm_editors WHERE id = :id");
            $stmt->bindParam(':id', $sender_id, PDO::PARAM_INT);
            $stmt->execute();
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            $name = $user ? $user['first_name'] . ' ' . $user['last_name'] : 'Unknown Editor';
        }
    } catch (PDOException $e) {
        error_log("Database error fetching username ({$sender_type} ID: {$sender_id}): " . $e->getMessage());
        return 'Error retrieving name';
    }
    return $name ?: 'Unknown User';
}


// Handle form submission for messages
$form_error = null; // Initialize form error for *this* potential submission

if (isset($_POST['send_message'])) {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $form_error = 'Invalid request origin. Please try submitting the form again.';
    } else {
        $message = trim($_POST['message'] ?? '');
        $attachment_name_db = null;
        $original_filename_db = null;

        if (empty($message) && empty($_FILES['attachment']['tmp_name'])) {
                $form_error = 'Please enter a message or upload an attachment.';
        } else {
            if (!empty($_FILES['attachment']['error']) && $_FILES['attachment']['error'] !== UPLOAD_ERR_NO_FILE) {
                    switch ($_FILES['attachment']['error']) {
                        case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $form_error = "Error: The uploaded file exceeds the maximum allowed size."; break;
                        case UPLOAD_ERR_PARTIAL: $form_error = "Error: The file was only partially uploaded."; break;
                        default: $form_error = "Error: An unknown error occurred during file upload."; break;
                    }
                    error_log("File upload error code: " . $_FILES['attachment']['error']);
            } elseif (!empty($_FILES['attachment']['tmp_name'])) {
                $original_filename = basename($_FILES['attachment']['name']);
                $file_size = $_FILES['attachment']['size'];
                $file_tmp_path = $_FILES['attachment']['tmp_name'];
                // Use lowercase extension for validation consistency
                $file_extension = strtolower(pathinfo($original_filename, PATHINFO_EXTENSION));
                $max_size_bytes = defined('MAX_FILE_SIZE') ? MAX_FILE_SIZE : 0;
                if (!defined('ATTACHMENTS_DIR')) define('ATTACHMENTS_DIR', __DIR__ . '/attachments');

                if ($max_size_bytes > 0 && $file_size > $max_size_bytes) {
                    $form_error = "Error: File is too large. Maximum size is " . round($max_size_bytes / 1024 / 1024, 2) . "MB.";
                // Compare lowercase extension against lowercase array
                } elseif (!in_array($file_extension, $allowed_extensions_array)) {
                    $form_error = "Error: Invalid file type. Allowed types are: " . htmlspecialchars($db_allowed_types_string);
                } else {
                    // File type is valid, proceed
                    $safe_extension = preg_replace('/[^a-zA-Z0-9]/', '', $file_extension);
                    $unique_id = bin2hex(random_bytes(16));
                    $new_filename = $unique_id . '.' . $safe_extension;
                    $attachment_path = rtrim(ATTACHMENTS_DIR, '/') . '/' . $new_filename;

                    if (!is_dir(ATTACHMENTS_DIR)) {
                        if (!mkdir(ATTACHMENTS_DIR, 0755, true)) {
                           $form_error = 'Error: Cannot create attachments directory.';
                           error_log("Failed to create attachments directory: " . ATTACHMENTS_DIR);
                        }
                    }
                    if (!$form_error && !is_writable(ATTACHMENTS_DIR)) {
                        $form_error = 'Error: Attachments directory is not writable.';
                        error_log("Attachments directory not writable: " . ATTACHMENTS_DIR);
                    }

                    // Move file if type was valid AND directories are okay
                    if (!$form_error) {
                        if (move_uploaded_file($file_tmp_path, $attachment_path)) {
                            $attachment_name_db = $new_filename;
                            $original_filename_db = $original_filename;
                            if (!chmod($attachment_path, 0644)) {
                                error_log("Warning: Could not set permissions to 644 for file: " . $attachment_path);
                            }
                        } else {
                            $form_error = 'Error: Failed to save the uploaded file.';
                            error_log("Failed to move uploaded file from $file_tmp_path to: " . $attachment_path);
                        }
                    }
                } // end file validation else
            } // End file processing block

            // If no errors occurred AT ANY STAGE (validation, dir, move), insert into DB
            if (!$form_error) {
                $sender_id = $_SESSION['poet_id'];
                $sender_type = 'poet';
                try {
                    $stmt = $pdo->prepare("INSERT INTO sm_revisions (submission_id, sender_id, sender_type, message, attachment, date_sent) VALUES (:submission_id, :sender_id, :sender_type, :message, :attachment, NOW())");
                    $stmt->bindParam(':submission_id', $submission_id, PDO::PARAM_INT);
                    $stmt->bindParam(':sender_id', $sender_id, PDO::PARAM_INT);
                    $stmt->bindParam(':sender_type', $sender_type, PDO::PARAM_STR);
                    $stmt->bindParam(':message', $message, PDO::PARAM_STR);
                    $stmt->bindParam(':attachment', $attachment_name_db, PDO::PARAM_STR);
                    $stmt->execute();

                    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                    // Set Flash Message for success
                    $_SESSION['flash_success'] = "Your message has been sent successfully.";
                    // Redirect WITHOUT the success flag
                    header("Location: revisions.php?id=" . $submission_id);
                    exit;

                } catch (PDOException $e) {
                    error_log("Database error inserting revision message: " . $e->getMessage());
                    $form_error = 'An error occurred while saving your message. Please try again.';
                    if ($attachment_name_db && file_exists(ATTACHMENTS_DIR . '/' . $attachment_name_db)) {
                        @unlink(ATTACHMENTS_DIR . '/' . $attachment_name_db);
                    }
                }
            } // end if (!$form_error) before DB insert
        } // End basic validation else
    } // End CSRF check else
} // End handle form submission


// --- START MESSAGE FETCHING AND PROCESSING LOGIC ---
$all_messages = [];
$absolute_latest_message_sender_type = null;
$messages_error = null;

$revision_status = defined('SUBMISSION_STATUS_REVISION_REQUESTED') ? SUBMISSION_STATUS_REVISION_REQUESTED : 3;

if ($submission['status'] == $revision_status) {
    try {
        $query = "SELECT * FROM sm_revisions WHERE submission_id = :submission_id ORDER BY date_sent DESC, id DESC";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':submission_id', $submission_id, PDO::PARAM_INT);
        $stmt->execute();
        $all_messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (!empty($all_messages)) {
            $absolute_latest_message_sender_type = $all_messages[0]['sender_type'];
        }

    } catch (PDOException $e) {
        error_log("Database error fetching revision messages: " . $e->getMessage());
        $messages_error = 'Error retrieving collaboration history.';
    }
}
// --- END MESSAGE FETCHING AND PROCESSING LOGIC ---


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

$common_message_styles = "border: 1px solid #ddd; padding: 15px; margin-bottom: 20px; border-radius: 5px;";

?>
<link rel="stylesheet" href="../styles.css">

<div class="container revision-container">
    <h2>Collaborate on Submission: <?= htmlspecialchars($submission['title'] ?? 'Untitled', ENT_QUOTES, 'UTF-8') ?></h2>

    <div class="submission-details" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee;">
        <p><strong>Overall Status:</strong>
            <?php
                if ($submission['status'] == $revision_status) { echo 'Revisions have been requested!'; }
                else { echo 'Status Not Requiring Revision'; }
            ?>
        </p>
        <?php if (!empty($submission['bio_comments'])): ?>
            <p><strong>Initial Author's Comments:</strong><br /><?= nl2br(htmlspecialchars($submission['bio_comments'], ENT_QUOTES, 'UTF-8')) ?></p>
        <?php endif; ?>
    </div>

    <?php if ($submission['status'] == $revision_status): ?>
        <h3>Collaboration Thread</h3>

        <div style="margin-bottom: 20px; padding: 10px; border: 1px dashed #aaa; text-align: center; background-color: #f0f0f0;">
            <?php if ($messages_error): ?> <strong style="color: red;">Error loading messages. Please try refreshing.</strong>
            <?php elseif (empty($all_messages)): ?> <strong>The editor has requested revisions. Please send your response using the form below. (Your turn)</strong>
            <?php elseif ($absolute_latest_message_sender_type === 'editor'): ?> <strong style="color: #2a7a2a;">Waiting for Your Response. (Your turn)</strong>
            <?php elseif ($absolute_latest_message_sender_type === 'poet'): ?> <strong style="color: #0056b3;">Waiting for Editor's Response.</strong>
            <?php else: ?> <strong>Status unclear. Please review history.</strong>
            <?php endif; ?>
        </div>

        <?php if (isset($messages_error)): ?>
                <p class="error-message"><?= htmlspecialchars($messages_error) ?></p>
        <?php else: ?>

            <?php if (!empty($all_messages)):
                $latest_message = $all_messages[0];
                $sender_name = htmlspecialchars(getUserName($latest_message['sender_id'], $latest_message['sender_type'], $pdo), ENT_QUOTES, 'UTF-8');
                $is_poet = ($latest_message['sender_type'] === 'poet');
                $display_title = 'Most recent message';
                $display_sender = $is_poet ? 'You' : $sender_name;
                $bgColor = $is_poet ? '#e6ffe6' : '#e7f5fe';
                $message_date = htmlspecialchars($latest_message['date_sent'], ENT_QUOTES, 'UTF-8');
                $message_text = nl2br(htmlspecialchars($latest_message['message'], ENT_QUOTES, 'UTF-8'));
                $attachment_file = $latest_message['attachment'] ? htmlspecialchars($latest_message['attachment'], ENT_QUOTES, 'UTF-8') : null;
                $attachment_display = $attachment_file;
            ?>
                <div class="latest-message" style="<?= $common_message_styles ?> background-color: <?= $bgColor ?>;">
                    <strong style="font-size: 1.1em;"><?= $display_title ?></strong> (from <?= $display_sender ?>)<br />
                    <span class="timestamp" style="font-size: 0.9em; color: #555;">Sent on: <?= $message_date ?></span>
                    <p class="message-body" style="margin-top: 10px;"><?= $message_text ?: '<i>(No message text provided)</i>' ?></p>
                    <?php if ($attachment_file): ?>
                        <p><a href="attachments/<?= $attachment_file ?>" class="attachment-link" download="<?= htmlspecialchars($attachment_display ?: $attachment_file) ?>">Download Attachment</a></p>
                    <?php endif; ?>
                </div>
            <?php elseif (!$messages_error): ?>
                <div style="<?= $common_message_styles ?> background-color: #f8f9fa;">No messages have been exchanged in this revision thread yet.</div>
            <?php endif; ?>

            <?php if (!empty($all_messages)): ?>
                <details class="message-history-details" style="margin-bottom: 20px;">
                    <summary style="cursor: pointer; font-weight: bold; padding: 5px; background-color: #eee; border-radius: 3px; margin-bottom: 10px;">
                        View Full Message History (<?= count($all_messages) ?> message<?= count($all_messages) > 1 ? 's' : '' ?>)
                    </summary>
                    <div class="older-messages-log" style="margin-top: 10px; border-top: 1px solid #ddd; padding-top: 15px;">
                        <?php
                        $history_messages_display_order = array_reverse($all_messages);
                        foreach ($history_messages_display_order as $message):
                            $sender_name_hist = htmlspecialchars(getUserName($message['sender_id'], $message['sender_type'], $pdo), ENT_QUOTES, 'UTF-8');
                            $is_poet_hist = ($message['sender_type'] === 'poet');
                            $display_name_hist = $is_poet_hist ? 'You' : $sender_name_hist;
                            $date_sent_hist = htmlspecialchars($message['date_sent'], ENT_QUOTES, 'UTF-8');
                            $message_text_hist = nl2br(htmlspecialchars($message['message'], ENT_QUOTES, 'UTF-8'));
                            $attachment_file_hist = $message['attachment'] ? htmlspecialchars($message['attachment'], ENT_QUOTES, 'UTF-8') : null;
                            $attachment_display_hist = $attachment_file_hist;
                            $bgColor_hist = $is_poet_hist ? '#f0fff0' : '#f0f8ff';
                            $borderColor_hist = $is_poet_hist ? '#a0d9a0' : '#a0c0e0';
                        ?>
                            <div class="history-log-entry" style="border: 1px solid <?= $borderColor_hist ?>; background-color: <?= $bgColor_hist ?>; padding: 10px; margin-bottom: 15px; border-radius: 4px; box-shadow: 1px 1px 3px rgba(0,0,0,0.1);">
                                <div class="message-header" style="padding-bottom: 5px; margin-bottom: 8px; border-bottom: 1px dotted #999; font-size: 0.9em; color: #333;">
                                    <strong><?= $display_name_hist ?></strong>
                                    <span class="timestamp" style="float: right; color: #555;">Sent: <?= $date_sent_hist ?></span>
                                    <div style="clear: both;"></div>
                                </div>
                                <div class="message-content">
                                    <p class="message-body" style="margin-top: 0; margin-bottom: 8px;"><?= $message_text_hist ?: '<i>(No message text provided)</i>' ?></p>
                                    <?php if ($attachment_file_hist): ?>
                                        <p style="font-size: 0.9em; margin-top: 5px; padding-top: 5px; border-top: 1px dashed #ccc;">
                                            <a href="attachments/<?= $attachment_file_hist ?>" class="attachment-link" download="<?= htmlspecialchars($attachment_display_hist ?: $attachment_file_hist) ?>">Download Attachment</a>
                                        </p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </details>
            <?php endif; ?>
        <?php endif; ?>


        <section class="message-form-section" style="border: 1px solid #ccc; padding: 20px; margin-top: 20px; background-color: #ffffe0; border-radius: 5px;">
            <h3>Send Your Response</h3>
            <?php /* UPDATED: Display form error (styled) OR flash success */ ?>
            <?php if ($form_error): /* Error from CURRENT submission attempt */ ?>
                <p class="error-message" style="color: #D8000C; background-color: #FFD2D2; border: 1px solid #D8000C; padding: 12px 15px; margin-top: 15px; margin-bottom: 20px; font-weight: bold; font-size: 1.1em; border-radius: 4px; text-align: center;">
                    <?= htmlspecialchars($form_error) ?>
                </p>
            <?php elseif ($flash_success): /* Success message from PREVIOUS successful submission */ ?>
                <p class="success-message" style="color: #2a7a2a; background-color: #e6ffe6; border: 1px solid #2a7a2a; padding: 10px 15px; margin-bottom: 15px; border-radius: 4px;">
                    <?= htmlspecialchars($flash_success) ?>
                </p>
            <?php endif; ?>

            <form method="post" enctype="multipart/form-data" action="revisions.php?id=<?= $submission_id ?>">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token, ENT_QUOTES, 'UTF-8'); ?>">

                <div class="form-group">
                    <label for="message" class="form-label">Message:</label>
                    <textarea id="message" name="message" rows="5" class="form-input"><?= isset($_POST['message']) && $form_error ? htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8') : '' ?></textarea>
                    <small class="form-help-text">Required if no attachment is uploaded.</small>
                </div>

                <div class="form-group">
                    <label for="attachment" class="form-label">Attach File (Optional):</label>
                    <?php
                        $accept_string = ''; if (!empty($allowed_extensions_array)) { $accept_string = '.' . implode(',.', $allowed_extensions_array); }
                        $help_text_parts = []; if (!empty($db_allowed_types_string)) { $help_text_parts[] = 'Accepted types: ' . htmlspecialchars($db_allowed_types_string, ENT_QUOTES, 'UTF-8'); }
                        $max_size_bytes = defined('MAX_FILE_SIZE') ? MAX_FILE_SIZE : 0; if ($max_size_bytes > 0) { $help_text_parts[] = 'Max size: ' . round($max_size_bytes / 1024 / 1024, 2) . 'MB'; }
                    ?>
                    <input type="file" id="attachment" name="attachment" class="form-input" accept="<?= htmlspecialchars($accept_string, ENT_QUOTES, 'UTF-8') ?>">
                    <?php if (!empty($help_text_parts)): ?> <small class="form-help-text"><?= implode('. ', $help_text_parts) ?>.</small> <?php endif; ?>
                </div>

                <div class="form-group">
                    <input type="submit" name="send_message" value="Send Message" class="button button-primary">
                </div>
            </form>
        </section>

    <?php else: ?>
        <p>This submission is not currently awaiting revisions. No collaboration actions are available.</p>
    <?php endif; ?>
</div>

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