<?php
// get_monthly_attendance.php

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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (isset($_POST['class_id']) && isset($_POST['section_id']) && isset($_POST['nepali_month']) && isset($_POST['total_working_days'])) {
    $class_id = $_POST['class_id'];
    $section_id = $_POST['section_id'];
    $nepaliMonth = $_POST['nepali_month'];
    $totalWorkingDays = $_POST['total_working_days'];
    $academicYear = $_POST['academic_year'];

    // Get students for the selected class and section
    $sql = "SELECT s.student_id, s.name, s.class as roll_no 
            FROM students s 
            INNER JOIN student_class_section_data scsd ON s.student_id = scsd.student_id
            WHERE scsd.class_id = :class_id 
            AND scsd.section_id = :section_id 
            AND scsd.academic_year = :academic_year
            AND scsd.status = 'active'
            AND s.status = 'active'
            ORDER BY s.name ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':class_id', $class_id, PDO::PARAM_INT);
    $stmt->bindParam(':section_id', $section_id, PDO::PARAM_INT);
    $stmt->bindParam(':academic_year', $academicYear, PDO::PARAM_STR);
    $stmt->execute();
    
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Check if any attendance data exists for this month
    $attendanceExists = false;
    $existingCount = 0;
    
    if (count($students) > 0) {
        // Get first student to check if attendance exists
        $firstStudent = $students[0];
        $checkSql = "SELECT COUNT(*) as count FROM monthly_attendance 
                    WHERE 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(':class_id', $class_id, PDO::PARAM_INT);
        $checkStmt->bindParam(':section_id', $section_id, PDO::PARAM_INT);
        $checkStmt->bindParam(':nepali_month', $nepaliMonth, PDO::PARAM_STR);
        $checkStmt->bindParam(':academic_year', $academicYear, PDO::PARAM_STR);
        $checkStmt->execute();
        $result = $checkStmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result && $result['count'] > 0) {
            $attendanceExists = true;
            $existingCount = $result['count'];
        }
    }
    
    if (count($students) > 0) {
        $serial = 1;
        foreach ($students as $student) {
            // Check if attendance already exists for this specific student
            $checkSql = "SELECT days_present, days_absent, remarks 
                        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['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', $nepaliMonth, PDO::PARAM_STR);
            $checkStmt->bindParam(':academic_year', $academicYear, PDO::PARAM_STR);
            $checkStmt->execute();
            
            $existingAttendance = $checkStmt->fetch(PDO::FETCH_ASSOC);
            
            // Determine if input should be locked (existing data exists)
            $readonly = $existingAttendance ? 'readonly' : '';
            $lockedClass = $existingAttendance ? 'input-locked' : '';
            
            ?>
            <tr data-student-id="<?php echo $student['student_id']; ?>">
                <td><?php echo $serial++; ?></td>
                <td class="text-left"><?php echo htmlspecialchars($student['name']); ?></td>
                <td><?php echo htmlspecialchars($student['roll_no']); ?></td>
                <td><?php echo $totalWorkingDays; ?></td>
                <td>
                    <div style="display: flex; align-items: center; justify-content: center;">
                        <input type="number" name="days_present[]" class="form-control attendance-input <?php echo $lockedClass; ?>" 
                               value="<?php echo $existingAttendance ? $existingAttendance['days_present'] : '0'; ?>" 
                               min="0" max="<?php echo $totalWorkingDays; ?>" required <?php echo $readonly; ?>>
                        <?php if ($existingAttendance): ?>
                            <span class="unlock-btn" title="Click to unlock and edit">
                                <i class="fa fa-lock"></i>
                            </span>
                        <?php endif; ?>
                    </div>
                </td>
                <td>
                    <input type="number" name="days_absent[]" class="form-control attendance-input" 
                           value="<?php echo $existingAttendance ? $existingAttendance['days_absent'] : '0'; ?>" 
                           min="0" max="<?php echo $totalWorkingDays; ?>" readonly>
                </td>
                <td class="attendance-percentage">
                    <?php 
                    if ($existingAttendance) {
                        $percentage = ($existingAttendance['days_present'] / $totalWorkingDays) * 100;
                        echo number_format($percentage, 2) . '%';
                    } else {
                        echo '0.00%';
                    }
                    ?>
                </td>
                <td>
                    <input type="text" name="remarks[]" class="form-control" 
                           value="<?php echo $existingAttendance ? htmlspecialchars($existingAttendance['remarks']) : ''; ?>" 
                           placeholder="Remarks (optional)" <?php echo $readonly; ?>>
                </td>
            </tr>
            <?php
        }
        
        // Add a hidden data attribute to indicate if attendance exists
        echo '<input type="hidden" id="attendance_exists_flag" value="' . ($attendanceExists ? '1' : '0') . '">';
        echo '<input type="hidden" id="existing_records_count" value="' . $existingCount . '">';
        
    } else {
        echo '<tr><td colspan="8" class="text-center text-danger">No active students found in this class and section</td></tr>';
    }
} else {
    echo '<tr><td colspan="8" class="text-center text-danger">Invalid parameters</td></tr>';
}
?>