<?php
// process_monthly_attendance.php

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

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // Validate required fields
    $required_fields = ['nepali_month', 'class_id', 'section_id', 'total_working_days', 'student_ids', 'days_present', 'days_absent'];
    foreach ($required_fields as $field) {
        if (!isset($_POST[$field])) {
            echo json_encode(['status' => 'error', 'message' => 'Missing required field: ' . $field]);
            exit;
        }
    }
    
    $nepali_month = $_POST['nepali_month'];
    $class_id = $_POST['class_id'];
    $section_id = $_POST['section_id'];
    $total_working_days = $_POST['total_working_days'];
    $academic_year = $_POST['academic_year'];
    $student_ids = $_POST['student_ids'];
    $days_present = $_POST['days_present'];
    $days_absent = $_POST['days_absent'];
    $remarks = isset($_POST['remarks']) ? $_POST['remarks'] : array_fill(0, count($student_ids), '');
    $update_mode = isset($_POST['update_mode']) ? $_POST['update_mode'] : 'insert';
    
    // Validate arrays length match
    if (count($student_ids) != count($days_present) || count($student_ids) != count($days_absent)) {
        echo json_encode(['status' => 'error', 'message' => 'Data mismatch']);
        exit;
    }
    
    try {
        $conn->beginTransaction();
        
        $success_count = 0;
        $fail_count = 0;
        
        for ($i = 0; $i < count($student_ids); $i++) {
            $student_id = $student_ids[$i];
            $present = $days_present[$i];
            $absent = $days_absent[$i];
            $remark = $remarks[$i];
            
            // Validate present days doesn't exceed total working days
            if ($present > $total_working_days) {
                $fail_count++;
                continue;
            }
            
            // Check if record already exists
            $checkSql = "SELECT id FROM monthly_attendance 
                        WHERE student_id = :student_id 
                        AND class_id = :class_id 
                        AND section_id = :section_id 
                        AND nepali_month = :nepali_month 
                        AND academic_year = :academic_year";
            
            $checkStmt = $conn->prepare($checkSql);
            $checkStmt->bindParam(':student_id', $student_id, PDO::PARAM_INT);
            $checkStmt->bindParam(':class_id', $class_id, PDO::PARAM_INT);
            $checkStmt->bindParam(':section_id', $section_id, PDO::PARAM_INT);
            $checkStmt->bindParam(':nepali_month', $nepali_month, PDO::PARAM_STR);
            $checkStmt->bindParam(':academic_year', $academic_year, PDO::PARAM_STR);
            $checkStmt->execute();
            
            $existing = $checkStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($existing) {
                // Update existing record
                $sql = "UPDATE monthly_attendance 
                        SET days_present = :days_present, 
                            days_absent = :days_absent, 
                            remarks = :remarks,
                            total_working_days = :total_working_days,
                            updated_at = NOW()
                        WHERE id = :id";
                
                $stmt = $conn->prepare($sql);
                $stmt->bindParam(':days_present', $present, PDO::PARAM_INT);
                $stmt->bindParam(':days_absent', $absent, PDO::PARAM_INT);
                $stmt->bindParam(':remarks', $remark, PDO::PARAM_STR);
                $stmt->bindParam(':total_working_days', $total_working_days, PDO::PARAM_INT);
                $stmt->bindParam(':id', $existing['id'], PDO::PARAM_INT);
            } else {
                // Insert new record
                $sql = "INSERT INTO monthly_attendance 
                        (student_id, class_id, section_id, nepali_month, academic_year, 
                         total_working_days, days_present, days_absent, remarks, created_at, updated_at) 
                        VALUES 
                        (:student_id, :class_id, :section_id, :nepali_month, :academic_year, 
                         :total_working_days, :days_present, :days_absent, :remarks, NOW(), NOW())";
                
                $stmt = $conn->prepare($sql);
                $stmt->bindParam(':student_id', $student_id, PDO::PARAM_INT);
                $stmt->bindParam(':class_id', $class_id, PDO::PARAM_INT);
                $stmt->bindParam(':section_id', $section_id, PDO::PARAM_INT);
                $stmt->bindParam(':nepali_month', $nepali_month, PDO::PARAM_STR);
                $stmt->bindParam(':academic_year', $academic_year, PDO::PARAM_STR);
                $stmt->bindParam(':total_working_days', $total_working_days, PDO::PARAM_INT);
                $stmt->bindParam(':days_present', $present, PDO::PARAM_INT);
                $stmt->bindParam(':days_absent', $absent, PDO::PARAM_INT);
                $stmt->bindParam(':remarks', $remark, PDO::PARAM_STR);
            }
            
            if ($stmt->execute()) {
                $success_count++;
            } else {
                $fail_count++;
            }
        }
        
        $conn->commit();
        
        $message = $success_count . ' attendance records ' . ($update_mode == 'update' ? 'updated' : 'saved') . ' successfully.';
        if ($fail_count > 0) {
            $message .= ' ' . $fail_count . ' records failed.';
        }
        
        echo json_encode([
            'status' => 'success', 
            'message' => $message,
            'success_count' => $success_count,
            'fail_count' => $fail_count
        ]);
        
    } catch (PDOException $e) {
        $conn->rollBack();
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
    
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>