<?php
require_once('common.php');  // Ensure this includes your PDO connection setup as $pdo
require_once('checklogin.php');  // Check if the user is logged in

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

// Ensure $cPoet is set
if (!isset($cPoet)) {
    // Assuming you retrieve poet details using session or some other method
    $stmt = $pdo->prepare("SELECT * FROM sm_poets WHERE id = :id");
    $stmt->bindParam(':id', $_SESSION['poet_id'], PDO::PARAM_INT);
    $stmt->execute();
    $cPoet = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Initialize message variables
$msg = '';

// Handle form submission for notification removal
if (isset($_POST['submit'])) {
    // CSRF protection check
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $msg = '<font color="red">Invalid request. Please try again.</font>';
    } else {
        // Only allow a poet to dismiss notifications on their OWN submissions.
        $stmt = $pdo->prepare(
            "UPDATE sm_submissions_status_updates ssu
             JOIN sm_submissions s ON s.id = ssu.submissionid
             SET ssu.ischecked = 1
             WHERE ssu.id = :id AND s.poetid = :poet_id"
        );
        $stmt->bindValue(':id', (int)($_POST['id'] ?? 0), PDO::PARAM_INT);
        $stmt->bindValue(':poet_id', (int)$cPoet['id'], PDO::PARAM_INT);
        if ($stmt->execute()) {
            $msg = 'Successfully removed the notification from your main page.';
        }
    }
}

// Generate a CSRF token for forms
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // PHP 7+
}

// Credit balance (silent zero if the credits table doesn't exist yet)
require_once(__DIR__ . '/credits.php');
$credit_balance = credits_balance($pdo, (int)$cPoet['id']);

// Include the header and poet's menu
include_once('header.php');
include_once('poets-menu.php');

// Fetch submission statuses from the database
$submission_status = [];
$stmt = $pdo->query("SELECT * FROM sm_status");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $submission_status[$row['id']] = $row['status'];
}
?>

<!-- Main container for the account manager -->
<div class="container centered-content">
    <h1 class="main-title">Welcome to Your Account Manager</h1>
    <span class="msg"><?php echo htmlspecialchars($msg ?? '', ENT_QUOTES, 'UTF-8'); ?></span>

    <?php if ($credit_balance > 0): ?>
      <div style="background: linear-gradient(135deg, #f5efe2 0%, #ece2cb 100%); border: 1px solid #d8c89a; border-left: 4px solid var(--c-brass); padding: 14px 20px; margin: 18px 0; text-align: left; border-radius: 0;">
        <div style="font-family: var(--sans); font-size: 11px; letter-spacing: 0.22em; text-transform: uppercase; color: var(--c-brass-deep); font-weight: 700; margin-bottom: 4px;">Submission Credits</div>
        <p style="margin: 0; font-family: var(--serif); font-size: 15px;">
          You have <strong style="color: var(--c-brass-deep); font-size: 17px;"><?= $credit_balance ?></strong>
          paid-submission credit<?= $credit_balance === 1 ? '' : 's' ?> available.
          Use them on contest entries or paid editions when you submit.
        </p>
      </div>
    <?php endif; ?>

    <?php
    // Display a standardized message if a new item has been accepted
    if (isset($cPoet['show_accepted_message']) && $cPoet['show_accepted_message'] == 1) {
        $accepted_message = settingGet('accepted_message');
        if ($accepted_message !== null) {
            echo '<p>' . nl2br(htmlspecialchars(stripslashes($accepted_message), ENT_QUOTES, 'UTF-8')) . '</p>';
        }
        $stmt = $pdo->prepare("UPDATE sm_poets SET show_accepted_message = 0 WHERE id = :id");
        $stmt->bindParam(':id', $cPoet['id'], PDO::PARAM_INT);
        $stmt->execute();
    }

    // Fetch and display unchecked submission status updates
    $stmt = $pdo->prepare("
        SELECT a.*, b.title, b.id AS sid
        FROM sm_submissions_status_updates AS a
        INNER JOIN sm_submissions AS b ON a.submissionid = b.id
        WHERE a.ischecked = 0 AND b.poetid = :poetid
        ORDER BY a.id DESC
    ");
    $stmt->bindParam(':poetid', $cPoet['id'], PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result as $row) {
        // Ensure the previous and current statuses exist in the $submission_status array
        $previous_status = $submission_status[$row['previous_status']] ?? 'Unknown Status';
        $current_status = $submission_status[$row['status']] ?? 'Unknown Status';
    ?>
        <div class="card">
            <h2><?php echo htmlspecialchars(stripslashes($row['title'] ?? 'Untitled'), ENT_QUOTES, 'UTF-8'); ?></h2>
            <p>Status:<br />
                Changed From <b><?php echo htmlspecialchars(ucfirst($previous_status), ENT_QUOTES, 'UTF-8'); ?></b> to <b><?php echo htmlspecialchars(ucfirst($current_status), ENT_QUOTES, 'UTF-8'); ?></b>
            </p>

            <?php if (!empty($row['note'])) { ?>
                <p>Note from Editor:<br />
                    <i><?php echo nl2br(htmlspecialchars($row['note'], ENT_QUOTES, 'UTF-8')); ?></i>
                </p>
            <?php } ?>
            
            <!-- Remove Notification Button -->
            <form method="post">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">
                <input type="submit" name="submit" value="Remove this Notification" class="button-primary">
            </form>
        </div>
    <?php
    }
    ?>
</div>

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

<!-- Link to your styles.css file -->
<link rel="stylesheet" href="styles.css">
