<?php
require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = getInput();

try {
    $db = getDB();

    switch ($method) {
        case 'GET':
            $date = $_GET['date'] ?? date('Y-m-d');
            $studentId = $_GET['studentId'] ?? '';

            if ($studentId) {
                $stmt = $db->prepare("SELECT * FROM attendance WHERE student_id = ? ORDER BY date DESC");
                $stmt->execute([$studentId]);
                sendJson($stmt->fetchAll());
            } else {
                $stmt = $db->prepare("SELECT a.*, s.full_name as student_name, s.student_id as student_code
                    FROM attendance a
                    LEFT JOIN students s ON a.student_id = s.id
                    WHERE a.date = ? ORDER BY s.full_name");
                $stmt->execute([$date]);
                sendJson($stmt->fetchAll());
            }
            break;

        case 'POST':
            // Mark attendance or holiday
            $status = $input['status'] ?? 'present';
            $date = $input['date'] ?? date('Y-m-d');
            $batchId = $input['batchId'] ?? 1;

            if ($status === 'holiday') {
                // Mark holiday for all students in batch
                $db->prepare("DELETE FROM attendance WHERE date = ? AND batch_id = ?")
                   ->execute([$date, $batchId]);

                // Get all active students in batch
                $studentStmt = $db->prepare("SELECT id FROM students WHERE batch_id = ? AND is_active = 1");
                $studentStmt->execute([$batchId]);
                $students = $studentStmt->fetchAll();

                $insertStmt = $db->prepare("INSERT INTO attendance (student_id, batch_id, date, status, marked_by)
                    VALUES (?, ?, ?, 'holiday', ?)");
                foreach ($students as $s) {
                    $insertStmt->execute([$s['id'], $batchId, $date, $input['markedBy'] ?? 0]);
                }
                sendJson(['success' => true, 'marked' => count($students)]);
            } else {
                // Mark individual student
                $stmt = $db->prepare("INSERT INTO attendance (student_id, batch_id, date, status, marked_by)
                    VALUES (?, ?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE status = ?, marked_by = ?");
                $stmt->execute([
                    $input['studentId'] ?? 0,
                    $batchId,
                    $date,
                    $status,
                    $input['markedBy'] ?? 0,
                    $status,
                    $input['markedBy'] ?? 0
                ]);
                sendJson(['success' => true]);
            }
            break;

        default:
            sendJson(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    sendJson(['error' => $e->getMessage()], 500);
}
