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

$conn = new Database();
$attendance_mgr = new Attendance();

if (!isset($_SESSION['teacher'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

if (isset($_POST['date']) && isset($_POST['class_id']) && isset($_POST['section_id']) && isset($_POST['attendance'])) {
    $date = $_POST['date'];
    $class_id = (int)$_POST['class_id'];
    $section_id = (int)$_POST['section_id'];
    $attendance_data = $_POST['attendance'];
    $marked_by = $_SESSION['teacher'];


    // Validate date
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Invalid date format
              </div>';
        exit();
    }

    // Check if date is not in future
    if (strtotime($date) > strtotime(date('Y-m-d'))) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Cannot mark attendance for future dates
              </div>';
        exit();
    }

    // Prepare bulk attendance data
    $bulk_data = [];
    foreach ($attendance_data as $student_data) {
        if (!empty($student_data['status'])) {
            $bulk_data[] = [
                'student_id' => (int)$student_data['student_id'],
                'status' => $student_data['status'],
                'remarks' => isset($student_data['remarks']) ? htmlspecialchars(trim($student_data['remarks'])) : ''
            ];
        }
    }

    if (empty($bulk_data)) {
        echo '<div class="alert alert-warning">
                <i class="fas fa-exclamation-circle"></i> No attendance data to save
              </div>';
        exit();
    }

    // Mark bulk attendance
    $result = $attendance_mgr->markBulkAttendance($class_id, $section_id, $date, $bulk_data, $marked_by);

    if ($result['success']) {
        echo '<div class="alert alert-success">
                <i class="fas fa-check-circle"></i> ' . $result['message'] . '
              </div>';
    } else {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> ' . $result['message'] . '
              </div>';
    }
} else {
    echo '<div class="alert alert-danger">Invalid request</div>';
}