<?php
session_start();
require_once('common.php');
require_once('checklogin.php');
require_once('config.php');
include_once('header.php');
include_once('poets-menu.php');

// CSRF Token Generation
if (empty($_SESSION['csrf_token'])) {
    if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // PHP 7+
    } else {
        $_SESSION['csrf_token'] = bin2hex(openssl_random_pseudo_bytes(16)); // PHP 5.6 fallback
    }
}

// Message initialization
$msg = '';

// Fetch settings for allowing withdrawals and downloads
$allow_withdraws = settingGet('allow_withdraws') === 'yes';
$allow_downloads = settingGet('allow_downloads') === 'yes';

// Handle submission deletion
if (isset($_GET['delete']) && isset($_GET['csrf_token']) && $_GET['csrf_token'] === $_SESSION['csrf_token']) {
    $stmt = $pdo->prepare("DELETE FROM sm_submissions WHERE id = :id AND poetid = :poetid");
    $stmt->bindParam(':id', $_GET['delete'], PDO::PARAM_INT);
    $stmt->bindParam(':poetid', $cPoet['id'], PDO::PARAM_INT);
    if ($stmt->execute()) {
        $msg = 'You have successfully withdrawn your submission.';
    } else {
        $msg = 'Error withdrawing submission. Please try again later.';
    }
}

// Handle withdrawal request
if (isset($_GET['withdraw']) && isset($_GET['csrf_token']) && $_GET['csrf_token'] === $_SESSION['csrf_token']) {
    $stmt = $pdo->prepare("DELETE FROM sm_submissions WHERE id = :id AND poetid = :poetid");
    $stmt->bindParam(':id', $_GET['withdraw'], PDO::PARAM_INT);
    $stmt->bindParam(':poetid', $cPoet['id'], PDO::PARAM_INT);
    if ($stmt->execute()) {
        $msg = 'You have successfully withdrawn your submission.';

        $stmt2 = $pdo->prepare("DELETE FROM sm_submissions_status_updates WHERE submissionid = :submissionid");
        $stmt2->bindParam(':submissionid', $_GET['withdraw'], PDO::PARAM_INT);
        $stmt2->execute();
    } else {
        $msg = 'Error withdrawing submission. Please try again later.';
    }
}

// Handle payment success message
if (isset($_GET['sucess-payment'])) {
    $msg = 'Submission Successful.';
}

// 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'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Submissions</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f4f4f9;
            margin: 0;
            padding: 0;
            color: #333;
        }

        h2 {
            font-size: 2.5rem;
            color: #333;
            text-align: center;
            margin-top: 30px;
        }

        .msg {
            text-align: center;
            font-size: 1.2rem;
            color: green;
            margin-bottom: 20px;
        }

        table.list {
            width: 80%;
            margin: 20px auto;
            border-collapse: collapse;
            box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1);
        }

        table.list th, table.list td {
            padding: 15px;
            text-align: left;
            font-size: 1rem;
        }

        table.list th {
            background-color: #4A90E2;
            color: white;
            text-transform: uppercase;
            letter-spacing: 0.1rem;
        }

        table.list tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        table.list tr:hover {
            background-color: #f1f1f1;
        }

        table.list td a {
            color: #4A90E2;
            text-decoration: none;
            font-weight: bold;
        }

        table.list td a:hover {
            text-decoration: underline;
        }

        .centered-button {
            display: block;
            width: 200px;
            margin: 30px auto;
            padding: 15px;
            background-color: #4A90E2;
            color: white;
            text-align: center;
            border: none;
            border-radius: 5px;
            font-size: 1.1rem;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .centered-button:hover {
            background-color: #357ABD;
        }

        .highlight {
            background-color: #fff3cd;
        }

        .highlight td {
            border-left: 5px solid #ffecb5;
        }

        @media only screen and (max-width: 768px) {
            table.list {
                width: 95%;
            }
        }
    </style>
</head>
<body>

<h2>My Submissions</h2>
<?php if (isset($_GET['success-payment'])):
  $parts = [];
  $parts[] = (($_GET['entry'] ?? '') === 'contest')
      ? 'Payment received — your contest entry has been submitted. Thank you!'
      : 'Your submission has been received.';
?>
  <p class="msg" style="color:#2e7d32; font-weight:600;"><?= htmlspecialchars(implode(' ', $parts), ENT_QUOTES, 'UTF-8') ?></p>
<?php endif; ?>

<!-- Display message if available -->
<?php if ($msg): ?>
    <div class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>

<!-- Submissions Table -->
<table class="list">
    <tr>
        <th>Date Submitted</th>
        <th>Title</th>
        <th>Status</th>
        <th>Edition</th>
        <th>Options</th>
    </tr>
<?php
// Fetch and display the user's submissions securely using PDO
$stmt = $pdo->prepare("
    SELECT sm_submissions.*, 
           rev.date_sent AS last_update_date, 
           rev.sender_type, 
           rev.sender_id 
    FROM sm_submissions 
    LEFT JOIN sm_revisions rev 
        ON sm_submissions.id = rev.submission_id 
        AND rev.date_sent = (
            SELECT MAX(r.date_sent)
            FROM sm_revisions r
            WHERE r.submission_id = sm_submissions.id
        )
    WHERE sm_submissions.poetid = :poetid 
    ORDER BY sm_submissions.date_submitted DESC
");

$stmt->bindParam(':poetid', $cPoet['id'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($result as $row) {
    $date_submitted = !empty($row['date_submitted']) ? date('M. d, Y h:ia', strtotime($row['date_submitted'])) : 'Unknown';
    $title = !empty($row['title']) ? htmlspecialchars(stripslashes($row['title']), ENT_QUOTES, 'UTF-8') : 'Untitled';
    // Get the status from the submission_status array
    $status = (isset($submission_status[$row['status']])) ? htmlspecialchars($submission_status[$row['status']], ENT_QUOTES, 'UTF-8') : 'Unknown';
    $edition_name = !empty($row['editionid']) ? htmlspecialchars(getEditionName($row['editionid']), ENT_QUOTES, 'UTF-8') : 'Unknown';
    $attachment_name = !empty($row['attachment']) ? htmlspecialchars($row['attachment'], ENT_QUOTES, 'UTF-8') : '';
    
    // Highlight row if the status is "Request Revision"
    $highlight_class = ($row['status'] == 3) ? 'highlight' : '';

    // Get last update information
    $last_update_date = !empty($row['last_update_date']) ? date('M. d, Y h:ia', strtotime($row['last_update_date'])) : 'No updates yet';
    // Show "You" if sender is poet, otherwise "Editor"
    $sender_name = ($row['sender_type'] === 'poet') ? 'You' : 'Editor';
?>
    <tr class="<?= $highlight_class ?>">
        <td><?= $date_submitted ?></td>
        <td><a href="gen-sub.php?id=<?= $row['id'] ?>"><?= $title ?></a></td>
        <td><?= $status ?></td>
        <td><?= $edition_name ?></td>
        <td>
            <?php if ($allow_withdraws && $row['status'] == 0) { ?>
            [<a href="javascript: if (confirm('Are you sure you want to withdraw this?')) { location.href = 'my-submissions.php?delete=<?= $row['id'] ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>'; }">WITHDRAW</a>] 
            <?php } ?>
            <?php if ($allow_downloads && $attachment_name): ?>
            [<a href="attachments/<?= $attachment_name ?>" download>DOWNLOAD</a>]
            <?php endif; ?>
            <?php if ($row['status'] == 3): ?>
            [<a href="revisions.php?id=<?= $row['id'] ?>">REVISION TOOL</a>]<br>
            <small>Last Revision Update: <?= $last_update_date ?> by <?= $sender_name ?></small>
            <?php endif; ?>
        </td>
    </tr>
<?php
}
$stmt->closeCursor();
?>
</table>

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

</body>
</html>
