<?php
// Start session and require common files
require_once('../common.php');
require_once('checklogin.php');

// Include PHPMailer files
require_once('../phpmailer/src/PHPMailer.php');
require_once('../phpmailer/src/SMTP.php');
require_once('../phpmailer/src/Exception.php');

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

// CSRF protection: Generate token if not set
if (!isset($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}

$msg = '';
$error = '';

// Fetch the poem details using prepared statement to prevent SQL injection
$poem_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

$query = "
    SELECT sm_submissions.*, sm_poets.author_name, sm_poets.author_lastname, sm_poets.email
    FROM sm_submissions
    INNER JOIN sm_poets ON sm_submissions.poetid = sm_poets.id
    WHERE sm_submissions.id = :id";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':id', $poem_id, PDO::PARAM_INT);
$stmt->execute();
$poem = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$poem) {
    die('Error retrieving poem');
}

// Handle form submission for status update
if (isset($_POST['submit'])) {
    // Readers may not change status; require an editor/admin and a valid CSRF token.
    if (!in_array($_SESSION['editor_type'] ?? '', ['editor', 'admin', 'superadmin'], true)) {
        die('Access denied.');
    }
    if (!isset($_POST['token']) || !hash_equals($_SESSION['token'], (string)$_POST['token'])) {
        die('Invalid request. Please reload and try again.');
    }
    $status = intval($_POST['status']);
    $note = htmlspecialchars($_POST['note'] ?? '', ENT_QUOTES, 'UTF-8');
    $current_status = htmlspecialchars($_POST['current_status'] ?? '', ENT_QUOTES, 'UTF-8');
    $editor_id = $_SESSION['editor_id'];

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

    // Show the accepted message if the status is 1 (Accepted)
    if ($status == 1) {
        $query = "UPDATE sm_poets SET show_accepted_message = 1 WHERE id = :id";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':id', $poem['poetid'], 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 = $pdo->prepare($query);
    $stmt->bindParam(':submission_id', $poem_id, PDO::PARAM_INT);
    $stmt->bindParam(':status', $status, PDO::PARAM_INT);
    $stmt->execute();

    // Fetch email configuration from database
    $smtp_query = "SELECT setting_key, setting_value FROM mail_settings WHERE setting_key IN ('mail_host', 'mail_port', 'mail_username', 'mail_password', 'mail_from_address', 'mail_from_name')";
    $smtp_stmt = $pdo->query($smtp_query);
    $smtp_settings = $smtp_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    // Handle missing keys gracefully
    $smtp_host = $smtp_settings['mail_host'] ?? '';
    $smtp_port = $smtp_settings['mail_port'] ?? '';
    $smtp_user = $smtp_settings['mail_username'] ?? '';
    $smtp_pass = $smtp_settings['mail_password'] ?? '';
    $fromEmailAddress = $smtp_settings['mail_from_address'] ?? '';
    $fromEmailName = $smtp_settings['mail_from_name'] ?? '';

    if ($smtp_host && $smtp_user && $smtp_pass && $smtp_port) {
        // Email the poet about the status update using PHPMailer
        try {
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = $smtp_host;
            $mail->SMTPAuth = true;
            $mail->SMTPSecure = $smtp_settings['mail_encryption'] ?? 'ssl';
            $mail->Port = $smtp_port;
            $mail->Username = $smtp_user;
            $mail->Password = $smtp_pass;

            $mail->setFrom($fromEmailAddress, $fromEmailName);
            $mail->addAddress($poem['email'], $poem['author_name'] . ' ' . $poem['author_lastname']);
            $mail->Subject = "Your submission has been updated";

            // Dynamically generate the login URL based on the current domain
            $login_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname(dirname($_SERVER['REQUEST_URI'])) . '/login.php';

            $mail->AltBody = "The status of your submission has been updated.\n\nPlease login to your account to view the new status of your submission.\n\n" . $login_url;

            $msgHTML = 'Your submission has been updated' . '<br /><br />';
            $msgHTML .= 'Please login to your account to view the new status of your submission.<br/><a href="' . $login_url . '">' . $login_url . '</a>';
            $mail->msgHTML($msgHTML);

            if ($mail->send()) {
                $msg = 'Successfully Updated the Status of this Submission. The user has been notified via email';
            } else {
                $msg = 'Successfully Updated the Status of this Submission. There was a problem sending the notification email.';
            }
        } catch (Exception $e) {
            $msg = 'Mailer Error: ' . $mail->ErrorInfo;
        }
    } else {
        $msg = 'Successfully Updated the Status of this Submission. Email configuration is incomplete.';
    }
}

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

<!-- Rest of your HTML code follows -->
<link rel="stylesheet" href="../styles.css"> <!-- Link to external CSS -->

<div class="container" style="max-width: 600px; margin: 20px auto; padding: 20px;">
    <p><a href="javascript: history.back(-1);">&lt;&lt; Go Back to previous page</a></p>
    <h2>Update Submission Status</h2>
    <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>

    <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" <?= $poem['status'] == 0 ? 'selected="selected"' : '' ?>>Pending</option>
                <option value="1" <?= $poem['status'] == 1 ? 'selected="selected"' : '' ?>>Accepted</option>
                <option value="2" <?= $poem['status'] == 2 ? 'selected="selected"' : '' ?>>Rejected</option>
                <option value="3" <?= $poem['status'] == 3 ? 'selected="selected"' : '' ?>>Request Revision</option>
                <?php
                $query = "SELECT * FROM sm_status WHERE id > 3 ORDER BY id";
                $stmt = $pdo->query($query);
                $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
                foreach ($result as $row):
                ?>
                <option value="<?= $row['id'] ?>" <?= $poem['status'] == $row['id'] ? 'selected="selected"' : '' ?>><?= htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8') ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <input name="submit" type="submit" value="Update Status" class="button-primary" />
        <input name="current_status" type="hidden" value="<?= htmlspecialchars($poem['status'], ENT_QUOTES, 'UTF-8') ?>" />
    </form>

    <br /><br />
    <p>Author: <br /><?= htmlspecialchars($poem['author_name'] . ' ' . $poem['author_lastname'], ENT_QUOTES, 'UTF-8') ?></p>
    <p>Author's Email: <br /><a href="mailto:<?= htmlspecialchars($poem['email'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($poem['email'], ENT_QUOTES, 'UTF-8') ?></a></p>
    <p>Title: <br /><?= htmlspecialchars($poem['title'], ENT_QUOTES, 'UTF-8') ?></p>

    <?php if ($poem['body'] != '') { ?>
        <p>Poem: <br /><?= nl2br(htmlspecialchars(stripslashes($poem['body']), ENT_QUOTES, 'UTF-8')) ?></p>
    <?php } ?>

    <?php if ($poem['attachment'] != '') {
        $attachmentName = explode('____', $poem['attachment']);
    ?>
        <p>Attachment: <br /><?= htmlspecialchars($attachmentName[1], ENT_QUOTES, 'UTF-8') ?> [<a href="downloadfile.php?filename=<?= htmlspecialchars($poem['attachment'], ENT_QUOTES, 'UTF-8') ?>">Download File</a>]</p>
    <?php } ?>

    <p>Bio/Comments: <br /><?= nl2br(htmlspecialchars($poem['bio_comments'], ENT_QUOTES, 'UTF-8')) ?></p>

</div>

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