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

$teacher_id = $_SESSION['teacher_id'];
$selected_course = $_GET['course_id'] ?? null;
$attendance_date = $_GET['att_date'] ?? date('Y-m-d');

$assigned_courses = [];
$students = [];
$db_error = "";

// ১. শিক্ষকের কোর্সগুলো নিয়ে আসা (Fallback সহ)
try {
    // এখানে টিচারের নিজের কোর্সগুলো খোঁজা হচ্ছে
    $stmt_c = $pdo->prepare("SELECT id, title FROM courses WHERE teacher_id = ? AND status='active'");
    $stmt_c->execute([$teacher_id]);
    $assigned_courses = $stmt_c->fetchAll(PDO::FETCH_ASSOC);

    // যদি টিচারের নামে কোনো কোর্স না থাকে, তবে সব অ্যাক্টিভ কোর্স দেখাবে (Fallback)
    if (empty($assigned_courses)) {
        $stmt_all = $pdo->query("SELECT id, title FROM courses WHERE status='active'");
        $assigned_courses = $stmt_all->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) { 
    // যদি teacher_id কলাম না থাকে, তবে সরাসরি সব কোর্স দেখাবে
    $stmt_fallback = $pdo->query("SELECT id, title FROM courses WHERE status='active'");
    $assigned_courses = $stmt_fallback->fetchAll(PDO::FETCH_ASSOC);
}

// ২. স্টুডেন্ট লিস্ট নিয়ে আসা (কোর্স সিলেক্ট করা থাকলে)
if ($selected_course) {
    try {
        $stmt_s = $pdo->prepare("SELECT id, name, admission_id, is_trial FROM students WHERE course_id = ? AND status = 'active' ORDER BY admission_id ASC");
        $stmt_s->execute([$selected_course]);
        $students = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $db_error = "Error fetching students: " . $e->getMessage();
    }
}
?>

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    
    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding: 30px; transition: 0.4s; }
    
    /* Header Styling */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 25px; border-left: 6px solid var(--theme-green); }
    
    /* Square Sidebar Toggle Fix */
    #sidebarToggle { width: 42px !important; height: 42px !important; padding: 0; display: inline-flex !important; align-items: center; justify-content: center; flex-shrink: 0; border-radius: 8px; border: 1px solid #e2e8f0; background: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }

    /* Custom UI Elements */
    .custom-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 18px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); overflow: hidden; border-top: 5px solid var(--theme-green); }
    .filter-box { background: #fff; padding: 20px; border-radius: 15px; border: 1px solid #e2e8f0; margin-bottom: 25px; }
    .form-label { font-weight: 700; color: #64748b; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
    .form-select, .form-control { border-radius: 10px; padding: 12px; border: 2px solid #f1f5f9; background: var(--bg-soft); font-size: 14px; font-weight: 600; }

    /* Touch Friendly Attendance Toggle */
    .att-toggle-group { display: flex; background: #f1f5f9; border-radius: 12px; padding: 4px; width: fit-content; margin: 0 auto; border: 1px solid #e2e8f0; }
    .att-btn { border: none; padding: 8px 22px; border-radius: 10px; font-size: 13px; font-weight: 800; cursor: pointer; transition: 0.3s; color: #94a3b8; background: transparent; }
    .att-input-present:checked + .btn-present { background: #10b981; color: #fff; box-shadow: 0 4px 10px rgba(16, 185, 129, 0.3); }
    .att-input-absent:checked + .btn-absent { background: #ef4444; color: #fff; box-shadow: 0 4px 10px rgba(239, 68, 68, 0.3); }
    
    .table thead th { border: none; padding: 18px 20px; color: #64748b; font-weight: 800; text-transform: uppercase; font-size: 11px; background-color: var(--bg-soft); border-bottom: 1px solid #e2e8f0; }
    .trial-badge { font-size: 9px; padding: 2px 8px; border-radius: 4px; background: #fffbeb; color: #d97706; border: 1px solid #fef3c7; font-weight: 800; text-transform: uppercase; margin-left: 5px; }

    @media (max-width: 991px) {
        .main-content { padding: 15px !important; margin-left: 0; }
        .dashboard-header { flex-direction: column; align-items: flex-start !important; gap: 15px; padding: 15px 20px; }
        .dashboard-header .d-flex { width: 100%; align-items: center; }
        .att-toggle-group { width: 100%; }
        .att-btn { flex: 1; text-align: center; }
    }
</style>

<div class="main-content">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center">
            <button class="btn btn-light d-lg-none me-3" id="sidebarToggle">
                <i class="fas fa-bars text-dark"></i>
            </button>
            <div>
                <h4 class="mb-0 fw-bold text-dark"><i class="fas fa-calendar-check me-2" style="color: var(--theme-green);"></i> Attendance System</h4>
            </div>
        </div>
        <div class="d-none d-md-block">
             <span class="badge bg-light text-dark border px-3 py-2 rounded-pill fw-bold">
                <i class="far fa-clock me-2 text-success"></i> <?= date('l, d M Y') ?>
            </span>
        </div>
    </div>

    <div class="filter-box fade-up" style="animation-delay: 0.1s;">
        <form method="GET" class="row g-3 align-items-end">
            <div class="col-md-5">
                <label class="form-label">Select Your Course</label>
                <select name="course_id" class="form-select border-2" onchange="this.form.submit()">
                    <option value="">-- Choose Course --</option>
                    <?php foreach($assigned_courses as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= ($selected_course == $c['id']) ? 'selected' : '' ?>><?= htmlspecialchars($c['title']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">Attendance Date</label>
                <input type="date" name="att_date" class="form-control border-2" value="<?= $attendance_date ?>" onchange="this.form.submit()">
            </div>
        </form>
    </div>

    <?php if(isset($_GET['msg']) && $_GET['msg'] == 'success'): ?>
        <div class="alert alert-success fw-bold border-0 shadow-sm mb-4 bg-white text-success fade-up">
            <i class="fas fa-check-circle me-2"></i> Attendance recorded successfully!
        </div>
    <?php endif; ?>

    <?php if($selected_course): ?>
        <?php if(!empty($students)): ?>
            <div class="custom-card fade-up" style="animation-delay: 0.2s;">
                <form action="save_attendance.php" method="POST">
                    <input type="hidden" name="course_id" value="<?= $selected_course ?>">
                    <input type="hidden" name="att_date" value="<?= $attendance_date ?>">
                    
                    <div class="table-responsive">
                        <table class="table align-middle border-0 mb-0">
                            <thead>
                                <tr>
                                    <th class="ps-4">Admission ID</th>
                                    <th>Student Name</th>
                                    <th class="text-center">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($students as $s): ?>
                                <tr>
                                    <td class="ps-4 fw-bold text-muted">#<?= htmlspecialchars($s['admission_id'] ?? $s['id']) ?></td>
                                    <td>
                                        <div class="fw-bold text-dark"><?= htmlspecialchars($s['name']) ?> 
                                            <?php if($s['is_trial']): ?><span class="trial-badge">Trial User</span><?php endif; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="att-toggle-group shadow-sm">
                                            <input type="radio" name="att[<?= $s['id'] ?>]" value="present" id="p<?= $s['id'] ?>" class="d-none att-input-present" checked>
                                            <label class="att-btn btn-present" for="p<?= $s['id'] ?>">Present</label>

                                            <input type="radio" name="att[<?= $s['id'] ?>]" value="absent" id="a<?= $s['id'] ?>" class="d-none att-input-absent">
                                            <label class="att-btn btn-absent" for="a<?= $s['id'] ?>">Absent</label>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="p-4 border-top text-center bg-light">
                        <button type="submit" class="btn btn-save px-5 py-3 rounded-pill fw-bold text-white shadow border-0" style="background: var(--theme-green);">
                            <i class="fas fa-check-circle me-2"></i> Save All Attendance
                        </button>
                    </div>
                </form>
            </div>
        <?php else: ?>
            <div class="text-center py-5 fade-up bg-white rounded-4 border shadow-sm">
                <i class="fas fa-user-slash fa-4x text-muted opacity-25 mb-3"></i>
                <h5 class="fw-bold text-muted">No students found!</h5>
                <p class="text-muted small">Make sure students are assigned to Course ID: <?= $selected_course ?> and their status is 'active'.</p>
            </div>
        <?php endif; ?>
    <?php else: ?>
        <div class="text-center py-5 fade-up" style="opacity: 0.5;">
            <i class="fas fa-arrow-up fa-4x text-muted mb-3"></i>
            <h5 class="fw-bold text-muted">Please select a course to load students</h5>
        </div>
    <?php endif; ?>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        const sidebar = document.getElementById('sidebarMenu');
        
        if (toggleBtn && sidebar) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                sidebar.classList.toggle('mobile-show');
            });
        }
    });
</script>

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