<?php

include('includes/session.php');

error_reporting(0);

include('includes/dbconnection.php');

require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];


$student_id = $_SESSION['student_id'];



$month = isset($_POST['month']) ? $_POST['month'] : date('m');

$year = isset($_POST['year']) ? $_POST['year'] : date('Y');



$month_names = [

    '01' => 'January',

    '02' => 'February',

    '03' => 'March',

    '04' => 'April',

    '05' => 'May',

    '06' => 'June',

    '07' => 'July',

    '08' => 'August',

    '09' => 'September',

    '10' => 'October',

    '11' => 'November',

    '12' => 'December'

];



// Fetch attendance

$query = "SELECT DATE(date) as day_date, status FROM attendance WHERE student_id = $student_id AND MONTH(date) = $month AND YEAR(date) = $year";

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



$attendance_days = [];

while ($row = mysqli_fetch_assoc($result)) {

    $attendance_days[$row['day_date']] = $row['status'];

}



$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);

?>



<!DOCTYPE html>

<html lang="en">

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



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

    <div class="wrapper">

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

        <?php @include("includes/sidebaroldstdboard.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="oldstdboard.php"

                                                class="text-primary">Home</a></li>

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

                                    </ol>

                                </nav>

                            </div>

                        </div>

                    </div>

                </div>

            </section>





            <section class="content">

                <div class="card shadow-sm">

                    <div class="card-header bg-primary text-white">

                        <h5 class="card-title font-weight-bold">

                            <i class="fas fa-clipboard-list"></i> Attendance Report for

                            <?php echo $month_names[str_pad($month, 2, '0', STR_PAD_LEFT)] . ' - ' . $year; ?>

                        </h5>

                    </div>

                    <div class="card-body">

                        <form method="POST">

                            <div class="row">

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

                                    <label for="month">Month</label>

                                    <select name="month" id="month" class="form-control select2" required>

                                        <?php foreach ($month_names as $key => $name) { ?>

                                            <option value="<?php echo $key; ?>" <?php if ($key == $month)

                                                   echo 'selected'; ?>>

                                                <?php echo $name; ?>

                                            </option>

                                        <?php } ?>

                                    </select>

                                </div>

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

                                    <label for="year">Year</label>

                                    <select name="year" id="year" class="form-control select2" required>

                                        <?php

                                        $current_year = date('Y');

                                        for ($y = $current_year; $y >= ($current_year - 5); $y--) { ?>

                                            <option value="<?php echo $y; ?>" <?php if ($y == $year)

                                                   echo 'selected'; ?>>

                                                <?php echo $y; ?>

                                            </option>

                                        <?php } ?>

                                    </select>

                                </div>

                            </div>

                            <div class="form-group text-center">

                                <button type="submit" class="btn btn-primary btn-block"><i class="fas fa-filter"></i>

                                    Filter</button>

                            </div>

                        </form>



                        <?php if (empty($attendance_days)) { ?>

                            <div class="alert alert-info text-center">

                                No attendance records found for

                                <?php echo $month_names[str_pad($month, 2, '0', STR_PAD_LEFT)] . ' - ' . $year; ?>.

                            </div>

                        <?php } else { ?>

                            <div class="table-responsive">

                                <table class="table table-bordered table-striped calendar-table text-center">

                                    <thead class="thead-light">

                                        <tr>

                                            <th>Sun</th>

                                            <th>Mon</th>

                                            <th>Tue</th>

                                            <th>Wed</th>

                                            <th>Thu</th>

                                            <th>Fri</th>

                                            <th>Sat</th>

                                        </tr>

                                    </thead>

                                    <tbody>

                                        <?php

                                        $first_day_of_month = date('w', strtotime("$year-$month-01"));

                                        $current_day = 1;

                                        $weeks = ceil(($days_in_month + $first_day_of_month) / 7);



                                        for ($week = 0; $week < $weeks; $week++) {

                                            echo "<tr>";

                                            for ($day = 0; $day < 7; $day++) {

                                                if (($week === 0 && $day < $first_day_of_month) || ($current_day > $days_in_month)) {

                                                    echo "<td></td>";

                                                } else {

                                                    $date_string = sprintf("%04d-%02d-%02d", $year, $month, $current_day);



                                                    if (isset($attendance_days[$date_string])) {

                                                        if ($attendance_days[$date_string] == 'Present') {

                                                            echo "<td class='present-day'><span>$current_day</span><br><i class='fas fa-check-circle'></i></td>";

                                                        } else {

                                                            echo "<td class='absent-day'><span>$current_day</span><br><i class='fas fa-times-circle'></i></td>";

                                                        }

                                                    } else {

                                                        echo "<td class='no-data-day'><span>$current_day</span></td>";

                                                    }

                                                    $current_day++;

                                                }

                                            }

                                            echo "</tr>";

                                        }

                                        ?>

                                    </tbody>

                                </table>

                            </div>

                        <?php } ?>



                    </div>

                </div>

            </section>



        </div>

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

    </div>



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



    <script src="dist/js/select2.min.js"></script>

    <script>

        $(document).ready(function () {

            $('.select2').select2();

        });

    </script>



    <style>

        .calendar-table {

            width: 100%;

            table-layout: fixed;

        }



        .calendar-table td {

            vertical-align: middle;

            height: 70px;

            /* reduced height */

            font-size: 1rem;

            position: relative;

            padding: 5px;

        }



        .calendar-table td span {

            font-weight: bold;

            display: block;

            margin-bottom: 3px;

        }



        .present-day {

            background-color: #28a745;

            color: white;

            font-weight: bold;

            border-radius: 6px;

        }



        .absent-day {

            background-color: #dc3545;

            color: white;

            font-weight: bold;

            border-radius: 6px;

        }



        .no-data-day {

            background-color: #f8f9fa;

            color: #6c757d;

            font-weight: bold;

            border-radius: 6px;

        }



        .calendar-table td i {

            font-size: 1.3rem;

        }



        /* Responsive settings for smaller devices */

        @media (max-width: 768px) {

            .calendar-table td {

                height: 50px;

                font-size: 0.85rem;

                padding: 3px;

            }



            .calendar-table td i {

                font-size: 1.1rem;

            }

        }



        /* Table container to allow horizontal scrolling on very small devices */

        .table-responsive {

            overflow-x: auto;

            -webkit-overflow-scrolling: touch;

        }

    </style>



</body>



</html>