<?php
include 'includes/header.php';
require_once 'db/config.php';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: challenges.php');
    exit();
}

$challenge_id = $_GET['id'];

$pdo = db();
$stmt = $pdo->prepare('SELECT * FROM challenges WHERE id = ? AND deleted_at IS NULL');
$stmt->execute([$challenge_id]);
$challenge = $stmt->fetch();

if (!$challenge) {
    header('Location: challenges.php');
    exit();
}

$user_id = $_SESSION['user_id'] ?? null;
$submissions = [];
if ($user_id) {
    $stmt = $pdo->prepare('SELECT * FROM challenge_submissions WHERE user_id = ? AND challenge_id = ? ORDER BY submitted_at DESC');
    $stmt->execute([$user_id, $challenge_id]);
    $submissions = $stmt->fetchAll();
}

?>

<div class="container py-5">
    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">Submit Your Solution</h5>
                    <form action="submit_solution.php" method="post">
                        <input type="hidden" name="challenge_id" value="<?php echo $challenge['id']; ?>">
                        <div class="mb-3">
                            <label for="language" class="form-label">Language</label>
                            <select class="form-select" id="language" name="language" required>
                                <option value="python">Python</option>
                                <option value="javascript">JavaScript</option>
                                <option value="php">PHP</option>
                                <option value="html">HTML</option>
                                <option value="css">CSS</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="solution" class="form-label">Your Code</label>
                            <div id="editor"></div>
                            <textarea class="form-control d-none" id="solution" name="solution" rows="10" required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">Submit Solution</button>
                        <button type="button" class="btn btn-secondary" id="run-code">Run Code</button>
                    </form>
                    <div id="output" class="mt-3"></div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <h1 class="display-4 fw-bold"><?php echo htmlspecialchars($challenge['title']); ?></h1>
            <p class="fs-5 text-muted"><strong>Difficulty:</strong> <?php echo htmlspecialchars($challenge['difficulty']); ?> | <strong>Learning Style:</strong> <?php echo htmlspecialchars($challenge['learning_style']); ?></p>
            <hr>
            <ul class="nav nav-tabs" id="challengeTab" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="description-tab" data-bs-toggle="tab" data-bs-target="#description" type="button" role="tab" aria-controls="description" aria-selected="true">Description</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="submissions-tab" data-bs-toggle="tab" data-bs-target="#submissions" type="button" role="tab" aria-controls="submissions" aria-selected="false">My Submissions</button>
                </li>
            </ul>
            <div class="tab-content" id="challengeTabContent">
                <div class="tab-pane fade show active" id="description" role="tabpanel" aria-labelledby="description-tab">
                    <div class="pt-4">
                        <h2>Description</h2>
                        <p><?php echo nl2br(htmlspecialchars($challenge['description'])); ?></p>
                        <?php if (!empty($challenge['sample_cases_json'])) : ?>
                            <h2>Sample Cases</h2>
                            <pre class="bg-light p-3 rounded"><code><?php
                                $samples = json_decode($challenge['sample_cases_json'], true);
                                foreach ($samples as $sample) {
                                    echo "<strong>Input:</strong>\n" . htmlspecialchars($sample['input']) . "\n";
                                    echo "<strong>Output:</strong>\n" . htmlspecialchars($sample['output']) . "\n\n";
                                }
                            ?></code></pre>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="tab-pane fade" id="submissions" role="tabpanel" aria-labelledby="submissions-tab">
                    <div class="pt-4">
                        <h2>My Submissions</h2>
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Attempt</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['attempt_number']; ?></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="4" class="text-center">You have not made any submissions for this challenge yet.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</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';
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var editor = CodeMirror(document.getElementById('editor'), {
        lineNumbers: true,
        mode: 'python',
        theme: 'default'
    });
    var solutionTextarea = document.getElementById('solution');
    editor.on('change', function() {
        solutionTextarea.value = editor.getValue();
    });

    var languageSelect = document.getElementById('language');
    languageSelect.addEventListener('change', function() {
        var mode = this.value;
        if (mode === 'html' || mode === 'xml') {
            mode = 'htmlmixed';
        }
        editor.setOption('mode', mode);
    });
});
</script>

