<?php 
require_once '../db_connect.php';
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// 1. Dynamic Date (English)
$current_date = date('d F Y, l');

// 2. Fetch Stats and Exam List
try {
    // Statistics
    $total_exams = $pdo->query("SELECT COUNT(*) FROM exams")->fetchColumn() ?: 0;
    $active_exams = $pdo->query("SELECT COUNT(*) FROM exams WHERE status = 'active'")->fetchColumn() ?: 0;
    $draft_exams = $pdo->query("SELECT COUNT(*) FROM exams WHERE status = 'inactive'")->fetchColumn() ?: 0;

    // Main Table Data
    $stmt = $pdo->query("SELECT e.*, c.title as course_name FROM exams e JOIN courses c ON e.course_id = c.id ORDER BY e.id DESC");
    $exams = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

// 3. Status Message Handling
$msg = "";
if (isset($_GET['status'])) {
    if ($_GET['status'] == 'updated') {
        $msg = "<div class='alert alert-success d-flex align-items-center border-0 rounded-4 shadow-sm fw-bold mb-4 fade-up' style='border-left: 5px solid #10b981 !important;'><i class='fas fa-check-circle me-3 fa-2x text-success'></i> <div><strong class='d-block text-success'>Success!</strong><span class='text-muted small'>Status updated successfully!</span></div></div>";
    } elseif ($_GET['status'] == 'deleted') {
        $msg = "<div class='alert alert-danger d-flex align-items-center border-0 rounded-4 shadow-sm fw-bold mb-4 fade-up' style='border-left: 5px solid #ef4444 !important;'><i class='fas fa-trash-alt me-3 fa-2x text-danger'></i> <div><strong class='d-block text-danger'>Deleted!</strong><span class='text-muted small'>Exam has been permanently removed.</span></div></div>";
    }
}
?>

<style>
    /* Premium Theme Colors */
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }

    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    
    /* Header & Mobile Menu */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 25px; border-left: 6px solid var(--theme-green); }
    #sidebarToggle { display: none; width: 45px; height: 45px; border-radius: 12px; background: #f1f5f9; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; }
    #sidebarToggle:hover { background: var(--theme-green); color: #fff; }

    .date-badge { background: rgba(6, 78, 59, 0.05); color: var(--theme-green); padding: 6px 18px; border-radius: 50px; font-size: 12px; font-weight: 800; border: 1px solid rgba(6, 78, 59, 0.1); display: inline-block; }
    .btn-theme { background: var(--theme-green); color: #fff; border-radius: 12px; padding: 12px 24px; font-weight: 700; border: none; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
    .btn-theme:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 15px rgba(6, 78, 59, 0.2); }

    /* Stats Card Styling */
    .stat-badge-box { background: #fff; border-radius: 16px; padding: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.04); border-top: 4px solid #ddd; transition: 0.3s; height: 100%; }
    .stat-badge-box:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.08); }
    .sb-green { border-top-color: var(--theme-green); }
    .sb-gold { border-top-color: var(--theme-gold); }
    .sb-dark { border-top-color: var(--theme-dark); }
    .stat-icon { width: 45px; height: 45px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; }

    /* Desktop Table Styling */
    .desktop-table-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; border-top: 5px solid var(--theme-green); }
    .table thead th { background-color: #f1f5f9; color: #64748b; font-size: 11px; text-transform: uppercase; font-weight: 800; padding: 18px 20px; border: none; letter-spacing: 0.5px; }
    .table tbody tr:hover { background-color: #f8fafc; }
    .table td { padding: 15px 20px; vertical-align: middle; font-size: 14px; color: #334155; border-bottom: 1px solid #f1f5f9; }
    
    /* Action Buttons */
    .btn-action { width: 34px; height: 34px; display: inline-flex; align-items: center; justify-content: center; border-radius: 10px; transition: 0.2s; border: 1px solid transparent; text-decoration: none; cursor: pointer;}
    .act-edit { background: rgba(6, 78, 59, 0.08); color: var(--theme-green); }
    .act-edit:hover { background: var(--theme-green); color: #fff; transform: translateY(-2px); }
    .act-delete { background: #fef2f2; color: #ef4444; border-color: #fecaca; }
    .act-delete:hover { background: #ef4444; color: #fff; transform: translateY(-2px); }
    .act-excel { background: #f0fdf4; color: #16a34a; border-color: #bbf7d0; }
    .act-excel:hover { background: #16a34a; color: #fff; transform: translateY(-2px); }
    .act-add-q { background: #fffbeb; color: #d97706; border-color: #fde68a; }
    .act-add-q:hover { background: #d97706; color: #fff; transform: translateY(-2px); }

    /* Animations */
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    /* 📱 Mobile Specific Styles (Card View) */
    .exam-mobile-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; transition: 0.3s; }
    
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .dashboard-header .d-flex { width: 100%; align-items: center; }
        .dashboard-header .btn-theme { width: 100%; } 
        #sidebarToggle { display: inline-flex !important; }
        .header-title { font-size: 1.2rem; }
    }
    @media (min-width: 992px) { #sidebarToggle { display: none !important; } }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center w-100">
            <button class="shadow-sm" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <div>
                <h4 class="mb-1 fw-bold text-dark header-title"><i class="fas fa-file-signature me-2" style="color: var(--theme-green);"></i> Online Exams</h4>
                <div class="date-badge"><i class="far fa-calendar-alt me-2"></i><?= $current_date; ?></div>
            </div>
        </div>
        <a href="add_exam.php" class="btn-theme shadow-sm mt-3 mt-md-0">
            <i class="fas fa-plus-circle me-2"></i> Create New Exam
        </a>
    </div>

    <div class="row g-3 mb-4 fade-up" style="animation-delay: 0.1s;">
        <div class="col-12 col-md-4">
            <div class="stat-badge-box sb-dark d-flex align-items-center">
                <div class="stat-icon bg-dark bg-opacity-10 text-dark me-3"><i class="fas fa-file-alt"></i></div>
                <div>
                    <small class="text-muted fw-bold text-uppercase" style="font-size: 11px; letter-spacing: 0.5px;">Total Exams</small>
                    <h3 class="mb-0 fw-bold" style="color: var(--theme-dark);"><?= sprintf("%02d", $total_exams); ?></h3>
                </div>
            </div>
        </div>
        <div class="col-12 col-md-4">
            <div class="stat-badge-box sb-green d-flex align-items-center">
                <div class="stat-icon bg-success bg-opacity-10 text-success me-3"><i class="fas fa-check-circle"></i></div>
                <div>
                    <small class="text-muted fw-bold text-uppercase" style="font-size: 11px; letter-spacing: 0.5px;">Active Exams</small>
                    <h3 class="mb-0 fw-bold" style="color: var(--theme-green);"><?= sprintf("%02d", $active_exams); ?></h3>
                </div>
            </div>
        </div>
        <div class="col-12 col-md-4">
            <div class="stat-badge-box sb-gold d-flex align-items-center">
                <div class="stat-icon bg-warning bg-opacity-10 text-warning me-3"><i class="fas fa-clock"></i></div>
                <div>
                    <small class="text-muted fw-bold text-uppercase" style="font-size: 11px; letter-spacing: 0.5px;">Drafts / Upcoming</small>
                    <h3 class="mb-0 fw-bold" style="color: var(--theme-gold);"><?= sprintf("%02d", $draft_exams); ?></h3>
                </div>
            </div>
        </div>
    </div>

    <?= $msg; ?>

    <div class="desktop-table-card d-none d-lg-block fade-up" style="animation-delay: 0.2s;">
        <div class="table-responsive">
            <table class="table align-middle border-0 mb-0">
                <thead>
                    <tr>
                        <th class="ps-4">Exam Details</th>
                        <th>Course</th>
                        <th>Created Date</th>
                        <th>Duration & Qus.</th>
                        <th>Status</th>
                        <th class="text-end pe-4">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($exams)): foreach($exams as $ex): ?>
                    <tr>
                        <td class="ps-4 py-3">
                            <div class="fw-bold text-dark" style="font-size: 15px;"><?= htmlspecialchars($ex['exam_title']); ?></div>
                            <small class="text-muted fw-bold">Exam ID: #<?= $ex['id']; ?></small>
                        </td>
                        <td>
                            <span class="badge bg-primary-subtle text-primary border border-primary-subtle px-3 py-2 rounded-pill fw-bold" style="font-size: 10px;">
                                <i class="fas fa-book me-1"></i> <?= htmlspecialchars($ex['course_name']); ?>
                            </span>
                        </td>
                        <td>
                            <div class="small text-dark fw-bold">
                                <i class="far fa-calendar-alt text-muted me-1"></i>
                                <?= date('d M, Y', strtotime($ex['created_at'])); ?>
                            </div>
                        </td>
                        <td>
                            <div class="d-flex flex-column gap-1">
                                <span class="badge bg-light text-dark border px-2 py-1 text-start" style="font-size: 10px; width: fit-content;"><i class="far fa-clock me-1 text-primary"></i> <?= $ex['duration_minutes']; ?> Mins</span>
                                <span class="badge bg-light text-dark border px-2 py-1 text-start" style="font-size: 10px; width: fit-content;"><i class="fas fa-list-ol me-1 text-warning"></i> <?= $ex['total_questions']; ?> Qus.</span>
                            </div>
                        </td>
                        <td>
                            <a href="toggle_exam_status.php?id=<?= $ex['id']; ?>&current=<?= $ex['status']; ?>" 
                               class="btn btn-sm rounded-pill px-3 fw-bold <?= $ex['status'] == 'active' ? 'btn-success shadow-sm' : 'btn-secondary opacity-75'; ?>"
                               style="font-size: 10px; letter-spacing: 0.5px;">
                                <i class="fas <?= $ex['status'] == 'active' ? 'fa-eye' : 'fa-eye-slash'; ?> me-1"></i>
                                <?= strtoupper($ex['status']); ?>
                            </a>
                        </td>
                        <td class="text-end pe-4">
                            <div class="d-flex justify-content-end gap-1">
                                <a href="import_questions.php?exam_id=<?= $ex['id']; ?>" class="btn-action act-excel shadow-sm" title="Excel Import"><i class="fas fa-file-excel"></i></a>
                                <a href="add_questions.php?exam_id=<?= $ex['id']; ?>" class="btn-action act-add-q shadow-sm" title="Add Questions"><i class="fas fa-plus-circle"></i></a>
                                <a href="edit_exam.php?id=<?= $ex['id']; ?>" class="btn-action act-edit shadow-sm" title="Edit Exam"><i class="fas fa-pen"></i></a>
                                <button onclick="deleteExam(<?= $ex['id']; ?>)" class="btn-action act-delete shadow-sm" title="Delete"><i class="fas fa-trash-alt"></i></button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                    <tr><td colspan="6" class="text-center py-5 text-muted fw-bold"><i class="fas fa-file-signature fa-3x mb-3 d-block opacity-25"></i> No exams found currently.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-block d-lg-none fade-up" style="animation-delay: 0.2s;">
        <div class="row g-3">
            <?php if(!empty($exams)): foreach($exams as $ex): ?>
            <div class="col-12">
                <div class="exam-mobile-card p-3">
                    <div class="d-flex justify-content-between align-items-start mb-3 pb-3 border-bottom">
                        <div>
                            <h6 class="fw-bold text-dark mb-1" style="font-size: 15px;"><?= htmlspecialchars($ex['exam_title']); ?></h6>
                            <span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill" style="font-size: 9px; padding: 3px 8px;">
                                <i class="fas fa-book me-1"></i> <?= htmlspecialchars($ex['course_name']); ?>
                            </span>
                        </div>
                        <a href="toggle_exam_status.php?id=<?= $ex['id']; ?>&current=<?= $ex['status']; ?>" class="badge <?= $ex['status'] == 'active' ? 'bg-success' : 'bg-secondary' ?> text-decoration-none" style="font-size: 10px; padding: 5px 10px;">
                            <i class="fas <?= $ex['status'] == 'active' ? 'fa-eye' : 'fa-eye-slash'; ?>"></i> <?= strtoupper($ex['status']); ?>
                        </a>
                    </div>
                    
                    <div class="bg-light p-3 rounded-3 border mb-3">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-muted fw-bold" style="font-size: 11px;"><i class="far fa-calendar-alt text-primary me-1"></i> <?= date('d M, Y', strtotime($ex['created_at'])); ?></span>
                            <span class="text-muted fw-bold" style="font-size: 11px;">ID: #<?= $ex['id']; ?></span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center border-top pt-2 mt-2">
                            <span class="text-dark fw-bold" style="font-size: 12px;"><i class="far fa-clock text-success me-1"></i> <?= $ex['duration_minutes']; ?> Mins</span>
                            <span class="text-dark fw-bold" style="font-size: 12px;"><i class="fas fa-list-ol text-warning me-1"></i> <?= $ex['total_questions']; ?> Qus.</span>
                        </div>
                    </div>
                    
                    <div class="row g-2">
                        <div class="col-6">
                            <a href="add_questions.php?exam_id=<?= $ex['id']; ?>" class="btn btn-light border w-100 fw-bold" style="font-size: 11px; padding: 8px; color: #d97706;"><i class="fas fa-plus-circle me-1"></i> Add Qus.</a>
                        </div>
                        <div class="col-6">
                            <a href="import_questions.php?exam_id=<?= $ex['id']; ?>" class="btn btn-light border w-100 fw-bold" style="font-size: 11px; padding: 8px; color: #16a34a;"><i class="fas fa-file-excel me-1"></i> Import</a>
                        </div>
                        <div class="col-6">
                            <a href="edit_exam.php?id=<?= $ex['id']; ?>" class="btn btn-light border w-100 fw-bold text-primary" style="font-size: 11px; padding: 8px;"><i class="fas fa-pen me-1"></i> Edit</a>
                        </div>
                        <div class="col-6">
                            <button onclick="deleteExam(<?= $ex['id']; ?>)" class="btn btn-light border w-100 fw-bold text-danger" style="font-size: 11px; padding: 8px;"><i class="fas fa-trash-alt me-1"></i> Delete</button>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; else: ?>
                <div class="col-12 text-center py-5 bg-white rounded-4 border shadow-sm">
                    <i class="fas fa-file-signature fa-3x text-muted opacity-25 mb-3 d-block"></i>
                    <h6 class="fw-bold text-muted">No exams found!</h6>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<script>
function deleteExam(id) {
    if (confirm('Are you sure? Deleting this exam will permanently remove all questions and student results associated with it!')) {
        window.location.href = 'delete_exam.php?id=' + id;
    }
}

// Mobile Sidebar Toggle
document.addEventListener("DOMContentLoaded", function() {
    const toggleBtn = document.getElementById('sidebarToggle');
    if (toggleBtn) {
        toggleBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const sidebar = document.querySelector('.sidebar') || document.getElementById('sidebarMenu');
            if (sidebar) { sidebar.classList.toggle('active'); }
        });
    }
});
</script>

<?php include 'includes/footer.php'; ?>