<?php
require_once 'config/database.php';
requireAdmin(); // Ensure only admins can access this page

$pageTitle = "Member Approval";

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0 text-dark">
                        <i class="fas fa-user-check text-danger"></i> 
                        Member Approval
                    </h1>
                    <small class="text-muted">Review and approve pending membership applications</small>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php" class="text-primary">Home</a></li>
                        <li class="breadcrumb-item"><a href="members.php" class="text-primary">Members</a></li>
                        <li class="breadcrumb-item active">Member Approval</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Admin Assignment Filter -->
            <div class="row mb-3">
                <div class="col-md-12">
                    <div class="card card-outline card-primary">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-filter"></i> Filter Applications
                            </h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="statusFilter">Status</label>
                                        <select id="statusFilter" class="form-control">
                                            <option value="">All</option>
                                            <option value="pending" selected>Pending</option>
                                            <option value="under_review">Under Review</option>
                                            <option value="approved">Approved</option>
                                            <option value="rejected">Rejected</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="assignmentFilter">Assignment</label>
                                        <select id="assignmentFilter" class="form-control">
                                            <option value="">All</option>
                                            <option value="assigned_to_me">Assigned to Me</option>
                                            <option value="unassigned">Unassigned</option>
                                            <option value="assigned_to_others">Assigned to Others</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="dateFilter">Date Range</label>
                                        <select id="dateFilter" class="form-control">
                                            <option value="">All Time</option>
                                            <option value="today">Today</option>
                                            <option value="yesterday">Yesterday</option>
                                            <option value="this_week">This Week</option>
                                            <option value="this_month">This Month</option>
                                            <option value="custom">Custom Range</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>&nbsp;</label>
                                        <button id="applyFilters" class="btn btn-primary btn-block">
                                            <i class="fas fa-search"></i> Apply Filters
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div id="customDateRange" class="row mt-2" style="display: none;">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="dateFrom">From</label>
                                        <input type="date" id="dateFrom" class="form-control">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="dateTo">To</label>
                                        <input type="date" id="dateTo" class="form-control">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Stats Cards -->
            <div class="row">
                <div class="col-md-3 col-sm-6 col-12">
                    <div class="info-box bg-info">
                        <span class="info-box-icon"><i class="fas fa-hourglass-half"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Pending Applications</span>
                            <span class="info-box-number" id="pendingCount">0</span>
                            <div class="progress">
                                <div class="progress-bar" style="width: 100%"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6 col-12">
                    <div class="info-box bg-warning">
                        <span class="info-box-icon"><i class="fas fa-search"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Under Review</span>
                            <span class="info-box-number" id="reviewCount">0</span>
                            <div class="progress">
                                <div class="progress-bar" style="width: 100%"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6 col-12">
                    <div class="info-box bg-success">
                        <span class="info-box-icon"><i class="fas fa-check"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Approved Today</span>
                            <span class="info-box-number" id="approvedTodayCount">0</span>
                            <div class="progress">
                                <div class="progress-bar" style="width: 100%"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6 col-12">
                    <div class="info-box bg-danger">
                        <span class="info-box-icon"><i class="fas fa-times"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Rejected</span>
                            <span class="info-box-number" id="rejectedCount">0</span>
                            <div class="progress">
                                <div class="progress-bar" style="width: 100%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Members Pending Approval Table -->
            <div class="row">
                <div class="col-md-12">
                    <div class="card card-outline card-primary shadow">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-user-clock"></i> Membership Applications
                            </h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div id="memberApprovalsTableContainer" class="table-responsive">
                                <table id="memberApprovalsTable" class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>KSO ID</th>
                                            <th>Member</th>
                                            <th>Contact</th>
                                            <th>College</th>
                                            <th>Applied On</th>
                                            <th>Status</th>
                                            <th>Assigned To</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td colspan="8" class="text-center py-4">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="sr-only">Loading...</span>
                                                </div>
                                                <div class="mt-2">Loading applications...</div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Member Approval Modal -->
<div class="modal fade" id="approvalModal" tabindex="-1" role="dialog" aria-labelledby="approvalModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h5 class="modal-title" id="approvalModalLabel">
                    <i class="fas fa-user-check"></i> Member Approval
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="member_id">
                
                <div class="row mb-3">
                    <div class="col-md-4 text-center">
                        <img id="memberPhoto" src="dist/img/user-default.jpg" alt="Member Photo" class="img-circle elevation-2" style="width: 120px; height: 120px; object-fit: cover;">
                        <div class="mt-2">
                            <span id="memberKsoId" class="badge badge-info"></span>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <h4 id="memberName"></h4>
                        <p id="memberDetails" class="text-muted"></p>
                        <div class="row">
                            <div class="col-md-6">
                                <strong><i class="fas fa-envelope mr-1"></i> Email:</strong>
                                <p id="memberEmail" class="text-muted"></p>
                            </div>
                            <div class="col-md-6">
                                <strong><i class="fas fa-phone mr-1"></i> Phone:</strong>
                                <p id="memberPhone" class="text-muted"></p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card card-outline card-info">
                    <div class="card-header">
                        <h3 class="card-title">Member Information</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <strong><i class="fas fa-university mr-1"></i> College:</strong>
                                <p id="memberCollege" class="text-muted"></p>
                            </div>
                            <div class="col-md-6">
                                <strong><i class="fas fa-graduation-cap mr-1"></i> Course:</strong>
                                <p id="memberCourse" class="text-muted"></p>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <strong><i class="fas fa-calendar mr-1"></i> DOB:</strong>
                                <p id="memberDob" class="text-muted"></p>
                            </div>
                            <div class="col-md-6">
                                <strong><i class="fas fa-venus-mars mr-1"></i> Gender:</strong>
                                <p id="memberGender" class="text-muted"></p>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <strong><i class="fas fa-tint mr-1"></i> Blood Group:</strong>
                                <p id="memberBloodGroup" class="text-muted"></p>
                            </div>
                            <div class="col-md-6">
                                <strong><i class="fas fa-id-card mr-1"></i> Membership Type:</strong>
                                <p id="membershipType" class="text-muted"></p>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <strong><i class="fas fa-map-marker-alt mr-1"></i> Address:</strong>
                                <p id="memberAddress" class="text-muted"></p>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <strong><i class="fas fa-user-shield mr-1"></i> Emergency Contact:</strong>
                                <p id="memberEmergencyContact" class="text-muted"></p>
                            </div>
                            <div class="col-md-6">
                                <strong><i class="fas fa-calendar-alt mr-1"></i> Applied On:</strong>
                                <p id="memberCreatedAt" class="text-muted"></p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card card-outline card-warning">
                    <div class="card-header">
                        <h3 class="card-title">Admin Decision</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="approvalStatus">Application Status</label>
                            <select id="approvalStatus" class="form-control">
                                <option value="approved">Approve</option>
                                <option value="rejected">Reject</option>
                                <option value="under_review">Mark for Review</option>
                            </select>
                        </div>
                        <div id="rejectionReasonGroup" class="form-group" style="display: none;">
                            <label for="rejectionReason">Rejection Reason</label>
                            <textarea id="rejectionReason" class="form-control" rows="3" placeholder="Please specify the reason for rejection"></textarea>
                        </div>
                        <div id="assignmentGroup" class="form-group" style="display: none;">
                            <label for="assignTo">Assign to Admin</label>
                            <select id="assignTo" class="form-control">
                                <option value="">Select Admin</option>
                                <!-- Will be populated via API -->
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="approvalNotes">Notes</label>
                            <textarea id="approvalNotes" class="form-control" rows="3" placeholder="Add any additional notes about this application"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" id="assignButton" class="btn btn-warning">
                    <i class="fas fa-user-tag"></i> Assign
                </button>
                <button type="button" id="saveApprovalButton" class="btn btn-success">
                    <i class="fas fa-check"></i> Submit Decision
                </button>
            </div>
        </div>
    </div>
</div>

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap 4 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<!-- DataTables & Plugins -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Custom Scripts -->
<script>
    $(document).ready(function() {
        // Show/hide date range inputs
        $('#dateFilter').change(function() {
            if ($(this).val() === 'custom') {
                $('#customDateRange').show();
            } else {
                $('#customDateRange').hide();
            }
        });
        
        // Show/hide rejection reason
        $('#approvalStatus').change(function() {
            if ($(this).val() === 'rejected') {
                $('#rejectionReasonGroup').show();
            } else {
                $('#rejectionReasonGroup').hide();
            }
            
            if ($(this).val() === 'under_review') {
                $('#assignmentGroup').show();
            } else {
                $('#assignmentGroup').hide();
            }
        });
        
        // Initialize DataTable
        const approvalsTable = $('#memberApprovalsTable').DataTable({
            ajax: {
                url: 'api/member-approval/fetch.php',
                data: function(d) {
                    d.status = $('#statusFilter').val();
                    d.assignment = $('#assignmentFilter').val();
                    d.dateRange = $('#dateFilter').val();
                    d.dateFrom = $('#dateFrom').val();
                    d.dateTo = $('#dateTo').val();
                },
                dataSrc: function(json) {
                    if (json.success && json.data) {
                        // Update the counters
                        $('#pendingCount').text(json.counts.pending || 0);
                        $('#reviewCount').text(json.counts.under_review || 0);
                        $('#approvedTodayCount').text(json.counts.approved_today || 0);
                        $('#rejectedCount').text(json.counts.rejected || 0);
                        
                        return json.data;
                    } else {
                        console.error('Error loading approval data:', json.message);
                        $('#memberApprovalsTableContainer').html(
                            '<div class="alert alert-info">' +
                            '<i class="fas fa-info-circle mr-2"></i> ' +
                            'No member applications found matching your criteria.' +
                            '</div>'
                        );
                        return [];
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error:', error);
                    $('#memberApprovalsTableContainer').html(
                        '<div class="alert alert-danger">' +
                        '<i class="fas fa-exclamation-circle mr-2"></i> ' +
                        'Error loading member applications. Please try again later.' +
                        '</div>'
                    );
                    return [];
                }
            },
            columns: [
                { 
                    data: 'kso_id',
                    render: function(data) {
                        return '<span class="badge badge-info">' + data + '</span>';
                    }
                },
                { 
                    data: null,
                    render: function(data) {
                        return '<strong>' + data.first_name + ' ' + data.last_name + '</strong>';
                    }
                },
                {
                    data: null,
                    render: function(data) {
                        return '<a href="mailto:' + data.email + '"><i class="fas fa-envelope mr-1"></i>' + data.email + '</a><br>' +
                               '<a href="tel:' + data.phone + '"><i class="fas fa-phone mr-1"></i>' + data.phone + '</a>';
                    }
                },
                {
                    data: 'college',
                    render: function(data, type, row) {
                        return data + '<br><small>' + row.course + '</small>';
                    }
                },
                {
                    data: 'created_at',
                    render: function(data) {
                        const date = new Date(data);
                        return date.toLocaleDateString() + '<br><small>' + date.toLocaleTimeString() + '</small>';
                    }
                },
                {
                    data: 'status',
                    render: function(data) {
                        let badge = '';
                        switch (data) {
                            case 'pending':
                                badge = 'badge-info';
                                break;
                            case 'under_review':
                                badge = 'badge-warning';
                                break;
                            case 'approved':
                                badge = 'badge-success';
                                break;
                            case 'rejected':
                                badge = 'badge-danger';
                                break;
                            default:
                                badge = 'badge-secondary';
                        }
                        return '<span class="badge ' + badge + '">' + data.replace('_', ' ').toUpperCase() + '</span>';
                    }
                },
                {
                    data: null,
                    render: function(data) {
                        if (data.assigned_to) {
                            return data.assigned_to_name || 'Admin #' + data.assigned_to;
                        } else {
                            return '<span class="text-muted">Unassigned</span>';
                        }
                    }
                },
                {
                    data: null,
                    render: function(data) {
                        return '<div class="btn-group">' +
                               '<button type="button" class="btn btn-sm btn-info view-btn" data-id="' + data.id + '">' +
                               '<i class="fas fa-eye"></i></button>' +
                               '<button type="button" class="btn btn-sm btn-success approve-btn" data-id="' + data.id + '">' +
                               '<i class="fas fa-check"></i></button>' +
                               '<button type="button" class="btn btn-sm btn-danger reject-btn" data-id="' + data.id + '">' +
                               '<i class="fas fa-times"></i></button>' +
                               '</div>';
                    }
                }
            ],
            order: [[4, 'desc']],
            pageLength: 10,
            responsive: true,
            language: {
                emptyTable: "No member applications found",
                zeroRecords: "No matching applications found",
                info: "Showing _START_ to _END_ of _TOTAL_ applications",
                infoEmpty: "Showing 0 to 0 of 0 applications",
                infoFiltered: "(filtered from _MAX_ total applications)"
            }
        });
        
        // Reload table when filters are applied
        $('#applyFilters').click(function() {
            approvalsTable.ajax.reload();
        });
        
        // Load admin list for assignment
        function loadAdminList() {
            $.ajax({
                url: 'api/admins/fetch.php',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data) {
                        $('#assignTo').empty().append('<option value="">Select Admin</option>');
                        
                        response.data.forEach(function(admin) {
                            $('#assignTo').append('<option value="' + admin.id + '">' + 
                                admin.first_name + ' ' + admin.last_name + ' (' + admin.role + ')</option>');
                        });
                    }
                }
            });
        }
        
        // Load member details into approval modal
        function loadMemberDetails(memberId) {
            $.ajax({
                url: 'api/members/get-details.php',
                type: 'GET',
                data: { id: memberId },
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data) {
                        const member = response.data;
                        
                        // Set member ID in the hidden field
                        $('#member_id').val(member.id);
                        
                        // Set member photo if available
                        if (member.photo_url) {
                            $('#memberPhoto').attr('src', member.photo_url);
                        } else {
                            $('#memberPhoto').attr('src', 'dist/img/user-default.jpg');
                        }
                        
                        // Set member details
                        $('#memberKsoId').text(member.kso_id);
                        $('#memberName').text(member.first_name + ' ' + member.last_name);
                        $('#memberDetails').text(member.gender + ' • ' + member.course + ' • ' + member.college);
                        $('#memberEmail').text(member.email);
                        $('#memberPhone').text(member.phone || 'Not provided');
                        $('#memberCollege').text(member.college);
                        $('#memberCourse').text(member.course);
                        $('#memberDob').text(member.date_of_birth || 'Not provided');
                        $('#memberGender').text(member.gender || 'Not provided');
                        $('#memberBloodGroup').text(member.blood_group || 'Not provided');
                        $('#membershipType').text(member.membership_type);
                        $('#memberAddress').text(member.address || 'Not provided');
                        $('#memberEmergencyContact').text(
                            (member.emergency_contact_name ? member.emergency_contact_name + ': ' : '') + 
                            (member.emergency_contact || 'Not provided')
                        );
                        $('#memberCreatedAt').text(new Date(member.created_at).toLocaleString());
                        
                        // Reset form
                        $('#approvalStatus').val('approved');
                        $('#rejectionReason').val('');
                        $('#approvalNotes').val('');
                        $('#rejectionReasonGroup').hide();
                        $('#assignmentGroup').hide();
                        
                        // Show modal
                        $('#approvalModal').modal('show');
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message || 'Failed to load member details'
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load member details. Please try again.'
                    });
                }
            });
        }
        
        // Handle view button click
        $(document).on('click', '.view-btn', function() {
            const memberId = $(this).data('id');
            loadMemberDetails(memberId);
        });
        
        // Handle approve button click
        $(document).on('click', '.approve-btn', function() {
            const memberId = $(this).data('id');
            $('#member_id').val(memberId);
            $('#approvalStatus').val('approved');
            $('#rejectionReasonGroup').hide();
            $('#assignmentGroup').hide();
            
            Swal.fire({
                title: 'Quick Approve',
                text: 'Are you sure you want to approve this member?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, approve'
            }).then((result) => {
                if (result.isConfirmed) {
                    submitApproval();
                }
            });
        });
        
        // Handle reject button click
        $(document).on('click', '.reject-btn', function() {
            const memberId = $(this).data('id');
            
            Swal.fire({
                title: 'Rejection Reason',
                input: 'textarea',
                inputLabel: 'Please provide a reason for rejection',
                inputPlaceholder: 'Enter rejection reason...',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Reject',
                inputValidator: (value) => {
                    if (!value) {
                        return 'You need to provide a reason for rejection!';
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $('#member_id').val(memberId);
                    $('#approvalStatus').val('rejected');
                    $('#rejectionReason').val(result.value);
                    submitApproval();
                }
            });
        });
        
        // Handle assign button click
        $('#assignButton').click(function() {
            $('#approvalStatus').val('under_review');
            $('#assignmentGroup').show();
            $('#rejectionReasonGroup').hide();
        });
        
        // Handle save approval button click
        $('#saveApprovalButton').click(function() {
            submitApproval();
        });
        
        // Submit approval decision
        function submitApproval() {
            const memberId = $('#member_id').val();
            const status = $('#approvalStatus').val();
            const rejectionReason = $('#rejectionReason').val();
            const notes = $('#approvalNotes').val();
            const assignedTo = $('#assignTo').val();
            
            // Validation
            if (status === 'rejected' && !rejectionReason) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Validation Error',
                    text: 'Please provide a reason for rejection'
                });
                return;
            }
            
            if (status === 'under_review' && !assignedTo) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Validation Error',
                    text: 'Please select an admin for assignment'
                });
                return;
            }
            
            // Submit decision
            $.ajax({
                url: 'api/member-approval/process.php',
                type: 'POST',
                data: {
                    member_id: memberId,
                    status: status,
                    rejection_reason: rejectionReason,
                    notes: notes,
                    assigned_to: assignedTo
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: response.message || 'Application processed successfully'
                        }).then(() => {
                            $('#approvalModal').modal('hide');
                            approvalsTable.ajax.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message || 'Failed to process application'
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to process application. Please try again.'
                    });
                }
            });
        }
        
        // Load admin list on page load
        loadAdminList();
    });
</script>

<?php require_once 'templates/footer.php'; ?>
