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

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

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

if(!isset($_POST['student_id'])) {
    echo json_encode(['success' => false, 'message' => 'Student ID required']);
    exit();
}

$attendance = new Attendance();
$studentId = $_POST['student_id'];

try {
    // Get student info
    $sql = "SELECT s.*, c.name as class_name, sec.name as section_name 
            FROM student s 
            LEFT JOIN classes c ON s.classesID = c.id 
            LEFT JOIN sections sec ON s.sectionid = sec.id 
            WHERE s.studentID = :student_id";
    $attendance->query($sql);
    $attendance->bind(':student_id', $studentId);
    $student = $attendance->fetchSingle();

    if(!$student) {
        echo json_encode(['success' => false, 'message' => 'Student not found']);
        exit();
    }

    // Get attendance statistics
    $stats = $attendance->getStudentStatistics($studentId);

    // Get full attendance history
    $history = $attendance->getStudentAttendanceHistory($studentId);

    // Get monthly breakdown for chart
    $sql = "SELECT 
                DATE_FORMAT(attendance_date, '%Y-%m') as month,
                SUM(CASE WHEN status = 'Present' THEN 1 ELSE 0 END) as present,
                SUM(CASE WHEN status = 'Absent' THEN 1 ELSE 0 END) as absent,
                SUM(CASE WHEN status = 'Late' THEN 1 ELSE 0 END) as late,
                SUM(CASE WHEN status = 'Excused' THEN 1 ELSE 0 END) as excused
            FROM student_attendance 
            WHERE student_id = :student_id 
            GROUP BY DATE_FORMAT(attendance_date, '%Y-%m')
            ORDER BY month DESC
            LIMIT 6";
    $attendance->query($sql);
    $attendance->bind(':student_id', $studentId);
    $monthly = $attendance->fetchMultiple();

    // Format monthly data
    $monthlyFormatted = [];
    if($monthly) {
        foreach(array_reverse($monthly) as $m) {
            $date = DateTime::createFromFormat('Y-m', $m->month);
            $monthlyFormatted[] = [
                'month' => $date->format('M Y'),
                'present' => (int)$m->present,
                'absent' => (int)$m->absent,
                'late' => (int)$m->late,
                'excused' => (int)$m->excused
            ];
        }
    }

    // Prepare student data
    $studentData = [
        'name' => $student->name,
        'registerNO' => $student->registerNO,
        'class_name' => $student->class_name,
        'section_name' => $student->section_name,
        'photo' => !empty($student->photo) ? './upload/' . $student->photo : './upload/default.png'
    ];

    // Prepare statistics
    $statsData = [
        'total_days' => $stats ? $stats->total_days : 0,
        'present_days' => $stats ? $stats->present_days : 0,
        'absent_days' => $stats ? $stats->absent_days : 0,
        'late_days' => $stats ? $stats->late_days : 0,
        'excused_days' => $stats ? $stats->excused_days : 0,
        'attendance_percentage' => $stats ? $stats->attendance_percentage : 0
    ];

    // Format history data
    $historyData = [];
    if($history) {
        foreach($history as $record) {
            $historyData[] = [
                'attendance_date' => $record->attendance_date,
                'status' => $record->status,
                //'time_in' => $record->time_in,
                'remarks' => $record->remarks,
                'marked_by' => $record->marked_by
            ];
        }
    }

    echo json_encode([
        'success' => true,
        'student' => $studentData,
        'statistics' => $statsData,
        'history' => $historyData,
        'monthly' => $monthlyFormatted
    ]);

} catch(Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}