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

// Use the database connection from config.php
if (!isset($db)) {
    global $pdo;
    $db = $pdo;
}

// Define function to get the user name based on sender ID and type
function getUserName($sender_id, $sender_type) {
    global $db;
    if ($sender_type === 'poet') {
        $stmt = $db->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);
        return $user ? $user['name'] : 'Unknown Poet';
    } elseif ($sender_type === 'editor') {
        $stmt = $db->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);
        return $user ? $user['first_name'] . ' ' . $user['last_name'] : 'Unknown Editor';
    }
    return 'Unknown User';
}

// Fetch submission details
$submission_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Query to fetch submission information
$stmt = $db->prepare("SELECT * FROM sm_submissions WHERE id = :id");
$stmt->bindParam(':id', $submission_id, PDO::PARAM_INT);
$stmt->execute();
$submission = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Determine the sender ID based on the current user session
$sender_id = null;
$sender_type = null;

if (isset($_SESSION['editor_id'])) {
    // Editor is logged in
    $sender_id = (int)$_SESSION['editor_id'];
    $sender_type = 'editor';
} elseif (isset($_SESSION['poet_id'])) {
    // Poet is logged in
    $sender_id = (int)$_SESSION['poet_id'];
    $sender_type = 'poet';

    // Validate that the poet ID exists in sm_poets
    $stmt = $db->prepare("SELECT id FROM sm_poets WHERE id = :id");
    $stmt->bindParam(':id', $sender_id, PDO::PARAM_INT);
    $stmt->execute();
    $poet = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$poet) {
        die('Error: Invalid poet ID.');
    }
} else {
    die('Error: User not logged in.');
}

// CSRF token for this page's POST actions.
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}
$token_ok = isset($_POST['token']) && hash_equals($_SESSION['token'], (string)($_POST['token'] ?? ''));

// Allowed upload types (fall back to a safe default list).
$allowed_ext = array_filter(array_map('trim', explode(',', (string)(settingGet('allowed_file_types') ?: 'pdf, doc, docx, txt'))));
$allowed_ext = array_values(array_map(static fn($e) => strtolower(ltrim($e, '.')), $allowed_ext));
if (!$allowed_ext) { $allowed_ext = ['pdf', 'doc', 'docx', 'txt']; }

$form_error = '';

// Handle form submission for messages and attachments
if (isset($_POST['send_message'])) {
    if (!$token_ok) {
        $form_error = 'Invalid request. Please reload and try again.';
    } else {
        $message = htmlspecialchars($_POST['message'] ?? '', ENT_QUOTES, 'UTF-8');
        $attachment_name = '';
        $original_filename = '';

        // Handle file upload if any
        if (!empty($_FILES['attachment']['tmp_name']) && is_uploaded_file($_FILES['attachment']['tmp_name'])) {
            $original_filename = basename($_FILES['attachment']['name']);
            $ext = strtolower(pathinfo($original_filename, PATHINFO_EXTENSION));
            if (!in_array($ext, $allowed_ext, true)) {
                $form_error = 'Invalid file type. Allowed: ' . htmlspecialchars(implode(', ', $allowed_ext), ENT_QUOTES, 'UTF-8');
            } else {
                $attachments_dir = __DIR__ . '/../attachments';
                if (!is_dir($attachments_dir)) {
                    mkdir($attachments_dir, 0755, true);
                }
                // Random stored name; never trust the client's filename/extension on disk.
                $safe_ext = preg_replace('/[^a-z0-9]/', '', $ext);
                $attachment_name = bin2hex(random_bytes(16)) . '.' . $safe_ext;
                if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $attachments_dir . '/' . $attachment_name)) {
                    $form_error = 'Could not save the uploaded file.';
                    $attachment_name = '';
                    $original_filename = '';
                }
            }
        }

        // Insert the message into `sm_revisions` if everything is valid.
        if ($form_error === '' && $sender_id) {
            $stmt = $db->prepare("INSERT INTO sm_revisions (submission_id, sender_id, sender_type, message, attachment, original_filename, date_sent) VALUES (:submission_id, :sender_id, :sender_type, :message, :attachment, :original_filename, 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); // Either 'poet' or 'editor'
            $stmt->bindParam(':message', $message, PDO::PARAM_STR);
            $stmt->bindParam(':attachment', $attachment_name, PDO::PARAM_STR);
            $stmt->bindParam(':original_filename', $original_filename, PDO::PARAM_STR);
            $stmt->execute();
        }
    }
}

// Handle form submission for status update
if (isset($_POST['update_status'])) {
    if (!$token_ok) {
        $form_error = 'Invalid request. Please reload and try again.';
    } else {
        $status = intval($_POST['status']);

        // Update submission status
        $query = "UPDATE sm_submissions SET status = :status WHERE id = :id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':status', $status, PDO::PARAM_INT);
        $stmt->bindParam(':id', $submission_id, PDO::PARAM_INT);
        $stmt->execute();

        // Insert into sm_submission_status to track the status update
        $query = "INSERT INTO sm_submission_status (submission_id, status, date_updated) VALUES (:submission_id, :status, NOW())";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':submission_id', $submission_id, PDO::PARAM_INT);
        $stmt->bindParam(':status', $status, PDO::PARAM_INT);
        $stmt->execute();
    }
}

// Fetch the activity log for this submission
$stmt = $db->prepare("SELECT * FROM sm_revisions WHERE submission_id = :submission_id ORDER BY date_sent DESC");
$stmt->bindParam(':submission_id', $submission_id, PDO::PARAM_INT);
$stmt->execute();
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<link rel="stylesheet" href="../styles.css"> <!-- Link to external CSS -->
<div class="container" style="max-width: 800px; margin: 20px auto; padding: 20px;">
    <h2>Collaborate on Submission: <?= htmlspecialchars($submission['title'], ENT_QUOTES, 'UTF-8') ?></h2>

    <!-- Submission Details -->
    <p><strong>Title:</strong> <?= htmlspecialchars($submission['title'], ENT_QUOTES, 'UTF-8') ?></p>
    <p><strong>Current Status:</strong> 
        <?= $submission['status'] == 3 ? 'Request Revision' : 'Other' ?>
    </p>
    <p><strong>Author's Comments:</strong><br /><?= nl2br(htmlspecialchars($submission['bio_comments'], ENT_QUOTES, 'UTF-8')) ?></p>

    <!-- Activity Log -->
    <h3>Activity Log</h3>
    <div class="activity-log">
        <?php foreach ($messages as $index => $message): ?>
            <?php if ($index < 3): ?>
                <div class="log-entry" style="border: 1px solid #ddd; padding: 10px; margin-bottom: 15px; background-color: <?= $index === 0 ? '#e6ffe6' : '#f9f9f9'; ?>;">
                    <?php if ($index === 0): ?>
                        <strong style="color: #008000;">Most Recent Update</strong><br />
                    <?php endif; ?>
                    <strong>
                        <?= ($message['sender_type'] === 'poet') ? 'From User ' : 'From Editor ' ?>
                        <?= htmlspecialchars(getUserName($message['sender_id'], $message['sender_type']), ENT_QUOTES, 'UTF-8') ?>
                    </strong><br />
                    <span class="timestamp" style="font-size: 0.9em; color: #888;">Sent on: <?= htmlspecialchars($message['date_sent'], ENT_QUOTES, 'UTF-8') ?></span>
                    <p style="margin-top: 10px;">Message: <?= nl2br(htmlspecialchars($message['message'], ENT_QUOTES, 'UTF-8')) ?></p>
                    <?php if (!empty($message['attachment'])): ?>
                        <p><a href="../attachments/<?= htmlspecialchars($message['attachment'], ENT_QUOTES, 'UTF-8') ?>" download="<?= htmlspecialchars(($message['original_filename'] ?? '') ?: $message['attachment'], ENT_QUOTES, 'UTF-8') ?>" style="color: #007bff;">Download Attachment</a></p>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <details style="margin-bottom: 15px;">
                    <summary style="cursor: pointer;">Older Update from <?= htmlspecialchars(getUserName($message['sender_id'], $message['sender_type']), ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($message['date_sent'], ENT_QUOTES, 'UTF-8') ?>)</summary>
                    <div class="log-entry" style="border: 1px solid #ddd; padding: 10px; margin-bottom: 15px; background-color: #f9f9f9;">
                        <strong>
                            <?= ($message['sender_type'] === 'poet') ? 'From User ' : 'From Editor ' ?>
                            <?= htmlspecialchars(getUserName($message['sender_id'], $message['sender_type']), ENT_QUOTES, 'UTF-8') ?>
                        </strong><br />
                        <span class="timestamp" style="font-size: 0.9em; color: #888;">Sent on: <?= htmlspecialchars($message['date_sent'], ENT_QUOTES, 'UTF-8') ?></span>
                        <p style="margin-top: 10px;">Message: <?= nl2br(htmlspecialchars($message['message'], ENT_QUOTES, 'UTF-8')) ?></p>
                        <?php if (!empty($message['attachment'])): ?>
                            <p><a href="../attachments/<?= htmlspecialchars($message['attachment'], ENT_QUOTES, 'UTF-8') ?>" download="<?= htmlspecialchars(($message['original_filename'] ?? '') ?: $message['attachment'], ENT_QUOTES, 'UTF-8') ?>" style="color: #007bff;">Download Attachment</a></p>
                        <?php endif; ?>
                    </div>
                </details>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>
<hr>
    <!-- Send Message Form -->
    <section style="border: 1px solid #ccc; padding: 20px; margin-top: 20px; background-color: #ffffe0;">
        <h3>Create New Revision Request Message</h3>
        <?php if (!empty($form_error)): ?><p style="color:#c00; font-weight:bold;"><?= htmlspecialchars($form_error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>">
            <div class="form-group">
                <label for="message">Message:</label><br />
                <textarea name="message" rows="5" style="width: 100%; padding: 10px;"></textarea>
            </div>
            <div class="form-group">
                <label for="attachment">Attachment (Optional):</label><br />
                <input type="file" name="attachment">
            </div>
            <input type="submit" name="send_message" value="Send Message" class="button-primary">
        </form>
    </section>

    <!-- Update Status Form -->
    <section style="border: 1px solid #ccc; padding: 20px; margin-top: 20px; background-color: #f0f0f0;">
        <h3>Update Submission Status</h3>
        <form method="post" style="margin-top: 20px;">
            <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>">
            <div class="form-group" style="margin-bottom: 20px;">
                <label for="note">Update Note:</label>
                <textarea name="note" cols="50" rows="5" class="textarea" style="padding: 15px; width: 100%; box-sizing: border-box;"></textarea>
            </div>

            <div class="form-group" style="margin-bottom: 20px;">
                <label for="status">Update Status to:</label>
                <select name="status" class="input-field" style="width: 100%; padding: 10px; box-sizing: border-box;">
                    <option value="0" <?= $submission['status'] == 0 ? 'selected="selected"' : '' ?>>Pending</option>
                    <option value="1" <?= $submission['status'] == 1 ? 'selected="selected"' : '' ?>>Accepted</option>
                    <option value="2" <?= $submission['status'] == 2 ? 'selected="selected"' : '' ?>>Rejected</option>
                    <option value="3" <?= $submission['status'] == 3 ? 'selected="selected"' : '' ?>>Request Revision</option>
                    <?php
                    $query = "SELECT * FROM sm_status WHERE id > 3 ORDER BY id";
                    $stmt = $db->query($query);
                    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    foreach ($result as $row):
                    ?>
                    <option value="<?= $row['id'] ?>" <?= $submission['status'] == $row['id'] ? 'selected="selected"' : '' ?>><?= htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8') ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <input name="update_status" type="submit" value="Update Status" class="button-primary" />
        </form>
    </section>
</div>

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