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

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

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

if(!isset($_POST['request_id']) || !isset($_POST['action']) || !isset($_POST['remarks'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

$attendance = new Attendance();
$requestId = $_POST['request_id'];
$action = $_POST['action']; // 'approve' or 'reject'
$remarks = trim($_POST['remarks']);
$adminUsername = $_SESSION['teacher'];

try {
    // Get leave request details
    $sql = "SELECT * FROM attendance_leave_requests WHERE id = :request_id AND status = 'pending'";
    $attendance->query($sql);
    $attendance->bind(':request_id', $requestId);
    $leaveRequest = $attendance->fetchSingle();

    if(!$leaveRequest) {
        echo json_encode(['success' => false, 'message' => 'Leave request not found or already processed']);
        exit();
    }

    // Begin transaction
    $attendance->query("START TRANSACTION");
    $attendance->execute();

    // Update leave request status
    $newStatus = ($action === 'approve') ? 'approved' : 'rejected';
    $sql = "UPDATE attendance_leave_requests 
            SET status = :status, 
                approved_by = :admin, 
                approval_comment = :remarks,
                approved_at = NOW()
            WHERE id = :request_id";

    $attendance->query($sql);
    $attendance->bind(':status', $newStatus);
    $attendance->bind(':admin', $adminUsername);
    $attendance->bind(':remarks', $remarks);
    $attendance->bind(':request_id', $requestId);
    $attendance->execute();

    // If approved, update attendance records
    if($action === 'approve') {
        $studentId = $leaveRequest->student_id;
        $startDate = $leaveRequest->leave_from;
        $endDate = $leaveRequest->leave_to;

        // Get class and section for the student
        $sql = "SELECT classesID, sectionid FROM student WHERE studentID = :student_id";
        $attendance->query($sql);
        $attendance->bind(':student_id', $studentId);
        $studentInfo = $attendance->fetchSingle();

        // Generate date range
        $begin = new DateTime($startDate);
        $end = new DateTime($endDate);
        $end = $end->modify('+1 day');
        $interval = new DateInterval('P1D');
        $dateRange = new DatePeriod($begin, $interval, $end);

        foreach($dateRange as $date) {
            $dateStr = $date->format('Y-m-d');
            $dayOfWeek = $date->format('N'); // 1 (Monday) through 7 (Sunday)

            // Skip weekends
            if($dayOfWeek == 6 || $dayOfWeek == 7) {
                continue;
            }

            // Skip future dates
            if($dateStr > date('Y-m-d')) {
                continue;
            }

            // Check if attendance already exists for this date
            $sql = "SELECT id FROM student_attendance 
                    WHERE student_id = :student_id AND attendance_date = :date";
            $attendance->query($sql);
            $attendance->bind(':student_id', $studentId);
            $attendance->bind(':date', $dateStr);
            $existingRecord = $attendance->fetchSingle();

            if($existingRecord) {
                // Update existing record
                $sql = "UPDATE student_attendance 
                        SET status = 'Excused',
                            remarks = CONCAT(COALESCE(remarks, ''), ' [Leave Approved: ', :leave_type, ']'),
                            updated_at = NOW()
                        WHERE id = :id";
                $attendance->query($sql);
                $attendance->bind(':leave_type', $leaveRequest->leave_type);
                $attendance->bind(':id', $existingRecord->id);
                $attendance->execute();
            } else {
                // Insert new attendance record
                $sql = "INSERT INTO student_attendance 
                        (student_id, class_id, section_id, attendance_date, status, remarks, marked_by, marked_at)
                        VALUES 
                        (:student_id, :class_id, :section_id, :date, 'Excused', :remarks, :admin, NOW())";
                $attendance->query($sql);
                $attendance->bind(':student_id', $studentId);
                $attendance->bind(':class_id', $studentInfo->classesID);
                $attendance->bind(':section_id', $studentInfo->section);
                $attendance->bind(':date', $dateStr);
                $attendance->bind(':remarks', 'Leave Approved: ' . $leaveRequest->leave_type);
                $attendance->bind(':admin', $adminUsername);
                $attendance->execute();
            }
        }

        // Update student statistics
//        $attendance->updateStudentStatistics($studentId);

        // Update class summary for affected dates
        if($studentInfo) {
            foreach($dateRange as $date) {
                $dateStr = $date->format('Y-m-d');
                if($dateStr <= date('Y-m-d')) {
                    $attendance->updateClassSummary($studentInfo->classesID, $studentInfo->sectionid, $dateStr);
                }
            }
        }
    }

    // Create notification for student
    $notificationType = ($action === 'approve') ? 'leave_approved' : 'leave_rejected';
    $notificationMessage = ($action === 'approve')
        ? 'Your leave request has been approved.'
        : 'Your leave request has been rejected.';

    $sql = "INSERT INTO attendance_notifications 
            (student_id, notification_type, message, is_read, sent_at)
            VALUES (:student_id, :type, :message, 0, NOW())";
    $attendance->query($sql);
    $attendance->bind(':student_id', $leaveRequest->student_id);
    $attendance->bind(':type', $notificationType);
    $attendance->bind(':message', $notificationMessage . ' Remarks: ' . $remarks);
    $attendance->execute();

    // Commit transaction
    $attendance->query("COMMIT");
    $attendance->execute();

    $successMessage = ($action === 'approve')
        ? 'Leave request approved successfully. Attendance records have been updated.'
        : 'Leave request rejected successfully.';

    echo json_encode([
        'success' => true,
        'message' => $successMessage,
        'action' => $action
    ]);

} catch(Exception $e) {
    // Rollback on error
    $attendance->query("ROLLBACK");
    $attendance->execute();

    echo json_encode([
        'success' => false,
        'message' => 'Error processing request: ' . $e->getMessage()
    ]);
}