<?php
// check_monthly_attendance.php

include('session_validator.php');
include('includes/db_pdo.php');

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

if (isset($_POST['nepali_month']) && isset($_POST['class_id']) && isset($_POST['section_id']) && isset($_POST['academic_year'])) {
    
    $nepaliMonth = $_POST['nepali_month'];
    $class_id = $_POST['class_id'];
    $section_id = $_POST['section_id'];
    $academicYear = $_POST['academic_year'];
    $totalDays = isset($_POST['total_days']) ? $_POST['total_days'] : null;
    
    try {
        // Check if any attendance records exist for this combination
        $sql = "SELECT COUNT(*) as record_count, MAX(total_working_days) as working_days 
                FROM monthly_attendance 
                WHERE class_id = :class_id 
                AND section_id = :section_id 
                AND nepali_month = :nepali_month 
                AND academic_year = :academic_year";
        
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':class_id', $class_id, PDO::PARAM_INT);
        $stmt->bindParam(':section_id', $section_id, PDO::PARAM_INT);
        $stmt->bindParam(':nepali_month', $nepaliMonth, PDO::PARAM_STR);
        $stmt->bindParam(':academic_year', $academicYear, PDO::PARAM_STR);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result && $result['record_count'] > 0) {
            echo json_encode([
                'exists' => true,
                'record_count' => $result['record_count'],
                'total_days' => $result['working_days']
            ]);
        } else {
            echo json_encode(['exists' => false]);
        }
        
    } catch (PDOException $e) {
        echo json_encode([
            'exists' => false,
            'error' => 'Database error: ' . $e->getMessage()
        ]);
    }
    
} else {
    echo json_encode([
        'exists' => false,
        'error' => 'Missing parameters'
    ]);
}
?>