<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
requireAdmin();

$db = getDB();
$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $name = sanitize($_POST['exam_name'] ?? '');
        $date = $_POST['exam_date'] ?? '';
        $desc = sanitize($_POST['description'] ?? '');
        
        if (!$name || !$date) { $error = 'Name and date are required.'; }
        else {
            $stmt = $db->prepare("INSERT INTO exam_dates (exam_name, exam_date, description) VALUES (?,?,?)");
            $stmt->bind_param("sss", $name, $date, $desc);
            $stmt->execute();
            $success = 'Exam date added!';
        }
    } elseif ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $db->query("UPDATE exam_dates SET is_active = !is_active WHERE id=$id");
        $success = 'Updated.';
    } elseif ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $db->query("DELETE FROM exam_dates WHERE id=$id");
        $success = 'Exam date deleted.';
    } elseif ($action === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $name = sanitize($_POST['exam_name'] ?? '');
        $date = $_POST['exam_date'] ?? '';
        $desc = sanitize($_POST['description'] ?? '');
        $stmt = $db->prepare("UPDATE exam_dates SET exam_name=?, exam_date=?, description=? WHERE id=?");
        $stmt->bind_param("sssi", $name, $date, $desc, $id);
        $stmt->execute();
        $success = 'Exam date updated!';
    }
}

$exams = $db->query("SELECT * FROM exam_dates ORDER BY exam_date ASC")->fetch_all(MYSQLI_ASSOC);

$pageTitle = 'A/L Exam Dates';
include __DIR__ . '/../includes/header.php';
?>

<div class="app-layout">
    <?php include __DIR__ . '/../includes/sidebar.php'; ?>
    
    <div class="main-content">
        <div class="topbar">
            <button class="topbar-toggle" id="sidebarToggle"><i class="fa fa-bars"></i></button>
            <div class="topbar-title">A/L Exam Dates</div>
            <div class="topbar-actions">
                <button class="btn btn-primary btn-sm" onclick="openModal('addExamModal')">
                    <i class="fa fa-plus"></i> Add Exam Date
                </button>
            </div>
        </div>
        
        <div class="page-content">
            <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
            <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
            
            <div class="alert alert-info">
                <i class="fa fa-info-circle"></i>
                <strong>Note:</strong> Only active exam dates will appear in the student dashboard countdown. Set one exam as active for the main countdown display.
            </div>
            
            <?php if (empty($exams)): ?>
            <div class="card">
                <div class="empty-state">
                    <div class="empty-icon">📅</div>
                    <h3>No exam dates set</h3>
                    <p>Add the A/L examination date to show countdown to students</p>
                    <button class="btn btn-primary btn-sm mt-2" onclick="openModal('addExamModal')">Add Exam Date</button>
                </div>
            </div>
            <?php else: ?>
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:16px;">
                <?php foreach ($exams as $e): 
                    $daysLeft = ceil((strtotime($e['exam_date']) - time()) / 86400);
                    $isPast = $daysLeft < 0;
                ?>
                <div class="card" style="border-color:<?= $e['is_active'] ? 'rgba(99,102,241,0.5)' : 'var(--border)' ?>">
                    <div class="card-body" style="padding:20px;">
                        <div class="d-flex justify-between align-center" style="margin-bottom:12px;">
                            <span class="badge <?= $e['is_active'] ? 'badge-success' : 'badge-secondary' ?>">
                                <?= $e['is_active'] ? '✅ Active' : 'Inactive' ?>
                            </span>
                            <span class="badge <?= $isPast ? 'badge-danger' : 'badge-info' ?>">
                                <?= $isPast ? 'Past' : $daysLeft . ' days left' ?>
                            </span>
                        </div>
                        
                        <h3 style="font-size:17px;font-weight:700;margin-bottom:6px;"><?= htmlspecialchars($e['exam_name']) ?></h3>
                        
                        <div style="font-size:22px;font-weight:800;background:var(--gradient);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;margin-bottom:4px;">
                            <?= date('F j, Y', strtotime($e['exam_date'])) ?>
                        </div>
                        
                        <?php if ($e['description']): ?>
                        <p class="font-sm text-secondary" style="margin-bottom:12px;"><?= htmlspecialchars($e['description']) ?></p>
                        <?php endif; ?>
                        
                        <?php if (!$isPast && $e['is_active']): ?>
                        <!-- Mini countdown for active exam -->
                        <div style="background:rgba(99,102,241,0.1);border-radius:8px;padding:10px;text-align:center;margin-bottom:12px;" data-date="<?= $e['exam_date'] ?>">
                            <div style="font-size:20px;font-weight:700;color:var(--accent);" id="minicd-<?= $e['id'] ?>">
                                <?= $daysLeft ?>d left
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div style="display:flex;gap:6px;flex-wrap:wrap;">
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="action" value="toggle">
                                <input type="hidden" name="id" value="<?= $e['id'] ?>">
                                <button type="submit" class="btn btn-sm <?= $e['is_active'] ? 'btn-warning' : 'btn-success' ?>">
                                    <i class="fa <?= $e['is_active'] ? 'fa-pause' : 'fa-play' ?>"></i>
                                    <?= $e['is_active'] ? 'Deactivate' : 'Activate' ?>
                                </button>
                            </form>
                            <button class="btn btn-secondary btn-sm" onclick="editExam(<?= $e['id'] ?>, '<?= addslashes($e['exam_name']) ?>', '<?= $e['exam_date'] ?>', '<?= addslashes($e['description']) ?>')">
                                <i class="fa fa-edit"></i> Edit
                            </button>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?')">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $e['id'] ?>">
                                <button type="submit" class="btn btn-sm" style="background:rgba(239,68,68,0.1);color:#ef4444;border:1px solid rgba(239,68,68,0.2);"><i class="fa fa-trash"></i></button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add Exam Modal -->
<div class="modal-overlay" id="addExamModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title" id="examModalTitle">Add Exam Date</h3>
            <button class="modal-close" onclick="closeModal('addExamModal')"><i class="fa fa-times"></i></button>
        </div>
        <div class="modal-body">
            <form method="POST" id="examForm">
                <input type="hidden" name="action" id="examAction" value="add">
                <input type="hidden" name="id" id="examId">
                
                <div class="form-group">
                    <label class="form-label">Exam Name *</label>
                    <input type="text" name="exam_name" id="examName" class="form-control" placeholder="e.g., A/L Examination 2025" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Exam Date *</label>
                    <input type="date" name="exam_date" id="examDate" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="description" id="examDesc" class="form-control" rows="3" placeholder="Optional notes..."></textarea>
                </div>
                
                <div style="display:flex;gap:12px;justify-content:flex-end;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('addExamModal')">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="<?= APP_URL ?>/assets/js/main.js"></script>
<script>
function editExam(id, name, date, desc) {
    document.getElementById('examAction').value = 'edit';
    document.getElementById('examId').value = id;
    document.getElementById('examName').value = name;
    document.getElementById('examDate').value = date;
    document.getElementById('examDesc').value = desc;
    document.getElementById('examModalTitle').textContent = 'Edit Exam Date';
    openModal('addExamModal');
}
</script>
</body>
</html>
