<?php
session_start();
require_once 'includes/header.php';
require_once 'db/config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];

$pdo = db();
$stmt = $pdo->prepare('SELECT cs.id, c.title as challenge_title, cs.language, cs.status, cs.submitted_at FROM challenge_submissions cs JOIN challenges c ON cs.challenge_id = c.id WHERE cs.user_id = ? ORDER BY cs.submitted_at DESC');
$stmt->execute([$user_id]);
$submissions = $stmt->fetchAll();
?>

<div class="container py-5">
    <h1 class="display-4 fw-bold">My Submissions</h1>
    <p class="fs-5 text-muted">Here is a list of your submissions.</p>

    <table class="table table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Challenge</th>
                <th>Language</th>
                <th>Status</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($submissions) > 0) : ?>
                <?php foreach ($submissions as $submission) : ?>
                    <tr>
                        <td><?php echo $submission['id']; ?></td>
                        <td><?php echo htmlspecialchars($submission['challenge_title']); ?></td>
                        <td><?php echo htmlspecialchars($submission['language']); ?></td>
                        <td><span class="badge bg-<?php echo get_status_badge_class($submission['status']); ?>"><?php echo htmlspecialchars($submission['status']); ?></span></td>
                        <td><?php echo $submission['submitted_at']; ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php else : ?>
                <tr>
                    <td colspan="5" class="text-center">You have not made any submissions yet.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php
function get_status_badge_class($status) {
    switch ($status) {
        case 'passed':
            return 'success';
        case 'failed':
            return 'danger';
        case 'pending':
            return 'warning';
        default:
            return 'secondary';
    }
}

include 'includes/footer.php';
?>
