<?php
session_start();
if(isset($_SESSION['username'])){
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include 'includes/styles.php'; ?>
        <title>Leave Requests | <?php echo $school_name; ?></title>

        <?php
        require_once 'Classes/Attendance.php';
        $attendance = new Attendance();
        ?>
        <style>
            .request-card {
                background: white;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 15px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                border-left: 4px solid;
            }
            .request-pending { border-color: #ffc107;}
            .request-approved { border-color: #28a745; }
            .request-rejected { border-color: #dc3545; }

            .student-info {
                display: flex;
                align-items: center;
                margin-bottom: 15px;
            }
            .student-avatar {
                width: 60px;
                height: 60px;
                border-radius: 50%;
                margin-right: 15px;
                object-fit: cover;
            }
            .student-details h5 {
                margin: 0 0 5px 0;
                font-size: 1.1rem;
            }
            .student-details small {
                color: #666;
            }

            .leave-details {
                background: #f8f9fa;
                padding: 15px;
                border-radius: 6px;
                margin: 15px 0;
            }
            .leave-details .row {
                margin-bottom: 8px;
            }

            .action-buttons {
                display: flex;
                gap: 10px;
            }
            .action-buttons button {
                flex: 1;
            }

            .badge-pending { background: #ffc107; color: #000; }
            .badge-approved { background: #28a745; }
            .badge-rejected { background: #dc3545; }

            .filter-tabs {
                margin-bottom: 20px;
            }
            .filter-tabs .btn {
                margin-right: 10px;
                border-radius: 20px;
            }

            .stats-card {
                text-align: center;
                padding: 20px;
                background: white;
                border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                margin-bottom: 20px;
            }
            .stats-number {
                font-size: 2.5rem;
                font-weight: bold;
                margin: 10px 0;
            }
            .stats-label {
                color:#666;
                font-size: 0.9rem;
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
   <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

<div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0">Leave Requests</h1>
                        </div>
                       <div class="col-sm-6">
                           <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                                <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>attendance-dashboard">Attendance</a></li>
                                <li class="breadcrumb-item active">Leave Requests</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>


            <section class="content">
                <div class="container-fluid">

                    <!-- Statistics Row -->
                    <div class="row">
                        <?php
                        // Get pending requests count
                        $sql = "SELECT COUNT(*) FROM attendance_leave_requests WHERE status = 'pending'";
                        $conn->query($sql);
                        $pendingCount = $conn->fetchColumn();

                        // Get approved requests count (today)
                        $sql ="SELECT COUNT(*) FROM attendance_leave_requests 
                            WHERE status = 'approved' AND DATE(approved_at) = CURDATE()";
                        $conn->query($sql);
                        $approvedToday = $conn->fetchColumn();

                        // Get total requests this month
                        $sql = "SELECT COUNT(*) FROM attendance_leave_requests 
                            WHERE MONTH(requested_at) = MONTH(CURDATE()) 
                            AND YEAR(requested_at) = YEAR(CURDATE())";
                        $conn->query($sql);
                        $monthlyTotal = $conn->fetchColumn();
                        ?>

                        <div class="col-md-4">
                            <div class="stats-card" style="border-top: 4px solid #ffc107;">
                                <i class="fas fa-clock" style="font-size: 2rem; color: #ffc107;"></i>
                                <div class="stats-number" style="color: #ffc107;"><?php echo $pendingCount; ?></div>
                                <div class="stats-label">Pending Requests</div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="stats-card" style="border-top: 4px solid #28a745;">
                                <i class="fas fa-check-circle" style="font-size: 2rem; color: #28a745;"></i>
                                <div class="stats-number" style="color: #28a745;"><?php echo $approvedToday; ?></div>
                                <div class="stats-label">Approved Today</div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="stats-card" style="border-top: 4px solid #007bff;">
                                <i class="fas fa-calendar-alt" style="font-size:2rem; color: #007bff;"></i>
                                <div class="stats-number" style="color: #007bff;"><?php echo $monthlyTotal; ?></div>
                                <div class="stats-label">This Month</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Tabs -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="filter-tabs">
                                        <button class="btn btn-warning filter-btn active" data-status="pending">
                                           <i class="fas fa-clock"></i> Pending (<?php echo $pendingCount; ?>)
                                        </button>
                                        <button class="btn btn-success filter-btn" data-status="approved">
                                            <i class="fas fa-check"></i> Approved
                                        </button>
                                        <button class="btn btn-danger filter-btn" data-status="rejected">
                                            <i class="fas fa-times"></i> Rejected
                                        </button>
                                        <button class="btn btn-info filter-btn" data-status="all">
                                            <i class="fas fa-list"></i> All Requests
                                        </button>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4">
                                            <input type="text" id="search-input" class="form-control" placeholder="Search by student name or reg no...">
                                        </div>
                                        <div class="col-md-3">
                                            <select id="class-filter" class="form-control">
                                                <option value="">All Classes</option>
                                                <?php
                                                $sql = "SELECT * FROM classes ORDER BY name";
                                                $conn->query($sql);
                                                $classes = $conn->fetchMultiple();
                                                foreach($classes as $class) {
                                                    echo "<option value='{$class->id}'>{$class->name}</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <select id="date-filter" class="form-control">
                                                <option value="">All Dates</option>
                                                <option value="today">Today</option>
                                                <option value="week">This Week</option>
                                                <option value="month">This Month</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <button class="btn btn-primary btn-block" id="apply-filters">
                                                <i class="fas fa-filter"></i> Apply
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Leave Requests List -->
                    <div class="row">
                        <div class="col-md-12">
                            <div id="requests-container">
                                <!-- Requests will be loaded here -->
                                <div class="text-center" style="padding: 50px;">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="sr-only">Loading...</span>
                                    </div>
                                    <p>Loading leave requests...</p>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </section>

        </div>

        <?php include "includes/footer.php"; ?>

       <!-- Action Modal -->
       <div class="modal fade" id="actionModal" tabindex="-1">
           <div class="modal-dialog">
               <div class="modal-content">
                   <div class="modal-header">
                       <h5 class="modal-title" id="modalTitle">Confirm Action</h5>
                       <button type="button" class="close" data-dismiss="modal">
                           <span>&times;</span>
                       </button>
                   </div>
                   <form id="action-form">
                       <div class="modal-body">
                           <input type="hidden" id="request-id" name="request_id">
                           <input type="hidden" id="action-type" name="action">

                           <div class="form-group">
                               <label>Remarks/Comments</label>
                               <textarea class="form-control" id="admin-remarks" name="remarks" rows="3" required></textarea>
                           </div>

                           <div id="approve-section" style="display:none;">
                               <div class="alert alert-info">
                                   <i class="fas fa-info-circle"></i>
                                   Approving this leave will automatically update the student's attendance records for the specified dates.
                               </div>
                           </div>
                       </div>
                       <div class="modal-footer">
                           <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                           <button type="submit" class="btn btn-primary" id="confirm-action-btn">Confirm</button>
                       </div>
                   </form>
               </div>
           </div>
       </div>

       <script>
           let currentStatus = 'pending';
           let currentFilters ={
               search: '',
               class: '',
               dateRange: ''
           };

           $(document).ready(function() {
               // Load initial requests
               loadRequests();

               // Filter buttons
               $('.filter-btn').on('click', function() {
                   $('.filter-btn').removeClass('active');
                   $(this).addClass('active');
                   currentStatus = $(this).data('status');
                   loadRequests();
               });

               // Apply filters
               $('#apply-filters').on('click', function() {
                   currentFilters.search = $('#search-input').val();
                   currentFilters.class = $('#class-filter').val();
                   currentFilters.dateRange= $('#date-filter').val();
                   loadRequests();
               });

               // Search on enter
               $('#search-input').on('keypress', function(e) {
                   if(e.which === 13) {
                       $('#apply-filters').click();
                   }
               });

               // Action form submission
               $('#action-form').on('submit', function(e) {
                   e.preventDefault();
                   processAction();
               });
           });

           function loadRequests() {
               $.ajax({
                   url: 'get-leave-requests.php',
                   type: 'POST',
                   data: {
                       status: currentStatus,
                       search: currentFilters.search,
                      class_id: currentFilters.class,
                       date_range: currentFilters.dateRange
                   },
                   success: function(response) {
                       $('#requests-container').html(response);

                       // Attach event handlers
                       $('.approve-btn').on('click', function() {
                           showActionModal($(this).data('id'), 'approve');
});

                       $('.reject-btn').on('click', function() {
                           showActionModal($(this).data('id'), 'reject');
                       });

                       $('.view-details-btn').on('click', function() {
                           const card = $(this).closest('.request-card');
                           card.find('.leave-details').slideToggle();
});
                   },
                   error: function() {
                       $('#requests-container').html(
                           '<div class="alert alert-danger">Error loading requests. Please refresh the page.</div>'
                       );
                   }
               });
           }

           function showActionModal(requestId, action) {
               $('#request-id').val(requestId);
$('#action-type').val(action);

               if(action === 'approve') {
                   $('#modalTitle').text('Approve Leave Request');
                   $('#confirm-action-btn').removeClass('btn-danger').addClass('btn-success').text('Approve');
                   $('#approve-section').show();
               } else {
                   $('#modalTitle').text('Reject Leave Request');
                   $('#confirm-action-btn').removeClass('btn-success').addClass('btn-danger').text('Reject');
                   $('#approve-section').hide();
               }

               $('#admin-remarks').val('');
               $('#actionModal').modal('show');
           }

           function processAction() {
               const formData = $('#action-form').serialize();

               $('#confirm-action-btn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Processing...');

               $.ajax({
                   url: 'process-leave-action.php',
                   type: 'POST',
                   data: formData,
                   dataType: 'json',
                  success: function(response) {
                       if(response.success) {
                           $('#actionModal').modal('hide');

                           // Show success message
                           const alertClass = $('#action-type').val() === 'approve' ? 'success' : 'warning';
                           const message = `<div class="alert alert-${alertClass} alert-dismissible fade show">
                              <button type="button" class="close" data-dismiss="alert">&times;</button>
                               ${response.message}
                           </div>`;
                           
                           // Make sure the message is visible by adding it to a proper container
                           $('#requests-container').prepend(message);

                           // Reload requests after a short delay
                           setTimeout(function() {
                               loadRequests();
                           }, 1500);
                       } else {
                           // Show error message in modal
                           alert('Error: ' + response.message);
                       }
                   },
                   error: function() {
                       alert('Error processing request. Please try again.');
                   },
                   complete: function() {
$('#confirm-action-btn').prop('disabled', false).text('Confirm');
                   }
               });
           }
       </script>

    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include 'includes/styles.php'; ?>
    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6>You need to login to continue</h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $link;?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>