<?php
session_start();
if(isset($_SESSION['teacher'])){
    $username = $_SESSION['teacher'];
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include '../admin/includes/styles.php'; ?>
        <title>Mark Attendance | <?php echo $school_name; ?></title>

        <?php
        require_once 'Classes/Attendance.php';
        $attendance_mgr = new Attendance();

          // Get teacher info
        $sql = "SELECT * FROM teachers WHERE username = :username";
        $conn->query($sql);
        $conn->bind(':username', $username);
        $teacher = $conn->fetchSingle();

        if (!$teacher) {
            header("Location: $teacher_login_link");
            exit();
        }

        $teacher_id = $teacher->id;
        $teacher_name = $teacher->name;

        //fetch teachers class id
        $sql = "SELECT id FROM classes WHERE teacher_name = :teacher_name";
        $conn->query($sql);
        $conn->bind(':teacher_name', $teacher_name);
        $teacher_class_id = $conn->fetchColumn();

        // Get current date or selected date
        $selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
        $selected_class = isset($_GET['class']) ? (int)$_GET['class'] : 0;
        $selected_section = isset($_GET['section']) ? (int)$_GET['section'] : 0;
        ?>
        <style>
            .attendance-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 25px;
                border-radius: 10px;
                margin-bottom: 30px;
            }
            .student-row {
                padding: 15px;
                background: #fff;
                border-left: 4px solid #007bff;
                margin-bottom: 10px;
                border-radius: 4px;
                transition: all 0.3s;
            }
            .student-row:hover {
                background: #f8f9fa;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .student-row.marked {
                border-left-color: #28a745;
            }
            .attendance-btn-group {
                display: flex;
                gap: 5px;
            }
            .attendance-btn {
                padding: 8px 15px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-weight: 600;
                transition: all 0.3s;
                font-size: 12px;
            }
            .attendance-btn.active {
                transform: scale(1.1);
                box-shadow: 0 2px 4px rgba(0,0,0,0.2);
            }
            .btn-present {
                background: #28a745;
                color: white;
            }
            .btn-present:hover {
                background: #218838;
            }
            .btn-absent {
                background: #dc3545;
                color: white;
            }
            .btn-absent:hover {
                background: #c82333;
            }
            .btn-late {
                background: #ffc107;
                color: #333;
            }
            .btn-late:hover {
                background: #e0a800;
            }
            .btn-excused {
                background: #17a2b8;
                color: white;
            }
            .btn-excused:hover {
                background: #138496;
            }
            .quick-action-btn {
                margin: 5px;
            }
            .summary-card {
                text-align: center;
                padding: 15px;
                background: #fff;
                border-radius: 8px;
                border-left: 4px solid #007bff;
            }
            .summary-number {
                font-size: 24px;
                font-weight: bold;
                color: #007bff;
            }
            .summary-label {
                font-size: 12px;
                color: #6c757d;
                text-transform: uppercase;
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0">Mark Attendance</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>">Home</a></li>
                                <li class="breadcrumb-item active">Mark Attendance</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            <section class="content">
                <div class="container-fluid">

                    <!-- Selection Form -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Select Class & Date</h3>
                        </div>
                        <div class="card-body">
                            <form method="GET" id="selection-form">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Date <span class="text-danger">*</span></label>
                                            <input type="date" name="date" class="form-control" value="<?php echo $selected_date; ?>" required max="<?php echo date('Y-m-d'); ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Class <span class="text-danger">*</span></label>
                                            <select name="class" id="classID" class="form-control select2" required>
                                                <option value="">Select class</option>
                                                <?php
                                                $sql = "SELECT * FROM classes WHERE teacher_name =:teacher_name ORDER BY name";
                                                $conn->query($sql);
                                                $conn->bind(':teacher_name', $teacher_name);
                                                $classes = $conn->fetchMultiple();
                                                foreach ($classes as $class) {
                                                    $selected = ($selected_class == $class->id) ? 'selected' : '';
                                                    echo "<option value='{$class->id}' {$selected}>{$class->name}</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Section <span class="text-danger">*</span></label>
                                            <select name="section" id="section" class="form-control select2" required>
                                                <option value="">Select section</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>&nbsp;</label>
                                            <button type="submit" class="btn btn-primary btn-block">
                                                <i class="fas fa-search"></i> Load Students
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <?php if ($selected_class && $selected_section): ?>

                        <!-- Quick Actions -->
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">Quick Actions</h3>
                            </div>
                            <div class="card-body">
                                <button type="button" class="btn btn-success quick-action-btn" id="mark-all-present">
                                    <i class="fas fa-check-circle"></i> Mark All Present
                                </button>
                                <button type="button" class="btn btn-danger quick-action-btn" id="mark-all-absent">
                                    <i class="fas fa-times-circle"></i> Mark All Absent
                                </button>
                                <button type="button" class="btn btn-secondary quick-action-btn" id="clear-all">
                                    <i class="fas fa-undo"></i> Clear All
                                </button>
                            </div>
                        </div>

                        <!-- Students List -->
                        <?php
                        $students = $attendance_mgr->getClassAttendance($selected_class, $selected_section, $selected_date);


                        if (!empty($students)):
                            ?>
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        Students - <?php echo date('F d, Y', strtotime($selected_date)); ?>
                                        <span class="badge badge-info ml-2"><?php echo count($students); ?> Students</span>
                                    </h3>
                                    <div class="card-tools">
                                        <button type="button" class="btn btn-primary" id="save-attendance">
                                            <i class="fas fa-save"></i> Save Attendance
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">

                                    <!-- Summary -->
                                    <div class="row mb-4" id="summary-section">
                                        <div class="col-md-3">
                                            <div class="summary-card" style="border-left-color: #28a745;">
                                                <div class="summary-number" id="present-count">0</div>
                                                <div class="summary-label">Present</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="summary-card" style="border-left-color: #dc3545;">
                                                <div class="summary-number" id="absent-count">0</div>
                                                <div class="summary-label">Absent</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="summary-card" style="border-left-color: #ffc107;">
                                                <div class="summary-number" id="late-count">0</div>
                                                <div class="summary-label">Late</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="summary-card" style="border-left-color: #17a2b8;">
                                                <div class="summary-number" id="excused-count">0</div>
                                                <div class="summary-label">Excused</div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Students -->
                                    <form id="attendance-form">
                                        <input type="hidden" name="date" value="<?php echo $selected_date; ?>">
                                        <input type="hidden" name="class_id" value="<?php echo $selected_class; ?>">
                                        <input type="hidden" name="section_id" value="<?php echo $selected_section; ?>">

                                        <?php foreach ($students as $index => $student): ?>
                                            <div class="student-row" data-student-id="<?php echo $student->studentID; ?>">
                                                <div class="row align-items-center">
                                                    <div class="col-md-4">
                                                        <strong><?php echo ($index + 1); ?>. <?php echo htmlspecialchars($student->student_name); ?></strong><br>
                                                        <small class="text-muted">Reg: <?php echo htmlspecialchars($student->registerNO); ?></small>
                                                    </div>
                                                    <div class="col-md-5">
                                                        <div class="attendance-btn-group">
                                                            <button type="button" class="attendance-btn btn-present"
                                                                    data-status="present" data-student="<?php echo $student->studentID; ?>">
                                                                <i class="fas fa-check"></i> Present
                                                            </button>
                                                            <button type="button" class="attendance-btn btn-absent"
                                                                    data-status="absent" data-student="<?php echo $student->studentID; ?>">
                                                                <i class="fas fa-times"></i> Absent
                                                            </button>
                                                            <button type="button" class="attendance-btn btn-late"
                                                                    data-status="late" data-student="<?php echo $student->studentID; ?>">
                                                                <i class="fas fa-clock"></i> Late
                                                            </button>
                                                            <button type="button" class="attendance-btn btn-excused"
                                                                    data-status="excused" data-student="<?php echo $student->studentID; ?>">
                                                                <i class="fas fa-user-check"></i> Excused
                                                            </button>
                                                        </div>
                                                        <input type="hidden" name="attendance[<?php echo $student->studentID; ?>][student_id]" value="<?php echo $student->studentID; ?>">
                                                        <input type="hidden" name="attendance[<?php echo $student->studentID; ?>][status]" value="" class="status-input">
                                                    </div>
                                                    <div class="col-md-3">
                                                        <input type="text" name="attendance[<?php echo $student->studentID; ?>][remarks]"
                                                               class="form-control form-control-sm" placeholder="Remarks (optional)"
                                                               value="">
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </form>

                                </div>
                                <div class="card-footer">
                                    <button type="button" class="btn btn-primary btn-lg" id="save-attendance-bottom">
                                        <i class="fas fa-save"></i> Save Attendance
                                    </button>
                                    <a href="<?php echo $conn->teacher_url();?>attendance-report" class="btn btn-info">
                                        <i class="fas fa-chart-bar"></i> View Reports
                                    </a>
                                </div>
                            </div>
                            <div id="save-msg"></div>

                        <?php else: ?>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle"></i> No students found in the selected class and section.
                            </div>
                        <?php endif; ?>

                    <?php endif; ?>

                </div>
            </section>

        </div>

        <?php include "../admin/includes/footer.php"; ?>

        <script>
            $(function() {
                $('.select2').select2();

                // Load sections when class changes
                $('#classID').on('change', function() {
                    var classID = $(this).val();
                    if (classID) {
                        $.ajax({
                            type: 'POST',
                            url: 'fetch_section.php',
                            data: 'classesID=' + classID,
                            success: function(html) {
                                $('#section').html(html);
                                <?php if ($selected_section): ?>
                                $('#section').val('<?php echo $selected_section; ?>');
                                <?php endif; ?>
                            }
                        });
                    }
                });

                // Trigger on page load if class is selected
                <?php if ($selected_class): ?>
                $('#classID').trigger('change');
                <?php endif; ?>

                // Attendance button click
                $(document).on('click', '.attendance-btn', function() {
                    var $row = $(this).closest('.student-row');
                    var studentId = $(this).data('student');
                    var status = $(this).data('status');

                    // Remove active from all buttons in this row
                    $row.find('.attendance-btn').removeClass('active');

                    // Add active to clicked button
                    $(this).addClass('active');

                    // Update hidden input
                    $row.find('.status-input').val(status);

                    // Mark row as marked
                    $row.addClass('marked');

                    // Update summary
                    updateSummary();
                });

                // Quick actions
                $('#mark-all-present').on('click', function() {
                    $('.student-row').each(function() {
                        $(this).find('[data-status="present"]').click();
                    });
                });

                $('#mark-all-absent').on('click', function() {
                    $('.student-row').each(function() {
                        $(this).find('[data-status="absent"]').click();
                    });
                });

                $('#clear-all').on('click', function() {
                    if (confirm('Clear all attendance marks?')) {
                        $('.student-row').removeClass('marked');
                        $('.attendance-btn').removeClass('active');
                        $('.status-input').val('');
                        updateSummary();
                    }
                });

                // Update summary counts
                function updateSummary() {
                    var present = $('.status-input[value="present"]').length;
                    var absent = $('.status-input[value="absent"]').length;
                    var late = $('.status-input[value="late"]').length;
                    var excused = $('.status-input[value="excused"]').length;

                    $('#present-count').text(present);
                    $('#absent-count').text(absent);
                    $('#late-count').text(late);
                    $('#excused-count').text(excused);
                }

                // Initial summary update
                updateSummary();

                // Save attendance
                $('#save-attendance, #save-attendance-bottom').on('click', function() {
                    var formData = $('#attendance-form').serialize();

                    // Check if any status is marked
                    var hasMarks = false;
                    $('.status-input').each(function() {
                        if ($(this).val()) {
                            hasMarks = true;
                            return false;
                        }
                    });

                    if (!hasMarks) {
                        alert('Please mark attendance for at least one student');
                        return;
                    }

                    $.ajax({
                        url: 'process-mark-attendance.php',
                        method: 'POST',
                        data: formData,
                        beforeSend: function() {
                            $('#save-attendance, #save-attendance-bottom').attr('disabled', 'disabled');
                            $('#save-attendance').html('<i class="fas fa-spinner fa-spin"></i> Saving...');
                            $('#save-attendance-bottom').html('<i class="fas fa-spinner fa-spin"></i> Saving...');
                        },
                        success: function(data) {
                            $('#save-attendance, #save-attendance-bottom').attr('disabled', false);
                            $('#save-attendance').html('<i class="fas fa-save"></i> Save Attendance');
                            $('#save-attendance-bottom').html('<i class="fas fa-save"></i> Save Attendance');
                            $('#save-msg').html(data);

                            // Scroll to message
                            $('html, body').animate({
                                scrollTop: $('#save-msg').offset().top - 100
                            }, 500);
                        },
                        error: function() {
                            $('#save-attendance, #save-attendance-bottom').attr('disabled', false);
                            $('#save-attendance').html('<i class="fas fa-save"></i> Save Attendance');
                            $('#save-attendance-bottom').html('<i class="fas fa-save"></i> Save Attendance');
                            alert('An error occurred. Please try again.');
                        }
                    });
                });
            });
        </script>

    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include '../admin/includes/styles.php'; ?>
    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6>You need to login to continue</h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $teacher_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>