<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require_once 'connectiondb.php';

$student_id = $_GET['student_id'] ?? '';
if (empty($student_id)) {
    die("Student ID is required.");
}

$month = $_GET['month'] ?? date('Y-m');
$month_start = $month . '-01';
$month_end = date('Y-m-t', strtotime($month_start));

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Fetch student info
    $stmtStudent = $pdo->prepare("SELECT student_id, name FROM students WHERE id = ?");
    $stmtStudent->execute([$student_id]);
    $student = $stmtStudent->fetch(PDO::FETCH_ASSOC);
    if (!$student) {
        die("Student not found.");
    }

    // Fetch attendance records for the student for the selected month
    $stmtAttendance = $pdo->prepare("
        SELECT attendance_date, status
        FROM attendance
        WHERE student_id = ? AND attendance_date BETWEEN ? AND ?
        ORDER BY attendance_date
    ");
    $stmtAttendance->execute([$student_id, $month_start, $month_end]);
    $attendance_records_raw = $stmtAttendance->fetchAll(PDO::FETCH_ASSOC);

    // Map attendance by date
    $attendance_records = [];
    foreach ($attendance_records_raw as $record) {
        $attendance_records[$record['attendance_date']] = $record['status'];
    }

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

// Generate calendar for the month
$first_day_of_month = new DateTime($month_start);
$last_day_of_month = new DateTime($month_end);
$days_in_month = (int)$last_day_of_month->format('d');
$start_weekday = (int)$first_day_of_month->format('w'); // 0 (Sun) to 6 (Sat)

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Attendance Calendar for <?php echo htmlspecialchars($student['name']); ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<style>
    .present { background-color: #198754 !important; color: white !important; } /* Danger color */
    .absent { background-color:  #dc3545 !important; color: white !important; } /* Success color */
    .calendar-day {
        height: 100px;
        vertical-align: top;
        padding: 5px;
        border: 1px solid #dee2e6;
        text-align: center;
        vertical-align: middle;
    }
    .calendar-day-header {
        font-weight: bold;
        text-align: center;
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
    }
</style>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container my-4">
    <h2>Attendance Calendar for <?php echo htmlspecialchars($student['name']); ?> (<?php echo htmlspecialchars($student['student_id']); ?>)</h2>
    <form method="GET" action="admin_attendance_chart.php" class="mb-3">
        <input type="hidden" name="student_id" value="<?php echo htmlspecialchars($student_id); ?>" />
        <label for="month" class="form-label">Select Month:</label>
        <input type="month" id="month" name="month" value="<?php echo htmlspecialchars($month); ?>" class="form-control" style="max-width: 200px;" onchange="this.form.submit()" />
    </form>
    <table class="table table-bordered calendar-table">
        <thead>
            <tr>
                <th class="calendar-day-header">Sun</th>
                <th class="calendar-day-header">Mon</th>
                <th class="calendar-day-header">Tue</th>
                <th class="calendar-day-header">Wed</th>
                <th class="calendar-day-header">Thu</th>
                <th class="calendar-day-header">Fri</th>
                <th class="calendar-day-header">Sat</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $day = 1;
            $done = false;
            while (!$done) {
                echo '<tr>';
                for ($weekday = 0; $weekday < 7; $weekday++) {
                    if (($day == 1 && $weekday < $start_weekday) || $day > $days_in_month) {
                        // Empty cell before first day or after last day
                        echo '<td class="calendar-day"></td>';
                    } else {
                        $date_str = $month . '-' . str_pad($day, 2, '0', STR_PAD_LEFT);
                        $status = $attendance_records[$date_str] ?? '';
                        $class = ($status === 'present') ? 'present' : 'absent';
                        $display = ($status === 'present') ? 'P' : 'A';
                        echo '<td class="calendar-day ' . $class . '">';
                        echo '<div><strong>' . $day . '</strong></div>';
                        echo '<div style="font-size: 1.5em;">' . $display . '</div>';
                        echo '</td>';
                        $day++;
                    }
                }
                echo '</tr>';
                if ($day > $days_in_month) {
                    $done = true;
                }
            }
            ?>
        </tbody>
    </table>
    <a href="admin_attendance_progress.php" class="btn btn-secondary">Back to Attendance Progress</a>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
