<?= $this->extend('layout/main_layout') ?>
<?= $this->section('content') ?>
<div class="container-xxl py-5">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4 gap-3">
            <h1 class="h3 mb-0">Exam Drafts</h1>
            <?php if (!empty($semester) || !empty($schoolYear)): ?>
                <div class="text-muted small">
                    <?= esc($semester ?: 'Semester') ?> <?= esc($schoolYear ?: '') ?>
                </div>
            <?php endif; ?>
        </div>

        <?php if (session()->getFlashdata('success')): ?>
            <div class="alert alert-success">
                <?= esc(session()->getFlashdata('success')) ?>
            </div>
        <?php elseif (session()->getFlashdata('error')): ?>
            <div class="alert alert-danger">
                <?= esc(session()->getFlashdata('error')) ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($validation) && $validation->getErrors()): ?>
            <div class="alert alert-danger">
                <ul class="mb-0">
                    <?php foreach ($validation->getErrors() as $error): ?>
                        <li><?= esc($error) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <ul class="nav nav-pills mb-3" id="teacherExamTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="new-tab" data-bs-toggle="pill" data-bs-target="#new" type="button" role="tab" aria-controls="new" aria-selected="true">
                    New Exams
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="legacy-tab" data-bs-toggle="pill" data-bs-target="#legacy" type="button" role="tab" aria-controls="legacy" aria-selected="false">
                    Previous Exams
                </button>
            </li>
        </ul>
        <div class="tab-content" id="teacherExamTabsContent">
            <div class="tab-pane fade show active" id="new" role="tabpanel" aria-labelledby="new-tab">
                <div class="card mb-4">
                    <div class="card-header">
                        Submit a new draft
                    </div>
                    <div class="card-body">
                        <p class="text-muted small mb-3">
                            Max upload size: <?= esc(number_format($maxUploadBytes / (1024 * 1024))) ?> MB.
                            Allowed file types: Word documents only (.doc/.docx).
                        </p>
                        <form method="post" action="<?= base_url('/teacher/exam-drafts') ?>" enctype="multipart/form-data">
                            <?= csrf_field() ?>
                            <div class="row g-3">
                                <input type="hidden" name="class_section_id" value="<?= esc($selectedClassSection ?? 0) ?>">
                                <div class="col-lg-6">
                                    <label class="form-label">Exam type</label>
                                    <select name="exam_type" class="form-select">
                                        <option value="">Select type (optional)</option>
                                        <?php $selectedType = old('exam_type'); ?>
                                        <?php foreach ($examTypes as $type): ?>
                                            <option value="<?= esc($type) ?>" <?= $type === $selectedType ? 'selected' : '' ?>>
                                                <?= esc($type) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-lg-6">
                                    <label class="form-label">Draft file</label>
                                    <input
                                        type="file"
                                        name="draft_file"
                                        class="form-control"
                                        <?= empty($assignments) ? 'disabled' : '' ?>
                                    />
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Notes / instructions</label>
                                    <textarea
                                        name="description"
                                        rows="3"
                                        class="form-control"
                                        placeholder="Share context for the reviewer..."
                                        <?= empty($assignments) ? 'disabled' : '' ?>><?= esc(old('description')) ?></textarea>
                                </div>
                            </div>
                            <div class="text-end mt-3">
                                <button type="submit" class="btn btn-primary" <?= empty($assignments) ? 'disabled' : '' ?>>
                                    Send for review
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        Previous submissions
                    </div>
                    <div class="card-body">
                        <?php if (empty($drafts)): ?>
                            <p class="text-muted">You have not submitted any exam drafts yet.</p>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-borderless align-middle">
                                    <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Version</th>
                                    <th>Submitted</th>
                                    <th>Status</th>
                                    <th>Files & Review</th>
                                </tr>
                                    </thead>
                                    <tbody>
                                <?php foreach ($drafts as $draft): ?>
                                    <?php
                                        $statusInfo = $statusBadges[$draft['status'] ?? 'pending'] ?? ['label' => 'Unknown', 'class' => 'bg-secondary text-white'];
                                    ?>
                                    <tr>
                                        <td><?= esc($draft['exam_type'] ?? 'N/A') ?></td>
                                        <td class="text-nowrap">v<?= esc($draft['version'] ?? 1) ?></td>
                                        <td class="text-nowrap"><?= esc((!empty($draft['created_at']) ? local_datetime($draft['created_at'], 'M j, Y g:i A') : '—')) ?></td>
                                        <td>
                                            <span class="badge <?= esc($statusInfo['class']) ?>">
                                                <?= esc($statusInfo['label']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if (!empty($draft['teacher_file'])): ?>
                                                <div>
                                                    <a href="<?= base_url('exam-drafts/files/teacher/' . $draft['teacher_file']) ?>" target="_blank">
                                                        <?= esc($draft['teacher_filename'] ?? 'Download submitted file') ?>
                                                    </a>
                                                    <a href="<?= base_url('exam-drafts/files/teacher/' . $draft['teacher_file']) ?>" target="_blank" class="btn btn-sm btn-outline-secondary ms-2">
                                                        View
                                                    </a>
                                                </div>
                                            <?php else: ?>
                                                <div class="text-muted small">No file uploaded</div>
                                            <?php endif; ?>
                                            <?php if (!empty($draft['admin_comments'])): ?>
                                                <div class="mt-2">
                                                    <strong class="small">Review notes:</strong>
                                                    <div class="small text-secondary"><?= esc($draft['admin_comments']) ?></div>
                                                </div>
                                            <?php endif; ?>
                                            <?php if (!empty($draft['final_file'])): ?>
                                                <div class="mt-2">
                                                    <a href="<?= base_url('exam-drafts/files/final/' . $draft['final_file']) ?>" target="_blank" class="link-success small">
                                                        <?= esc($draft['final_filename'] ?? 'Download final draft') ?>
                                                    </a>
                                                    <a href="<?= base_url('exam-drafts/files/final/' . $draft['final_file']) ?>" target="_blank" class="btn btn-sm btn-outline-secondary ms-2">
                                                        View
                                                    </a>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="tab-pane fade" id="legacy" role="tabpanel" aria-labelledby="legacy-tab">
                <div class="card">
                    <div class="card-header">
                        Previous exams by class section
                    </div>
                    <div class="card-body">
                        <?php if (empty($legacyExams)): ?>
                            <p class="text-muted mb-0">No previous exams available for your classes yet.</p>
                        <?php else: ?>
                            <?php
                                $grouped = [];
                                foreach ($legacyExams as $item) {
                                    $cid = $item['class_section_id'] ?? 0;
                                    $grouped[$cid]['name'] = $item['class_section_name'] ?? ('Class ' . $cid);
                                    $grouped[$cid]['items'][] = $item;
                                }
                            ?>
                            <?php foreach ($grouped as $cid => $group): ?>
                                <div class="mb-3">
                                    <h6 class="mb-2"><?= esc($group['name']) ?></h6>
                                    <div class="list-group">
                                        <?php foreach ($group['items'] as $item): ?>
                                            <div class="list-group-item d-flex justify-content-between align-items-start">
                                                <div class="me-3">
                                                    <div class="fw-semibold"><?= esc($item['draft_title'] ?? 'Legacy Exam') ?></div>
                                                    <div class="small text-muted">
                                                        <?= esc($item['exam_type'] ?? 'N/A') ?> •
                                                        <?= esc($item['semester'] ?? '') ?> <?= esc($item['school_year'] ?? '') ?>
                                                    </div>
                                                </div>
                                                <div class="text-end">
                                                    <?php if (!empty($item['final_file'])): ?>
                                                        <a href="<?= base_url('exam-drafts/files/final/' . $item['final_file']) ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                                            Download
                                                        </a>
                                                        <a href="<?= base_url('exam-drafts/files/final/' . $item['final_file']) ?>" target="_blank" class="btn btn-sm btn-outline-secondary ms-2">
                                                            View
                                                        </a>
                                                    <?php else: ?>
                                                        <span class="text-muted small">File missing</span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>
