<?php 
// Advanced Debugging & Config
ini_set('display_errors', 1); error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');
require_once '../db_connect.php'; 

// Admin Security Check
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit; }

// ==========================================
// 🛠️ DATABASE SYNC
// ==========================================
try {
    $columns = $pdo->query("SHOW COLUMNS FROM attendance")->fetchAll(PDO::FETCH_COLUMN);
    if(!in_array('remarks', $columns)) { 
        $pdo->exec("ALTER TABLE attendance ADD COLUMN remarks VARCHAR(255) DEFAULT NULL"); 
    }
} catch(PDOException $e) {}

$success_msg = ''; $error_msg = '';
$selected_class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : (isset($_POST['class_id_hidden']) ? (int)$_POST['class_id_hidden'] : 0);

// Handle Redirect Messages (Prevents Resubmission on Reload)
if(isset($_GET['msg'])) {
    if($_GET['msg'] == 'saved') $success_msg = "Attendance saved successfully!";
    elseif($_GET['msg'] == 'error') $error_msg = "Something went wrong! Please try again.";
}

// ==========================================
// 1. SAVE ATTENDANCE DATA (With Redirect Fix)
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_attendance'])) {
    $course_id = (int)$_POST['course_id'];
    $teacher_id = (int)$_POST['teacher_id'];
    $attendance_date = $_POST['attendance_date'];
    $attendance_data = $_POST['attendance'] ?? [];
    $class_id_hidden = $_POST['class_id_hidden'];

    try {
        $pdo->beginTransaction();
        $check_stmt = $pdo->prepare("SELECT id FROM attendance WHERE student_id = ? AND course_id = ? AND attendance_date = ?");
        $update_stmt = $pdo->prepare("UPDATE attendance SET status = ?, remarks = ?, teacher_id = ? WHERE student_id = ? AND course_id = ? AND attendance_date = ?");
        $insert_stmt = $pdo->prepare("INSERT INTO attendance (student_id, course_id, teacher_id, status, attendance_date, remarks) VALUES (?, ?, ?, ?, ?, ?)");

        foreach ($attendance_data as $student_id => $data) {
            $status = strtolower($data['status']); 
            $remarks = trim($data['remarks']);
            
            $check_stmt->execute([$student_id, $course_id, $attendance_date]);
            if ($check_stmt->fetch()) {
                $update_stmt->execute([$status, $remarks, $teacher_id, $student_id, $course_id, $attendance_date]);
            } else {
                $insert_stmt->execute([$student_id, $course_id, $teacher_id, $status, $attendance_date, $remarks]);
            }
        }
        $pdo->commit();
        
        // Redirect to avoid form resubmission on reload
        echo "<script>window.location.href='?class_id=".$class_id_hidden."&msg=saved';</script>";
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        echo "<script>window.location.href='?class_id=".$class_id_hidden."&msg=error';</script>";
        exit;
    }
}

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

// Fetch Classes for Dropdown
$classes_query = $pdo->query("
    SELECT lc.id, lc.topic, lc.class_date, lc.course_id, lc.teacher_id, c.title as course_name 
    FROM live_classes lc 
    JOIN courses c ON lc.course_id = c.id 
    ORDER BY lc.class_date DESC LIMIT 50
")->fetchAll(PDO::FETCH_ASSOC);

// Fetch Students & Existing Attendance
$enrolled_students = []; $existing_attendance = []; $class_details = [];
if ($selected_class_id) {
    $class_stmt = $pdo->prepare("SELECT course_id, teacher_id, class_date FROM live_classes WHERE id = ?");
    $class_stmt->execute([$selected_class_id]);
    $class_details = $class_stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($class_details) {
        $student_stmt = $pdo->prepare("SELECT s.id, s.name, s.phone FROM students s JOIN enrollments e ON s.id = e.student_id WHERE e.course_id = ? AND e.status = 'active' ORDER BY s.name ASC");
        $student_stmt->execute([$class_details['course_id']]);
        $enrolled_students = $student_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $att_stmt = $pdo->prepare("SELECT student_id, status, remarks FROM attendance WHERE course_id = ? AND attendance_date = ?");
        $att_stmt->execute([$class_details['course_id'], $class_details['class_date']]);
        $existing_attendance = $att_stmt->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);
    }
}
?>

<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: 80px; font-family: 'Outfit', sans-serif; }
    
    /* Header */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 30px; 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; }
    
    /* Cards */
    .filter-card { background: #fff; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.02); border: 1px solid #e2e8f0; margin-bottom: 25px; padding: 25px; }
    .desktop-table-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.03); overflow: hidden; border-top: 5px solid var(--theme-green); }
    
    /* Table Styling */
    .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 { transition: 0.3s; border-bottom: 1px solid #f1f5f9; }
    .table tbody tr:hover { background-color: #f8fafc; }
    .table td { padding: 15px 20px; vertical-align: middle; }
    
    .avatar-circle { width: 45px; height: 45px; border-radius: 12px; background: rgba(6, 78, 59, 0.1); color: var(--theme-green); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 18px; flex-shrink: 0; }

    /* Custom Radio Buttons */
    .att-radio-group { display: inline-flex; gap: 8px; }
    .btn-att { padding: 8px 20px; font-size: 13px; font-weight: 700; border-radius: 10px; transition: 0.3s; box-shadow: none !important; border-width: 2px; }
    
    /* Inputs */
    .form-select, .form-control { border-radius: 12px; border: 2px solid #f1f5f9; padding: 12px 15px; font-size: 14px; background: #f8fafc; transition: 0.3s; }
    .form-select:focus, .form-control:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); }
    
    .btn-theme { background: var(--theme-green); color: #fff; border-radius: 12px; padding: 14px 30px; font-weight: 700; border: none; transition: 0.3s; box-shadow: 0 4px 15px rgba(6, 78, 59, 0.2); }
    .btn-theme:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 20px rgba(6, 78, 59, 0.3); }

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

    /* 📱 CSS TRICK: Transform Table into Mobile Cards safely */
    @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; }
        #sidebarToggle { display: inline-flex !important; }
        
        /* Transform Table to Cards */
        .desktop-table-card { background: transparent; border: none; box-shadow: none; border-top: none; }
        .table thead { display: none; }
        .table tbody, .table tr, .table td { display: block; width: 100%; }
        
        .table tbody tr { 
            background: #fff; 
            border-radius: 16px; 
            margin-bottom: 15px; 
            padding: 20px; 
            box-shadow: 0 4px 15px rgba(0,0,0,0.03); 
            border: 1px solid #e2e8f0; 
        }
        
        .table td { border: none; padding: 0; margin-bottom: 15px; }
        .table td:last-child { margin-bottom: 0; }
        
        .td-student-info { display: flex; align-items: center; gap: 15px; border-bottom: 1px solid #f1f5f9; padding-bottom: 15px; }
        .td-status .att-radio-group { width: 100%; display: flex; }
        .td-status .att-radio-group .btn { flex-grow: 1; }
        
        .bottom-submit-bar { padding: 15px !important; background: transparent !important; border: none !important; }
        .bottom-submit-bar .btn-theme { width: 100%; }
    }
</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">
            <button id="sidebarToggle" class="shadow-sm me-3"><i class="fas fa-bars fs-5"></i></button>
            <div>
                <h4 class="mb-0 fw-bold text-dark header-title"><i class="fas fa-clipboard-user me-2" style="color: var(--theme-gold);"></i> Class Attendance</h4>
                <p class="text-muted fw-semibold mb-0 d-none d-md-block" style="font-size: 13px;">Record daily attendance for live classes</p>
            </div>
        </div>
    </div>

    <?php if($success_msg): ?> 
        <div class="alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm 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"><?= $success_msg ?></span></div>
        </div>
    <?php endif; ?>
    <?php if($error_msg): ?> 
        <div class="alert alert-danger d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #ef4444 !important;">
            <i class="fas fa-exclamation-triangle me-3 fa-2x text-danger"></i> 
            <div><strong class="d-block text-danger">Error!</strong><span class="text-muted small"><?= $error_msg ?></span></div>
        </div>
    <?php endif; ?>

    <div class="filter-card fade-up" style="animation-delay: 0.1s;">
        <form method="GET" class="row g-3 align-items-end">
            <div class="col-md-9">
                <label class="form-label fw-bold text-muted small text-uppercase"><i class="fas fa-search me-1"></i> Select Class Session</label>
                <select name="class_id" class="form-select fw-bold text-dark border-2 shadow-none" onchange="this.form.submit()" required>
                    <option value="">-- Choose Class Schedule --</option>
                    <?php foreach($classes_query as $cls): ?>
                        <option value="<?= $cls['id'] ?>" <?= $selected_class_id == $cls['id'] ? 'selected' : '' ?>>
                            <?= date('d M, Y', strtotime($cls['class_date'])) ?> | <?= htmlspecialchars($cls['course_name']) ?> - <?= htmlspecialchars($cls['topic']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn w-100 py-2 fw-bold text-white shadow-sm" style="background: var(--theme-dark); border-radius: 12px; height: 48px;"><i class="fas fa-sync-alt me-1"></i> Load Roster</button>
            </div>
        </form>
    </div>

    <?php if ($selected_class_id && !empty($class_details)): ?>
        <?php if(empty($enrolled_students)): ?>
            <div class="text-center py-5 bg-white rounded-4 border shadow-sm fade-up" style="animation-delay: 0.2s;">
                <i class="fas fa-users-slash fa-3x text-muted opacity-25 mb-3 d-block"></i>
                <h6 class="fw-bold text-muted">No active students enrolled in this course!</h6>
            </div>
        <?php else: ?>
            <div class="desktop-table-card fade-up" style="animation-delay: 0.2s;">
                <form action="manage_attendance.php" method="POST">
                    <input type="hidden" name="class_id_hidden" value="<?= $selected_class_id ?>">
                    <input type="hidden" name="course_id" value="<?= $class_details['course_id'] ?>">
                    <input type="hidden" name="teacher_id" value="<?= $class_details['teacher_id'] ?>">
                    <input type="hidden" name="attendance_date" value="<?= $class_details['class_date'] ?>">

                    <div class="table-responsive" style="overflow-x: visible;">
                        <table class="table align-middle mb-0 border-0">
                            <thead>
                                <tr>
                                    <th class="ps-4">Student Profile</th>
                                    <th>Attendance Status</th>
                                    <th class="pe-4">Teacher's Note / Remarks</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($enrolled_students as $student): 
                                    $sid = $student['id'];
                                    $current_status = isset($existing_attendance[$sid]['status']) ? strtolower($existing_attendance[$sid]['status']) : 'present';
                                ?>
                                <tr>
                                    <td class="ps-4 td-student-info">
                                        <div class="d-flex align-items-center gap-3">
                                            <div class="avatar-circle shadow-sm"><?= strtoupper(substr($student['name'], 0, 1)) ?></div>
                                            <div>
                                                <div class="fw-bold text-dark" style="font-size: 15px;"><?= htmlspecialchars($student['name']) ?></div>
                                                <small class="text-muted fw-bold"><i class="fas fa-phone-alt me-1 text-primary" style="font-size:10px;"></i> <?= htmlspecialchars($student['phone']) ?></small>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="td-status">
                                        <div class="att-radio-group">
                                            <input type="radio" class="btn-check" name="attendance[<?= $sid ?>][status]" id="p_<?= $sid ?>" value="present" <?= $current_status == 'present' ? 'checked' : '' ?>>
                                            <label class="btn btn-outline-success btn-att" for="p_<?= $sid ?>"><i class="fas fa-check-circle me-1"></i> Present</label>
                                            
                                            <input type="radio" class="btn-check" name="attendance[<?= $sid ?>][status]" id="a_<?= $sid ?>" value="absent" <?= $current_status == 'absent' ? 'checked' : '' ?>>
                                            <label class="btn btn-outline-danger btn-att" for="a_<?= $sid ?>"><i class="fas fa-times-circle me-1"></i> Absent</label>
                                        </div>
                                    </td>
                                    <td class="pe-4 td-remarks">
                                        <input type="text" name="attendance[<?= $sid ?>][remarks]" class="form-control bg-light border-0 fw-medium" placeholder="Optional notes..." value="<?= htmlspecialchars($existing_attendance[$sid]['remarks'] ?? '') ?>">
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="p-4 bg-light text-end border-top bottom-submit-bar">
                        <button type="submit" name="save_attendance" class="btn-theme"><i class="fas fa-save me-2"></i> SUBMIT ATTENDANCE</button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Sidebar Toggle for Mobile
        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>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include 'includes/footer.php'; ?>