<?php
// monthly_attendance.php

// Include session validation and database connection
include('session_validator.php');
include('includes/db_pdo.php');

// Get current academic year in the correct format (YYYY-YYYY)
$current_year = date('Y');
$next_year = $current_year + 1;
$academic_year = $current_year . '-' . $next_year;

// Optional: Get the actual academic year from database if you want to be sure
$stmt = $conn->query("SELECT DISTINCT academic_year FROM student_class_section_data ORDER BY academic_year DESC LIMIT 1");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
    $academic_year = $row['academic_year'];
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SRMS Admin - Monthly Attendance Management</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
    <link rel="stylesheet" href="css/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <script src="js/modernizr/modernizr.min.js"></script>
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .attendance-table th {
            background-color: #f8f9fa;
            text-align: center;
        }
        .attendance-table td {
            text-align: center;
            vertical-align: middle;
        }
        .attendance-input {
            width: 70px;
            text-align: center;
            margin: 0 auto;
        }
        .summary-card {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 5px;
            background-color: #17a2b8;
            color: white;
        }
        .total-summary {
            font-size: 16px;
            padding: 8px 12px;
            border-radius: 4px;
        }
        .total-present {
            background-color: #28a745;
            color: white;
        }
        .total-absent {
            background-color: #dc3545;
            color: white;
        }
        .data-exists-badge {
            display: inline-block;
            padding: 2px 8px;
            background-color: #ffc107;
            color: #000;
            border-radius: 12px;
            font-size: 11px;
            font-weight: normal;
            margin-left: 5px;
        }
        .input-locked {
            background-color: #e9ecef !important;
            cursor: not-allowed;
        }
        .unlock-btn {
            padding: 2px 8px;
            margin-left: 5px;
            font-size: 12px;
            border-radius: 4px;
            cursor: pointer;
            border: 1px solid #6c757d;
            background-color: #f8f9fa;
        }
        .unlock-btn:hover {
            background-color: #e2e6ea;
        }
        .existing-data-indicator {
            color: #856404;
            background-color: #fff3cd;
            border-color: #ffeeba;
            padding: 5px 10px;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        .info-text {
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
        }
        .working-days-container {
            position: relative;
        }
        .working-days-warning {
            position: absolute;
            bottom: -20px;
            left: 0;
            font-size: 11px;
        }
    </style>
</head>

<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <?php include('includes/leftbar.php'); ?>
            <div class="main-page">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="panel">
                                <div class="panel-heading">
                                    <div class="panel-title">
                                        <h5>Monthly Attendance Management</h5> 
                                        <div> <h6>Academic Year: <?php echo $academic_year; ?></h6></div>
                                    </div>
                                </div>
                                <div class="panel-body">
                            

                                    <form id="attendanceForm">
                                        <div class="row">
                                            <div class="form-group col-md-3">
                                                <label for="nepali_month">Nepali Month *</label>
                                                <select id="nepali_month" name="nepali_month" class="form-control" required>
                                                    <option value="">Select Nepali Month</option>
                                                    <?php
                                                    $nepali_months = [
                                                        'Baisakh', 'Jestha', 'Ashadh', 'Shrawan', 
                                                        'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 
                                                        'Poush', 'Magh', 'Falgun', 'Chaitra'
                                                    ];
                                                    
                                                    foreach ($nepali_months as $month) {
                                                        echo "<option value='$month'>$month</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-3">
                                                <label for="class_id">Select Class *</label>
                                                <select id="class_id" name="class_id" class="form-control" required>
                                                    <option value="">Select Class</option>
                                                    <?php
                                                    // Fetch classes from the database
                                                    $stmt = $conn->query("SELECT class_id, class FROM classes WHERE status = 1 ORDER BY class_numeric");
                                                    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='" . $row['class_id'] . "'>" . $row['class'] . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-3">
                                                <label for="section_id">Select Section *</label>
                                                <select id="section_id" name="section_id" class="form-control" required>
                                                    <option value="">First select a class</option>
                                                </select>
                                            </div>

                                            <div class="form-group col-md-3">
                                                <label for="total_working_days">Total Working Days *</label>
                                                <div class="working-days-container">
                                                    <input type="number" id="total_working_days" name="total_working_days" 
                                                           class="form-control" min="1" max="31" required>
                                                    <div id="workingDaysInfo" class="info-text"></div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="form-group col-md-12 text-center">
                                                <button type="button" id="loadStudents" class="btn btn-primary">
                                                    <i class="fa fa-search"></i> Load Students
                                                </button>
                                                <button type="button" id="resetForm" class="btn btn-secondary">
                                                    <i class="fa fa-refresh"></i> Reset
                                                </button>
                                            </div>
                                        </div>

                                        <div id="existingDataMessage" style="display:none;" class="alert alert-warning existing-data-indicator">
                                            <i class="fa fa-info-circle"></i> 
                                            <span id="existingDataText"></span>
                                        </div>

                                        <div id="students-list-container" style="display:none; margin-top:20px;">
                                            <h4>Student Attendance Entry</h4>
                                            <div class="table-responsive">
                                                <table class="table table-bordered attendance-table">
                                                    <thead>
                                                        <tr>
                                                            <th>S.No.</th>
                                                            <th>Student Name</th>
                                                            <th>Roll No.</th>
                                                            <th>Total Days</th>
                                                            <th>Days Present</th>
                                                            <th>Days Absent</th>
                                                            <th>Attendance %</th>
                                                            <th>Remarks</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="students-list">
                                                    </tbody>
                                                    <tfoot>
                                                        <tr>
                                                            <td colspan="2" class="text-left">
                                                                <strong>Class Summary:</strong>
                                                            </td>
                                                            <td colspan="2">
                                                                <span id="totalPresentSummary" class="badge badge-success total-summary">Total Present: 0</span>
                                                            </td>
                                                            <td colspan="2">
                                                                <span id="totalAbsentSummary" class="badge badge-danger total-summary">Total Absent: 0</span>
                                                            </td>
                                                            <td colspan="2">
                                                                <button type="button" id="calculateAbsent" class="btn btn-sm btn-info">
                                                                    <i class="fa fa-calculator"></i> Auto Calculate Absent
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>

                                            <div class="form-group text-center">
                                                <button class="btn btn-success" type="submit" id="submitBtn">
                                                    <i class="fa fa-save"></i> Save Monthly Attendance
                                                </button>
                                                <button type="button" id="unlockAllBtn" class="btn btn-warning" style="display:none;">
                                                    <i class="fa fa-unlock-alt"></i> Unlock All for Editing
                                                </button>
                                            </div>
                                        </div>
                                    </form>

                                    <div id="loader" style="display:none;" class="text-center">
                                        <img src="images/loader.gif" alt="Loading..." width="50">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/iscroll/iscroll.js"></script>
    <script src="js/prism/prism.js"></script>
    <script src="js/main.js"></script>

    <script>
    $(document).ready(function () {
        // Load sections when class is selected
        $('#class_id').change(function() {
            var classId = $(this).val();
            if (classId) {
                $.ajax({
                    type: 'POST',
                    url: 'get_sections.php',
                    data: { class_id: classId },
                    dataType: 'json',
                    success: function(response) {
                        var options = '<option value="">Select Section</option>';
                        if (response.status === 'success' && response.sections.length > 0) {
                            $.each(response.sections, function(index, section) {
                                options += '<option value="' + section.section_id + '">' + 
                                         section.section_name + '</option>';
                            });
                        } else {
                            options += '<option value="">No sections available</option>';
                        }
                        $('#section_id').html(options);
                    },
                    error: function() {
                        $('#section_id').html('<option value="">Error loading sections</option>');
                    }
                });
            } else {
                $('#section_id').html('<option value="">First select a class</option>');
            }
        });

        // Check if working days already exist for selected month
        $('#total_working_days').on('focusout', function() {
            checkExistingWorkingDays();
        });

        $('#nepali_month, #class_id, #section_id').change(function() {
            checkExistingWorkingDays();
        });

        function checkExistingWorkingDays() {
            var nepaliMonth = $('#nepali_month').val();
            var classId = $('#class_id').val();
            var sectionId = $('#section_id').val();
            var totalDays = $('#total_working_days').val();

            if (nepaliMonth && classId && sectionId) {
                $.ajax({
                    type: 'POST',
                    url: 'check_monthly_attendance.php',
                    data: {
                        nepali_month: nepaliMonth,
                        class_id: classId,
                        section_id: sectionId,
                        academic_year: '<?php echo $academic_year; ?>',
                        total_days: totalDays
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.exists) {
                            var message = 'Attendance data already exists for ' + response.record_count + ' students in this month. ';
                            if (response.total_days) {
                                message += 'Total working days: ' + response.total_days + '. ';
                            }
                            message += 'Existing data will be loaded for review.';
                            
                            $('#existingDataText').text(message);
                            $('#existingDataMessage').show();
                            
                            // If total days is empty or different, suggest correction
                            if (response.total_days && response.total_days != totalDays) {
                                $('#workingDaysInfo').html('<span class="text-warning"><i class="fa fa-exclamation-triangle"></i> Existing data has ' + response.total_days + ' working days. Consider using the same value.</span>');
                            } else {
                                $('#workingDaysInfo').html('');
                            }
                        } else {
                            $('#existingDataMessage').hide();
                            $('#workingDaysInfo').html('');
                        }
                    }
                });
            }
        }

        // Load students when button is clicked
        $('#loadStudents').click(function() {
            var classId = $('#class_id').val();
            var sectionId = $('#section_id').val();
            var nepaliMonth = $('#nepali_month').val();
            var totalWorkingDays = $('#total_working_days').val();

            if (!classId || !sectionId || !nepaliMonth || !totalWorkingDays) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Missing Information',
                    text: 'Please select class, section, Nepali month and enter total working days'
                });
                return;
            }

            loadStudents(classId, sectionId, nepaliMonth, totalWorkingDays);
        });

        // Reset form
        $('#resetForm').click(function() {
            $('#attendanceForm')[0].reset();
            $('#section_id').html('<option value="">First select a class</option>');
            $('#students-list-container').hide();
            $('#students-list').empty();
            $('#existingDataMessage').hide();
            $('#workingDaysInfo').html('');
            $('#unlockAllBtn').hide();
        });

        // Unlock All button functionality
        $('#unlockAllBtn').click(function() {
            unlockAllInputs();
        });

        function loadStudents(classId, sectionId, nepaliMonth, totalWorkingDays) {
            $('#loader').show();
            
            $.ajax({
                type: 'POST',
                url: 'get_monthly_attendance.php',
                data: {
                    class_id: classId,
                    section_id: sectionId,
                    nepali_month: nepaliMonth,
                    total_working_days: totalWorkingDays,
                    academic_year: '<?php echo $academic_year; ?>'
                },
                success: function(response) {
                    $('#loader').hide();
                    
                    if (response.trim() === '' || response.includes('No active students found')) {
                        Swal.fire({
                            icon: 'info',
                            title: 'No Students',
                            text: 'No active students found for the selected class and section'
                        });
                        $('#students-list-container').hide();
                        $('#unlockAllBtn').hide();
                    } else {
                        $('#students-list').html(response);
                        $('#students-list-container').show();
                        
                        // Check if any rows have existing data (locked state)
                        var hasLockedInputs = $('#students-list .input-locked').length > 0;
                        if (hasLockedInputs) {
                            $('#unlockAllBtn').show();
                            $('#submitBtn').text('Update Attendance');
                        } else {
                            $('#unlockAllBtn').hide();
                            $('#submitBtn').text('Save Monthly Attendance');
                        }
                        
                        // Update total summaries
                        updateTotalSummaries(totalWorkingDays);
                        
                        // Check for existing data message
                        checkExistingWorkingDays();
                        
                        // Focus on the first student's present days input after loading
                        setTimeout(function() {
                            $('#students-list tr:first-child input[name="days_present[]"]').focus();
                        }, 500);
                    }
                },
                error: function(xhr, status, error) {
                    $('#loader').hide();
                    console.error("AJAX error:", status, error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load students. Please try again.'
                    });
                }
            });
        }

        // Auto calculate absent days
        $(document).on('click', '#calculateAbsent', function() {
            var totalWorkingDays = parseInt($('#total_working_days').val());
            
            $('input[name="days_present[]"]').each(function() {
                if (!$(this).prop('readonly')) {
                    var presentDays = parseInt($(this).val()) || 0;
                    var absentDays = totalWorkingDays - presentDays;
                    if (absentDays < 0) absentDays = 0;
                    
                    $(this).closest('tr').find('input[name="days_absent[]"]').val(absentDays);
                    updateAttendancePercentage($(this).closest('tr'), totalWorkingDays);
                }
            });
            updateTotalSummaries(totalWorkingDays);
        });

        // Update absent days when present days change
        $(document).on('keyup change', 'input[name="days_present[]"]', function() {
            if ($(this).prop('readonly')) {
                return;
            }
            
            var totalWorkingDays = parseInt($('#total_working_days').val());
            var presentDays = parseInt($(this).val()) || 0;
            
            if (presentDays > totalWorkingDays) {
                presentDays = totalWorkingDays;
                $(this).val(totalWorkingDays);
            }
            
            var absentDays = totalWorkingDays - presentDays;
            $(this).closest('tr').find('input[name="days_absent[]"]').val(absentDays);
            updateAttendancePercentage($(this).closest('tr'), totalWorkingDays);
            updateTotalSummaries(totalWorkingDays);
        });

        // Unlock individual input
        $(document).on('click', '.unlock-btn', function() {
            var row = $(this).closest('tr');
            var presentInput = row.find('input[name="days_present[]"]');
            var remarksInput = row.find('input[name="remarks[]"]');
            
            presentInput.prop('readonly', false).removeClass('input-locked');
            remarksInput.prop('readonly', false);
            $(this).remove();
            
            // Add a small indicator that this row is now editable
            row.find('td:first').append('<span class="badge badge-warning" style="margin-left:5px;">Editing</span>');
            
            // Update total summaries
            updateTotalSummaries(parseInt($('#total_working_days').val()));
        });

        function unlockAllInputs() {
            $('#students-list tr').each(function() {
                var row = $(this);
                var presentInput = row.find('input[name="days_present[]"]');
                var remarksInput = row.find('input[name="remarks[]"]');
                
                if (presentInput.prop('readonly')) {
                    presentInput.prop('readonly', false).removeClass('input-locked');
                    remarksInput.prop('readonly', false);
                    row.find('.unlock-btn').remove();
                    row.find('td:first').append('<span class="badge badge-warning" style="margin-left:5px;">Editing</span>');
                }
            });
            
            $('#unlockAllBtn').hide();
            $('#submitBtn').text('Update Attendance');
            
            Swal.fire({
                icon: 'info',
                title: 'All Fields Unlocked',
                text: 'You can now edit all attendance records.',
                timer: 2000
            });
        }

        function updateAttendancePercentage(row, totalDays) {
            var presentDays = parseInt(row.find('input[name="days_present[]"]').val()) || 0;
            var percentage = ((presentDays / totalDays) * 100).toFixed(2);
            row.find('.attendance-percentage').text(percentage + '%');
            
            // Color code based on percentage
            var percentageCell = row.find('.attendance-percentage');
            if (percentage >= 75) {
                percentageCell.css('color', '#28a745').css('font-weight', 'bold');
            } else if (percentage >= 60) {
                percentageCell.css('color', '#ffc107').css('font-weight', 'bold');
            } else {
                percentageCell.css('color', '#dc3545').css('font-weight', 'bold');
            }
        }

        function updateTotalSummaries(totalDays) {
            var totalPresent = 0;
            
            $('input[name="days_present[]"]').each(function() {
                totalPresent += parseInt($(this).val()) || 0;
            });
            
            var totalAbsent = (totalDays * $('input[name="days_present[]"]').length) - totalPresent;
            
            $('#totalPresentSummary').text('Total Present: ' + totalPresent);
            $('#totalAbsentSummary').text('Total Absent: ' + totalAbsent);
        }

        // Keyboard navigation for 'w' (up) and 's' (down) keys
        $(document).on('keydown', 'input[name="days_present[]"]:not([readonly])', function(e) {
            var key = e.key.toLowerCase();
            
            if (key === 'w' || key === 's') {
                e.preventDefault();
                
                var currentInput = $(this);
                var currentRow = currentInput.closest('tr');
                var allRows = $('#students-list tr');
                var currentIndex = allRows.index(currentRow);
                
                if (key === 'w' && currentIndex > 0) {
                    var prevRow = allRows.eq(currentIndex - 1);
                    prevRow.find('input[name="days_present[]"]').focus().select();
                } else if (key === 's' && currentIndex < allRows.length - 1) {
                    var nextRow = allRows.eq(currentIndex + 1);
                    nextRow.find('input[name="days_present[]"]').focus().select();
                }
            }
        });

        // Enter key to move to next row
        $(document).on('keydown', 'input[name="days_present[]"]:not([readonly])', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                
                var currentRow = $(this).closest('tr');
                var allRows = $('#students-list tr');
                var currentIndex = allRows.index(currentRow);
                
                if (currentIndex < allRows.length - 1) {
                    var nextRow = allRows.eq(currentIndex + 1);
                    nextRow.find('input[name="days_present[]"]').focus().select();
                }
            }
        });

        // Submit attendance form
        $('#attendanceForm').submit(function (e) {
            e.preventDefault();
            
            if ($('#students-list tr').length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No Students',
                    text: 'Please load students first'
                });
                return;
            }

            $('#loader').show();

            // Collect form data
            var formData = {
                nepali_month: $('#nepali_month').val(),
                class_id: $('#class_id').val(),
                section_id: $('#section_id').val(),
                total_working_days: $('#total_working_days').val(),
                academic_year: '<?php echo $academic_year; ?>',
                student_ids: [],
                days_present: [],
                days_absent: [],
                remarks: [],
                update_mode: $('#unlockAllBtn').is(':visible') ? 'update' : 'insert'
            };

            // Validate and collect data
            var isValid = true;
            $('#students-list tr').each(function() {
                var presentDays = parseInt($(this).find('input[name="days_present[]"]').val()) || 0;
                
                if (presentDays > formData.total_working_days) {
                    isValid = false;
                    return false;
                }
                
                formData.student_ids.push($(this).data('student-id'));
                formData.days_present.push(presentDays);
                formData.days_absent.push($(this).find('input[name="days_absent[]"]').val() || 0);
                formData.remarks.push($(this).find('input[name="remarks[]"]').val() || '');
            });

            if (!isValid) {
                $('#loader').hide();
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    text: 'Present days cannot exceed total working days'
                });
                return;
            }

            $.ajax({
                type: 'POST',
                url: 'process_monthly_attendance.php',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    $('#loader').hide();
                    
                    if (response.status === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: response.message
                        }).then(() => {
                            $('#attendanceForm')[0].reset();
                            $('#section_id').html('<option value="">First select a class</option>');
                            $('#students-list-container').hide();
                            $('#students-list').empty();
                            $('#existingDataMessage').hide();
                            $('#unlockAllBtn').hide();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message
                        });
                    }
                },
                error: function (xhr, status, error) {
                    $('#loader').hide();
                    console.error("AJAX Error:", status, error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while saving attendance. Please try again.'
                    });
                }
            });
        });
    });
</script>
</body>
</html>