<?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>Attendance Reports | <?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 filter parameters
        $selected_class = isset($_GET['class']) ? (int)$_GET['class'] : 0;
        $selected_section = isset($_GET['section']) ? (int)$_GET['section'] : 0;
        $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
        $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
        ?>
        <style>
            .report-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 25px;
                border-radius: 10px;
                margin-bottom: 30px;
            }
            .stat-card {
                text-align: center;
                padding: 20px;
                background: #fff;
                border-radius: 8px;
                border-left: 4px solid #007bff;
                height: 100%;
            }
            .stat-number {
                font-size: 32px;
                font-weight: bold;
                color: #007bff;
            }
            .stat-label {
                font-size: 13px;
                color: #6c757d;
                text-transform: uppercase;
                margin-top: 5px;
            }
            .percentage-badge {
                display: inline-block;
                padding: 5px 10px;
                border-radius: 4px;
                font-weight: 600;
            }
            .percentage-high {
                background: #d4edda;
                color: #155724;
            }
            .percentage-medium {
                background: #fff3cd;
                color: #856404;
            }
            .percentage-low {
                background: #f8d7da;
                color: #721c24;
            }

            .fa-eye{
                background-color: transparent;
            }
        </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">Attendance Reports</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"><a href="<?php echo $conn->teacher_url();?>mark-attendance">Mark Attendance</a></li>
                                <li class="breadcrumb-item active">Attendance Reports </li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">

                    <!-- Filter Form -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Filter Reports</h3>
                        </div>
                        <div class="card-body">
                            <form method="GET">
                                <div class="row">
                                    <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-2">
                                        <div class="form-group">
                                            <label>Start Date</label>
                                            <input type="date" name="start_date" class="form-control" value="<?php echo $start_date; ?>">
                                        </div>
                                    </div>

                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>End Date</label>
                                            <input type="date" name="end_date" class="form-control" value="<?php echo $end_date; ?>">
                                        </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> Generate
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

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

                        <?php
                        // Get report data
                        $report_data = $attendance_mgr->getClassReport($selected_class, $selected_section, $start_date, $end_date);
                        $class_summary = $attendance_mgr->getClassSummary($selected_class, $selected_section, $start_date, $end_date);

                        // Calculate overall statistics
                        $total_students = count($report_data);
                        $total_present = 0;
                        $total_absent = 0;
                        $total_days = 0;
                        $avg_percentage = 0;

                        foreach ($report_data as $student) {
                            $total_present += $student->present_days;
                            $total_absent += $student->absent_days;
                            $total_days += $student->total_days;
                            $avg_percentage += $student->attendance_percentage;
                        }

                        if ($total_students > 0) {
                            $avg_percentage = round($avg_percentage / $total_students, 2);
                        }
                        ?>

                        <!-- Overall Statistics -->
                        <div class="row mb-4">
                            <div class="col-lg-3 col-6">
                                <div class="stat-card" style="border-left-color: #007bff;">
                                    <div class="stat-number"><?php echo $total_students; ?></div>
                                    <div class="stat-label">Total Students</div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-6">
                                <div class="stat-card" style="border-left-color: #28a745;">
                                    <div class="stat-number"><?php echo $total_present; ?></div>
                                    <div class="stat-label">Total Present Days</div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-6">
                                <div class="stat-card" style="border-left-color: #dc3545;">
                                    <div class="stat-number"><?php echo $total_absent; ?></div>
                                    <div class="stat-label">Total Absent Days</div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-6">
                                <div class="stat-card" style="border-left-color: #ffc107;">
                                    <div class="stat-number"><?php echo $avg_percentage; ?>%</div>
                                    <div class="stat-label">Avg Attendance</div>
                                </div>
                            </div>
                        </div>

                        <!-- Student-wise Report -->
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    Student Attendance Report
                                    <small class="text-muted">(<?php echo date('M d, Y', strtotime($start_date)); ?> - <?php echo date('M d, Y', strtotime($end_date)); ?>)</small>
                                </h3>
                                <div class="card-tools">
                                    <button type="button" class="btn btn-success btn-sm" onclick="exportToExcel()">
                                        <i class="fas fa-file-excel"></i> Export
                                    </button>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="window.print()">
                                        <i class="fas fa-print"></i> Print
                                    </button>
                                </div>
                            </div>
                            <div class="card-body">
                                <table id="attendance-report-table" class="table table-bordered table-striped">
                                    <thead>
                                    <tr>
                                        <th>S/N</th>
                                        <th>Student Name</th>
                                        <th>Reg No</th>
                                        <th>Total Days</th>
                                        <th>Present</th>
                                        <th>Absent</th>
                                        <th>Late</th>
                                        <th>Excused</th>
                                        <th>Percentage</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                    if (!empty($report_data)) {
                                        $sn = 1;
                                        foreach ($report_data as $student) {
                                            $percentage = $student->attendance_percentage;

                                            if ($percentage >= 90) {
                                                $badge_class = 'percentage-high';
                                                $status = 'Excellent';
                                            } elseif ($percentage >= 75) {
                                                $badge_class = 'percentage-medium';
                                                $status = 'Good';
                                            } else {
                                                $badge_class = 'percentage-low';
                                                $status = 'Poor';
                                            }
                                            ?>
                                            <tr>
                                                <td><?php echo $sn++; ?></td>
                                                <td><?php echo htmlspecialchars($student->name); ?></td>
                                                <td><?php echo htmlspecialchars($student->registerNO); ?></td>
                                                <td><?php echo $student->total_days; ?></td>
                                                <td class="text-success"><?php echo $student->present_days; ?></td>
                                                <td class="text-danger"><?php echo $student->absent_days; ?></td>
                                                <td class="text-warning"><?php echo $student->late_days; ?></td>
                                                <td class="text-info"><?php echo $student->excused_days; ?></td>
                                                <td>
                                        <span class="percentage-badge <?php echo $badge_class; ?>">
                                            <?php echo $percentage; ?>%
                                        </span>
                                                </td>
                                                <td><?php echo $status; ?></td>
                                                <td>
                                                    <a href="<?php echo $conn->teacher_url();?>view-attendance-history?id=<?php echo $student->studentID; ?>" class="btn btn-sm btn-info">
                                                        <i class="fas fa-eye"></i> View
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php
                                        }
                                    } else {
                                        echo '<tr><td colspan="11" class="text-center">No data available</td></tr>';
                                    }
                                    ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                    <?php endif; ?>

                </div>
            </section>

        </div>

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

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

                // Load sections
                $('#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
                <?php if ($selected_class): ?>
                $('#classID').trigger('change');
                <?php endif; ?>

                // Initialize DataTable
                $('#attendance-report-table').DataTable({
                    "responsive": true,
                    "lengthChange": true,
                    "autoWidth": false,
                    "pageLength": 25,
                    "order": [[8, "desc"]]
                });
            });

            function exportToExcel() {
                var table = document.getElementById('attendance-report-table');
                var html = table.outerHTML;
                var url = 'data:application/vnd.ms-excel,' + encodeURIComponent(html);
                var downloadLink = document.createElement("a");
                document.body.appendChild(downloadLink);
                downloadLink.href = url;
                downloadLink.download = 'attendance_report_' + new Date().getTime() + '.xls';
                downloadLink.click();
                document.body.removeChild(downloadLink);
            }
        </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
}
?>