<?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>Student Attendance History | <?php echo $school_name; ?></title>

        <?php
        require_once 'Classes/Attendance.php';
        $attendance = 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();

        ?>
        <style>
            .stat-card {
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .stat-card.present { background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white; }
            .stat-card.absent { background: linear-gradient(135deg, #dc3545 0%, #e83e8c 100%); color: white; }
            .stat-card.late { background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%); color: white; }
            .stat-card.excused { background: linear-gradient(135deg, #17a2b8 0%, #6610f2 100%); color: white; }
            .stat-number { font-size: 2.5rem; font-weight: bold; margin: 10px 0; }
            .stat-label { font-size: 0.9rem; opacity: 0.9; }
            .attendance-badge { padding: 5px 10px; border-radius: 4px; font-size: 0.85rem; font-weight: 500; }
            .badge-present { background: #28a745; color: white; }
            .badge-absent { background: #dc3545; color: white; }
            .badge-late { background: #ffc107; color: #000; }
            .badge-excused { background: #17a2b8; color: white; }
            .student-info { background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
            .student-photo { width: 100px; height: 100px; border-radius: 50%; object-fit: cover; }
            .chart-container { height: 300px; }
            .alert-pattern { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; }
            .month-nav { display: flex; justify-content: space-between; align-items: center; margin: 20px 0; }
            .calendar-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 5px; }
            .calendar-day {
                aspect-ratio: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-size: 0.85rem;
            }
            .calendar-day.present { background: #28a745; color: white; }
            .calendar-day.absent { background: #dc3545; color: white; }
            .calendar-day.late { background: #ffc107; color: #000; }
            .calendar-day.excused { background: #17a2b8; color: white; }
            .calendar-day.weekend { background: #f8f9fa; }
            .calendar-day.future { background: #e9ecef; opacity: 0.5; }
            .calendar-day.day-header {
                font-weight: bold;
                text-align: center;
                background: #f8f9fa;
                border: none;
            }
        </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">Student Attendance History</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">Attendance</li>
                                <li class="breadcrumb-item active">Student History</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>


            <section class="content">
                <div class="container-fluid">
                    <!-- Search Student -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header bg-primary">
                                    <h3 class="card-title">Search Student</h3>
                                </div>
                                <div class="card-body">
                                    <form id="search-student-form">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label>Class</label>
                                                    <select name="class_id" id="class_id" 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){
                                                            echo "<option value='{$class->id}'>{$class->name}</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label>Section</label>
                                                    <select name="section_id" id="section_id" class="form-control select2" required>
                                                        <option value="">Select Section</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label>Student</label>
                                                    <select name="student_id" id="student_id" class="form-control select2" required>
                                                        <option value="">Select Student</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <div class="form-group">
                                                    <label>&nbsp;</label>
                                                    <button type="submit" class="btn btn-primary btn-block">
                                                        <i class="fas fa-search"></i> View History
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Student Info & Statistics -->
                    <div id="student-data" style="display:none;">
                        <!-- Student Info Card -->
                        <div class="row">
                            <div class="col-md-12">
                                <div class="student-info">
                                    <div class="row">
                                        <div class="col-md-2 text-center">
                                            <img id="student-photo" src="" alt="Student Photo" class="student-photo">
                                        </div>
                                        <div class="col-md-10">
                                            <h3 id="student-name"></h3>
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <strong>Reg No:</strong> <span id="student-regno"></span>
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Class:</strong> <span id="student-class"></span>
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Section:</strong> <span id="student-section"></span>
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Overall Attendance:</strong>
                                                    <span id="overall-percentage" style="font-size:1.2rem; font-weight:bold;"></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Statistics Cards -->
                        <div class="row">
                            <div class="col-md-3">
                                <div class="stat-card present">
                                    <div class="stat-label">Present Days</div>
                                    <div class="stat-number" id="present-count">0</div>
                                    <small id="present-percent">0%</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card absent">
                                    <div class="stat-label">Absent Days</div>
                                    <div class="stat-number" id="absent-count">0</div>
                                    <small id="absent-percent">0%</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card late">
                                    <div class="stat-label">Late Days</div>
                                    <div class="stat-number" id="late-count">0</div>
                                    <small id="late-percent">0%</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card excused">
                                    <div class="stat-label">Excused Days</div>
                                    <div class="stat-number" id="excused-count">0</div>
                                    <small id="excused-percent">0%</small>
                                </div>
                            </div>
                        </div>

                        <!-- Pattern Alert -->
                        <div id="pattern-alert" style="display:none;" class="alert-pattern">
                            <i class="fas fa-exclamation-triangle"></i>
                            <strong>Attendance Pattern Alert:</strong>
                            <span id="pattern-message"></span>
                        </div>

                        <!-- Monthly View & Chart -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-info">
                                        <h3 class="card-title">Monthly Calendar View</h3>
                                    </div>
                                    <div class="card-body">
                                        <div class="month-nav">
                                            <button class="btn btn-sm btn-outline-primary" id="prev-month">
                                                <i class="fas fa-chevron-left"></i> Previous
                                            </button>
                                            <h4 id="current-month"></h4>
                                            <button class="btn btn-sm btn-outline-primary" id="next-month">
                                                Next <i class="fas fa-chevron-right"></i>
                                            </button>
                                        </div>
                                        <div class="calendar-grid" id="calendar-grid">
                                            <!-- Calendar will be populated here -->
                                        </div>
                                        <div style="margin-top: 15px;">
                                            <small>
                                                <span class="badge badge-success">P</span> Present &nbsp;
                                                <span class="badge badge-danger">A</span> Absent &nbsp;
                                                <span class="badge badge-warning">L</span> Late &nbsp;
                                                <span class="badge badge-info">E</span> Excused
                                            </small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-success">
                                        <h3 class="card-title">Attendance Trend</h3>
                                    </div>
                                    <div class="card-body">
                                        <div class="chart-container">
                                            <canvas id="attendance-chart"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Detailed History Table -->
                        <div class="row">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-header bg-warning">
                                        <h3 class="card-title">Detailed Attendance History</h3>
                                        <div class="card-tools">
                                            <!-- <button class="btn btn-sm btn-success" id="export-excel">
                                                <i class="fas fa-file-excel"></i> Export to Excel
                                            </button> -->
                                            <!-- <button class="btn btn-sm btn-danger" id="export-pdf">
                                                <i class="fas fa-file-pdf"></i> Export to PDF
                                            </button> -->
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <table class="table table-bordered table-striped" id="history-table">
                                            <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Day</th>
                                                <th>Status</th>
                                                <th>Remarks</th>
                                                <th>Marked By</th>
                                            </tr>
                                            </thead>
                                            <tbody id="history-tbody">
                                            <!-- Data will be loaded here -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </section>

        </div>

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

        <script>
            let currentMonth = new Date();
            let attendanceChart = null;
            let currentStudentId = null;
            let allAttendanceHistory = [];
            $('.select2').select2();

            $(document).ready(function() {
                // Load sections when class is selected
                $('#class_id').on('change', function() {
                    const classID = $(this).val();
                    if(classID) {
                        $.ajax({
                            url: 'fetch_section.php',
                            type: 'POST',
                            data: {classesID: classID},
                            success: function(html) {
                                $('#section_id').html(html);
                                $('#student_id').html('<option value="">Select Student</option>');
                            }
                        });
                    }
                });

                // Load students when section is selected
                $('#section_id').on('change', function() {
                    const classID = $('#class_id').val();
                    const sectionID = $(this).val();
                    if(classID && sectionID) {
                        $.ajax({
                            url: 'fetch_students_by_section.php',
                            type: 'POST',
                            data: {class_id: classID, section_id: sectionID},
                            success: function(response) {
                                $('#student_id').html(response);
                            }
                        });
                    }
                });

                // Search student history
                $('#search-student-form').on('submit', function(e) {
                    e.preventDefault();
                    const studentId = $('#student_id').val();
                    if(studentId) {
                        loadStudentHistory(studentId);
                    }
                });

                // Month navigation
                // Month navigation
                $('#prev-month').on('click', function() {
                    currentMonth.setMonth(currentMonth.getMonth() - 1);
                    updateCalendar(allAttendanceHistory);
                });

                $('#next-month').on('click', function() {
                    currentMonth.setMonth(currentMonth.getMonth() + 1);
                    updateCalendar(allAttendanceHistory);
                });

                // Export functions
                $('#export-excel').on('click', function() {
                    const studentId = $('#student_id').val();
                    window.location.href = 'export-student-attendance.php?student_id=' + studentId + '&format=excel';
                });

                $('#export-pdf').on('click', function() {
                    const studentId = $('#student_id').val();
                    window.location.href = 'export-student-attendance.php?student_id=' + studentId + '&format=pdf';
                });
            });

            function loadStudentHistory(studentId) {
                currentStudentId = studentId; // Store current student ID
                $.ajax({
                    url: 'get-student-attendance-data.php',
                    type: 'POST',
                    data: {student_id: studentId},
                    dataType: 'json',
                    success: function(data) {
                        if(data.success) {
                            allAttendanceHistory = data.history; // Store all history
                            displayStudentInfo(data.student);
                            displayStatistics(data.statistics);
                            displayAttendanceHistory(data.history);
                            updateCalendar(data.history);
                            createChart(data.monthly);
                            checkPatterns(data.history);
                            $('#student-data').slideDown();
                        } else {
                            alert('Error loading student data');
                        }
                    },
                    error: function() {
                        alert('Error connecting to server');
                    }
                });
            }



            function displayStudentInfo(student) {
                $('#student-photo').attr('src', student.photo || '../admin/upload/default.png');
                $('#student-name').text(student.name);
                $('#student-regno').text(student.registerNO);
                $('#student-class').text(student.class_name);
                $('#student-section').text(student.section_name);
            }

            function displayStatistics(stats) {
                const total = parseInt(stats.total_days) || 1;
                const present = parseInt(stats.present_days) || 0;
                const absent = parseInt(stats.absent_days) || 0;
                const late = parseInt(stats.late_days) || 0;
                const excused = parseInt(stats.excused_days) || 0;

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

                $('#present-percent').text(((present/total)*100).toFixed(1) + '%');
                $('#absent-percent').text(((absent/total)*100).toFixed(1) + '%');
                $('#late-percent').text(((late/total)*100).toFixed(1) + '%');
                $('#excused-percent').text(((excused/total)*100).toFixed(1) + '%');

                const attendance = stats.attendance_percentage || 0;
                $('#overall-percentage').text(attendance + '%')
                    .css('color', attendance >= 75 ? '#28a745' : (attendance >= 60 ? '#ffc107' : '#dc3545'));
            }

            function displayAttendanceHistory(history) {
                let html = '';
                history.forEach(record => {
                    const statusClass = `badge-${record.status.toLowerCase()}`;
                    const date = new Date(record.attendance_date);
                    const dayName = date.toLocaleDateString('en-US', {weekday: 'short'});

                    html += `
            <tr>
                <td>${record.attendance_date}</td>
                <td>${dayName}</td>
                <td><span class="attendance-badge ${statusClass}">${record.status}</span></td>
                <td>${record.remarks || '-'}</td>
                <td>${record.marked_by || 'System'}</td>
            </tr>
        `;
                });
                $('#history-tbody').html(html || '<tr><td colspan="5" class="text-center">No attendance records found</td></tr>');
            }


            function updateCalendar(history = []) {
                const month = currentMonth.getMonth();
                const year = currentMonth.getFullYear();
                const firstDay = new Date(year, month, 1).getDay();
                const daysInMonth = new Date(year, month + 1, 0).getDate();
                const today = new Date();

                let html = '';

                // Day headers
                ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].forEach(day => {
                    html += `<div class="calendar-day" style="font-weight:bold; text-align:center; background:#f8f9fa;">${day}</div>`;
                });

                // Empty cells before first day
                for(let i = 0; i < firstDay; i++) {
                    html += '<div class="calendar-day"></div>';
                }

                // Days of month
                for(let day = 1; day <= daysInMonth; day++) {
                    const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                    const currentDate = new Date(year, month, day);
                    const dayOfWeek = currentDate.getDay();
                    const isFuture = currentDate > today;
                    const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;

                    let className = 'calendar-day';
                    let content = day;
                    let tooltip = '';

                    if(isFuture) {
                        className += ' future';
                    } else if(isWeekend) {
                        className += ' weekend';
                    } else {
                        // Find attendance record for this date
                        const record = history.find(r => r.attendance_date === dateStr);

                        if(record) {
                            // Use the exact status from database (case-sensitive match)
                            const status = record.status.toLowerCase();
                            className += ' ' + status;
                            tooltip = `title="${record.status}${record.remarks ? ': ' + record.remarks : ''}"`;
                            // Show first letter of status for better visual indication
                            content = record.status.charAt(0).toUpperCase();
                        }
                    }

                    html += `<div class="${className}" ${tooltip}>${content}</div>`;
                }

                $('#calendar-grid').html(html);
                $('#current-month').text(currentMonth.toLocaleDateString('en-US', {month: 'long', year: 'numeric'}));
            }

            function createChart(monthlyData) {
                const ctx = document.getElementById('attendance-chart').getContext('2d');

                if(attendanceChart) {
                    attendanceChart.destroy();
                }

                const labels = monthlyData.map(m => m.month);
                const presentData = monthlyData.map(m => m.present);
                const absentData = monthlyData.map(m => m.absent);
                const lateData = monthlyData.map(m => m.late);

                attendanceChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: 'Present',
                                data: presentData,
                                borderColor: '#28a745',
                                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                                tension: 0.4
                            },
                            {
                                label: 'Absent',
                                data: absentData,
                                borderColor: '#dc3545',
                                backgroundColor: 'rgba(220, 53, 69, 0.1)',
                                tension: 0.4
                            },
                            {
                                label: 'Late',
                                data: lateData,
                                borderColor: '#ffc107',
                                backgroundColor: 'rgba(255, 193, 7, 0.1)',
                                tension: 0.4
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }

            function checkPatterns(history) {
                let consecutiveAbsent = 0;
                let maxConsecutive = 0;

                history.forEach(record => {
                    if(record.status === 'Absent') {
                        consecutiveAbsent++;
                        maxConsecutive = Math.max(maxConsecutive, consecutiveAbsent);
                    } else {
                        consecutiveAbsent = 0;
                    }
                });

                if(maxConsecutive >= 3) {
                    $('#pattern-message').text(`Student has ${maxConsecutive} consecutive absences. Consider parent notification.`);
                    $('#pattern-alert').slideDown();
                } else {
                    $('#pattern-alert').slideUp();
                }
            }
        </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
}
?>