<?php
session_start();
require_once '../../admin/includes/database.php';
require_once '../../admin/Classes/Attendance.php';

header('Content-Type: application/json');

$conn = new Database();

if (!isset($_SESSION['student'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}


if(!isset($_POST['student_id']) || !isset($_POST['month']) || !isset($_POST['year'])) {
    echo json_encode([]);
    exit();
}
$studentId = $_POST['student_id'];
$month = $_POST['month'];
$year = $_POST['year'];

// Verify student ownership
$sql = "SELECT studentID FROM student WHERE studentID = :student_id AND username = :username";
$conn->query($sql);
$conn->bind(':student_id', $studentId);
$conn->bind(':username', $_SESSION['student']);
$student = $conn->fetchSingle();

if(!$student) {
    echo json_encode([]);
    exit();
}

// Get attendance for the month
$sql = "SELECT attendance_date, status, remarks 
        FROM student_attendance 
        WHERE student_id = :student_id 
        AND MONTH(attendance_date) = :month 
        AND YEAR(attendance_date) = :year
        ORDER BY attendance_date";

$conn->query($sql);
$conn->bind(':student_id', $studentId);
$conn->bind(':month', $month);
$conn->bind(':year', $year);

$records = $conn->fetchMultiple();

$result = [];
if($records) {
    foreach($records as $record) {
        $result[] = [
            'attendance_date' => $record->attendance_date,
            'status' => $record->status,
            'remarks' => $record->remarks
        ];
    }
}

echo json_encode($result);
