<?php
session_start();
if (!isset($_SESSION['student_id'])) {
    header('Location: student_login.php');
    exit;
}

$lang = $_SESSION['lang'] ?? 'en';
$lang_strings = include 'lang.php';

require_once 'connectiondb.php';

// Fetch student name
$stmt = $pdo->prepare("SELECT name FROM students WHERE id = ?");
$stmt->execute([$_SESSION['student_id']]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);
$student_name = $student ? $student['name'] : 'Student';

$student_id = $_SESSION['student_id'];

try {
    // Debug: output student_id
    echo "<!-- Debug: student_id = $student_id -->";

    $stmt = $pdo->prepare("
        SELECT attendance_date, status
        FROM attendance
        WHERE student_id = ?
        ORDER BY attendance_date ASC
    ");
    $stmt->execute([$student_id]);
    $attendance_records = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Debug: output count of attendance records fetched
    $count = count($attendance_records);
    echo "<!-- Debug: attendance records fetched = $count -->";
} catch (PDOException $e) {
    die("Failed to fetch attendance records: " . $e->getMessage());
}

// Calculate attendance percentage
$present_count = 0;
$total_count = count($attendance_records);
$attendance_by_date = [];
foreach ($attendance_records as $record) {
    $attendance_by_date[$record['attendance_date']] = $record['status'];
    if (strtolower($record['status']) === 'present') {
        $present_count++;
    }
}
$attendance_percentage = $total_count > 0 ? round(($present_count / $total_count) * 100, 2) : 0;

// Get current month and year or from query params
$month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Calculate first day of month and total days
$first_day_of_month = mktime(0, 0, 0, $month, 1, $year);
$days_in_month = date('t', $first_day_of_month);
$month_name = date('F', $first_day_of_month);
$start_day_of_week = date('N', $first_day_of_month); // 1 (Mon) to 7 (Sun)

function getStatusColor($status) {
    switch (strtolower($status)) {
        case 'present':
            return 'bg-success text-white';
        case 'absent':
            return 'bg-danger text-white';
        case 'late':
            return 'bg-warning text-dark';
        case 'excused':
            return 'bg-info text-white';
        default:
            return '';
    }
}
?>
<!DOCTYPE html>
<html lang="<?php echo htmlspecialchars($lang); ?>">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Your Attendance - Calendar View</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <style>
        .calendar {
            max-width: 700px;
            margin: 20px auto;
        }
        .calendar th, .calendar td {
            width: 14.28%;
            height: 100px;
            vertical-align: top;
            border: 1px solid #dee2e6;
            padding: 5px;
        }
        .calendar .date-number {
            font-weight: bold;
        }
        .legend {
            max-width: 700px;
            margin: 10px auto;
            display: flex;
            justify-content: space-around;
        }
        .legend-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .legend-color {
            width: 20px;
            height: 20px;
            border-radius: 3px;
        }
        .progress {
            max-width: 700px;
            margin: 20px auto;
            height: 25px;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand" href="student_dashboard.php">MCQ Exam Portal</a>
    <div class="d-flex align-items-center">
      <span class="navbar-text text-white me-3"><?php echo htmlspecialchars($lang_strings[$lang]['welcome']); ?>, <?php echo htmlspecialchars($student_name); ?></span>
      <a href="student_dashboard.php" class="btn btn-light btn-sm me-2">Back to Dashboard</a>
      <a href="student_logout.php" class="btn btn-outline-light btn-sm">Logout</a>
    </div>
  </div>
</nav>
<div class="container my-4">
    <h2>Your Attendance - <?php echo htmlspecialchars($month_name . ' ' . $year); ?></h2>
    <p><strong>Attendance Percentage: </strong> <?php echo $attendance_percentage; ?>%</p>
    <div class="progress">
        <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $attendance_percentage; ?>%;" aria-valuenow="<?php echo $attendance_percentage; ?>" aria-valuemin="0" aria-valuemax="100">
            <?php echo $attendance_percentage; ?>%
        </div>
    </div>
    <form method="GET" class="mb-3">
        <label for="monthSelect" class="form-label">Select Month:</label>
        <select id="monthSelect" name="month" class="form-select d-inline-block w-auto" onchange="this.form.submit()">
            <?php
            for ($m = 1; $m <= 12; $m++) {
                $selected = ($m === $month) ? 'selected' : '';
                echo "<option value='$m' $selected>" . date('F', mktime(0, 0, 0, $m, 1)) . "</option>";
            }
            ?>
        </select>
        <label for="yearSelect" class="form-label ms-3">Select Year:</label>
        <select id="yearSelect" name="year" class="form-select d-inline-block w-auto" onchange="this.form.submit()">
            <?php
            $currentYear = (int)date('Y');
            for ($y = $currentYear; $y >= $currentYear - 5; $y--) {
                $selected = ($y === $year) ? 'selected' : '';
                echo "<option value='$y' $selected>$y</option>";
            }
            ?>
        </select>
    </form>
    <div class="calendar">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Mon</th>
                    <th>Tue</th>
                    <th>Wed</th>
                    <th>Thu</th>
                    <th>Fri</th>
                    <th>Sat</th>
                    <th>Sun</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $day = 1;
                $cell_count = 0;
                echo "<tr>";
                // Empty cells before first day
                for ($i = 1; $i < $start_day_of_week; $i++) {
                    echo "<td></td>";
                    $cell_count++;
                }
                while ($day <= $days_in_month) {
                    if ($cell_count % 7 == 0 && $cell_count != 0) {
                        echo "</tr><tr>";
                    }
                    $date_str = sprintf('%04d-%02d-%02d', $year, $month, $day);
                    $status = $attendance_by_date[$date_str] ?? '';
                    $color_class = getStatusColor($status);
                    echo "<td class='$color_class'>";
                    echo "<div class='date-number'>$day</div>";
                    if ($status) {
                        echo "<div>$status</div>";
                    }
                    echo "</td>";
                    $day++;
                    $cell_count++;
                }
                // Empty cells after last day
                while ($cell_count % 7 != 0) {
                    echo "<td></td>";
                    $cell_count++;
                }
                echo "</tr>";
                ?>
            </tbody>
        </table>
    </div>
    <div class="legend">
        <div class="legend-item"><div class="legend-color bg-success"></div> Present</div>
        <div class="legend-item"><div class="legend-color bg-danger"></div> Absent</div>
        <div class="legend-item"><div class="legend-color bg-warning"></div> Late</div>
        <div class="legend-item"><div class="legend-color bg-info"></div> Excused</div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
