<?php
require_once('../common.php');
require_once('checklogin.php');
require_once('../config.php'); // Include PDO database configuration

// Ensure $showipaddress is defined
$showipaddress = "no"; // Default value, or fetch it dynamically

// Define submission statuses as a static array
$submission_status = [
    0 => 'Pending',
    1 => 'Approved',
    2 => 'Rejected',
    3 => 'In Review',
    4 => 'Published',
    // Add more statuses as needed
];

// Function to sanitize user input and prevent XSS
function sanitize_input($input) {
    if ($input === null) {
        return ''; // Handle null input safely
    }
    return htmlspecialchars(trim((string)$input), ENT_QUOTES, 'UTF-8');
}

// Function to generate CSRF token
function generate_csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Function to validate CSRF token
function validate_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

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

// Redirect if poet ID is not set
if (!isset($_GET['poetid']) || empty($_GET['poetid'])) {
    header('Location: editors-search.php');
    exit;
}

$poetid = intval($_GET['poetid']);  // Ensure poet ID is an integer

// Handle submission deletion securely using prepared statements
$msg = '';
if (isset($_GET['delete']) && validate_csrf_token($_GET['csrf_token'])) {
    $delete_id = intval($_GET['delete']);  // Ensure delete ID is an integer

    $stmt = $pdo->prepare("DELETE FROM sm_submissions WHERE id = :delete_id AND poetid = :poetid");
    if ($stmt->execute(['delete_id' => $delete_id, 'poetid' => $poetid])) {
        $msg = "The submission has been successfully deleted.";
    } else {
        $msg = "Failed to delete the submission. Please try again.";
    }
}

include_once('header.php');
include_once('editors-menu.php');
?>
<center><h2>User History</h2></center>
<?php if (!empty($msg)): ?>
<div style="text-align: center; color: green; font-size: 18px; margin-bottom: 20px;">
    <?= sanitize_input($msg) ?>
</div>
<?php endif; ?>
<table width="1000" border="5" cellpadding="15" align="center">
    <tr>
        <th>Date Submitted</th>
        <th>Title</th>
        <th>Contributor</th>        
        <th>Edition</th>                
        <th>Status</th>
        <?php if ($showipaddress == "yes"): ?><th>IP Address</th><?php endif ?>
        <th>Tools</th>
    </tr>
<?php
// Secure query using PDO
$stmt = $pdo->prepare("
    SELECT a.id AS sid, a.title, a.date_submitted, a.status, a.editionid, a.ip_address, 
           b.author_name, b.author_lastname
    FROM sm_submissions AS a
    INNER JOIN sm_poets AS b ON a.poetid = b.id
    WHERE a.poetid = :poetid
    ORDER BY a.status, a.date_submitted DESC");

$stmt->execute(['poetid' => $poetid]);

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
    <tr>
        <td><?= date('M. d, Y h:ia', strtotime($row['date_submitted'])) ?></td>
        <td><a href="view-submission.php?id=<?= intval($row['sid']) ?>"><?= sanitize_input($row['title']) ?></a></td>
        <td><?= sanitize_input($row['author_name']) ?> <?= sanitize_input($row['author_lastname']) ?></td>
        <td><?= sanitize_input(getEditionName($row['editionid'])) ?></td>
        <td><?= isset($submission_status[$row['status']]) ? sanitize_input($submission_status[$row['status']]) : 'Unknown (ID: ' . intval($row['status']) . ')' ?></td>
        <?php if ($showipaddress == "yes"): ?><td><?= sanitize_input($row['ip_address']) ?></td><?php endif ?>
        <td>
            [<a href="editors-update-status.php?id=<?= intval($row['sid']) ?>">Update Status</a>] 
            <?php if ($row['status'] != 1): // Hide delete button for "Approved" submissions ?>
            [<a href="#" onclick="confirmDelete('<?= intval($row['sid']) ?>', '<?= $poetid ?>')">Delete</a>]
            <?php endif; ?>
        </td>
    </tr>
<?php
}
?>
</table>

<script>
// JavaScript function for delete confirmation
function confirmDelete(submissionId, poetId) {
    if (confirm("Are you sure you want to delete this submission? This action cannot be undone.")) {
        const csrfToken = '<?= generate_csrf_token() ?>';
        window.location.href = `user_history.php?delete=${submissionId}&poetid=${poetId}&csrf_token=${csrfToken}`;
    }
}
</script>

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