<?php

include('includes/session1.php');

error_reporting(0);

include('includes/dbconnection.php');
include('includes/session_term_helper.php');

// Resolve current session and term (with fallback support)
$sessionTerm = resolveCurrentSessionTerm($con);
$currentSessionId = $sessionTerm['session_id'] ?: null;
$currentSessionName = $sessionTerm['session_name'];
$currentTermId = $sessionTerm['term_id'] ?: null;
$currentTermName = $sessionTerm['term_name'];



if (!isset($_SESSION['sid'])) {

    header('location:logoutteacher.php');

    exit();

}



$tabSessionID = $_SESSION['tab_id'] ?? 1; // Default to 1 if not set



$class = $_GET['class'];

$section = $_GET['section'];

$month = $_GET['month'] ?? date('m');

$year = $_GET['year'] ?? date('Y');



// Fetch attendance data for the selected class, month, and year

$query = "

    SELECT students.studentName, 

           SUM(CASE WHEN attendance.status = 'Present' THEN 1 ELSE 0 END) as present, 

           SUM(CASE WHEN attendance.status = 'Absent' THEN 1 ELSE 0 END) as absent 

    FROM attendance 

    JOIN students ON attendance.student_id = students.id

    WHERE attendance.class = '$class' 

    AND attendance.section = '$section' 

    AND MONTH(attendance.date) = $month

    AND YEAR(attendance.date) = $year

    GROUP BY students.id";



$result = mysqli_query($con, $query);

$attendance_data = mysqli_fetch_all($result, MYSQLI_ASSOC);



$students = [];

$present = [];

$absent = [];



foreach ($attendance_data as $row) {

    $students[] = $row['studentName'];

    $present[] = $row['present'];

    $absent[] = $row['absent'];

}

?>



<!DOCTYPE html>

<html>

<?php @include("includes/head.php"); ?>



<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

        <?php @include("includes/headert.php"); ?>

        <?php @include("includes/sidebart.php"); ?>



        <div class="content-wrapper">

            <section class="content-header premium-header">

                <div class="container-fluid">

                    <div class="header-glass-card">

                        <div class="row align-items-center">

                            <div class="col-md-8">

                                <div class="title-section">

                                    <div class="icon-box bg-primary-gradient shadow-sm">

                                        <i class="fas fa-users"></i>

                                    </div>

                                    <div>

                                        <h1 class="premium-title text-primary">

                                            Attendance Management

                                            <span class="premium-subtitle text-secondary">Attendance Report</span>

                                        </h1>
                                        <div class="mt-1">
                                            <?php if ($currentSessionName): ?>
                                                <span class="badge badge-primary mr-1">
                                                    <i class="fas fa-calendar-alt"></i>
                                                    <?= htmlspecialchars($currentSessionName) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($currentTermName): ?>
                                                <span class="badge badge-success">
                                                    <i class="fas fa-bookmark"></i>
                                                    <?= htmlspecialchars($currentTermName) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="badge badge-warning">
                                                    <i class="fas fa-exclamation-triangle"></i> No active term
                                                </span>
                                            <?php endif; ?>
                                        </div>

                                    </div>

                                </div>

                            </div>

                            <div class="col-md-4">

                                <nav aria-label="breadcrumb">

                                    <ol class="breadcrumb premium-breadcrumb">

                                        <li class="breadcrumb-item"><a href="teacher_dashboard.php"
                                                class="text-primary">Home</a></li>

                                        <li class="breadcrumb-item active" aria-current="page">Attendance Report</li>

                                    </ol>

                                </nav>

                            </div>

                        </div>

                    </div>

                </div>

            </section>



            <section class="content">

                <div class="card card-primary">

                    <div class="card-header">

                        <h5 class="card-title font-weight-bold"><i class="fas fa-clipboard-list"></i> Attendance Report
                            for <?php echo $class; ?> - <?php echo $section; ?> || Month/Year:
                            <?php echo $month . '/' . $year; ?></h5>

                    </div>

                    <div class="card-body">





                        <!-- Date Picker for Dynamic Report Generation -->

                        <div class="form-group col-md-4">

                            <label for="month" class="form-group">Select Month:</label>

                            <input type="month" id="month" name="month" value="<?php echo $year . '-' . $month; ?>"
                                onchange="updateReport()" class="form-control" required>

                        </div>





                        <hr>

                        <h5 class="text-primary font-weight-bold text-center">Attendance Report for
                            <?php echo $month . '/' . $year; ?></h5>

                        <hr>

                        <!-- Canvas for the Chart -->

                        <canvas id="attendanceChart">



                        </canvas> <!-- Explicit height and width -->



                        <script>
                            function updateReport() {
                                const selectedMonth = document.getElementById('month').value.split('-')[1];
                                const selectedYear = document.getElementById('month').value.split('-')[0];
                                window.location.href = `attendance_report.php?class=<?php echo $class; ?>&section=<?php echo $section; ?>&month=${selectedMonth}&year=${selectedYear}&tab_id=<?php echo $tabSessionID; ?>`;
                            }
                        </script>

                    </div>

                </div>

            </section>

        </div>

        <?php @include("includes/footer.php"); ?>

        <?php @include("includes/foot.php"); ?>

        <script>
            (function () {
                const students = <?php echo json_encode($students); ?>;
                const present = <?php echo json_encode($present); ?>;
                const absent = <?php echo json_encode($absent); ?>;

                const ctx = document.getElementById('attendanceChart').getContext('2d');
                const attendanceChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: students,
                        datasets: [
                            {
                                label: 'Present',
                                data: present,
                                backgroundColor: 'green',
                                borderColor: 'green',
                                borderWidth: 1
                            },
                            {
                                label: 'Absent',
                                data: absent,
                                backgroundColor: 'red',
                                borderColor: 'red',
                                borderWidth: 1
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            tooltip: {
                                callbacks: {
                                    label: function (tooltipItem) {
                                        const status = tooltipItem.datasetIndex === 0 ? 'Present' : 'Absent';
                                        return `${tooltipItem.label}: ${status} - ${tooltipItem.raw} days`;
                                    }
                                }
                            },
                            legend: {
                                display: true,
                                onClick: function (e, legendItem) {
                                    const meta = attendanceChart.getDatasetMeta(legendItem.datasetIndex);
                                    meta.hidden = !meta.hidden;
                                    attendanceChart.update();
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function (value) { return value + ' days'; }
                                }
                            }
                        }
                    }
                });
            })();
        </script>

</body>



</html>