<?php
require_once 'config/database.php';
requireAdmin();

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">Members Management</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item active">Members</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Info boxes -->
            <div class="row">
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box">
                        <span class="info-box-icon bg-info elevation-1"><i class="fas fa-users"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Members</span>
                            <span class="info-box-number" id="totalMembers">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-success elevation-1"><i class="fas fa-user-check"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Active Members</span>
                            <span class="info-box-number" id="activeMembers">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-user-clock"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Pending Approval</span>
                            <span class="info-box-number" id="pendingMembers">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-danger elevation-1"><i class="fas fa-user-times"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Suspended</span>
                            <span class="info-box-number" id="suspendedMembers">0</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Members Table -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">All Members</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-info mr-2" id="printMembersBtn">
                                    <i class="fas fa-print"></i> Print Members
                                </button>
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addMemberModal">
                                    <i class="fas fa-plus"></i> Add Member
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <table id="membersTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>KSO ID</th>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Phone</th>
                                        <th>College</th>
                                        <th>Membership Type</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Add Member Modal -->
<div class="modal fade" id="addMemberModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Add New Member</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="addMemberForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>First Name *</label>
                                <input type="text" class="form-control" name="first_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Last Name *</label>
                                <input type="text" class="form-control" name="last_name" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Email *</label>
                                <input type="email" class="form-control" name="email" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Phone</label>
                                <input type="tel" class="form-control" name="phone">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Date of Birth</label>
                                <input type="date" class="form-control" name="date_of_birth">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Gender</label>
                                <select class="form-control" name="gender">
                                    <option value="">Select Gender</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>College *</label>
                                <input type="text" class="form-control" name="college" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Course *</label>
                                <input type="text" class="form-control" name="course" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Membership Type *</label>
                                <select class="form-control" name="membership_type" required>
                                    <option value="">Select Type</option>
                                    <option value="Individual">Individual</option>
                                    <option value="Family">Family</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Blood Group</label>
                                <select class="form-control" name="blood_group">
                                    <option value="">Select Blood Group</option>
                                    <option value="A+">A+</option>
                                    <option value="A-">A-</option>
                                    <option value="B+">B+</option>
                                    <option value="B-">B-</option>
                                    <option value="AB+">AB+</option>
                                    <option value="AB-">AB-</option>
                                    <option value="O+">O+</option>
                                    <option value="O-">O-</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Add Member</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Load member statistics
    loadMemberStats();
    
    // Initialize DataTable
    const table = $('#membersTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "api/fetch_members.php",
            "dataSrc": function(json) {
                if (!json.success) {
                    console.error('Failed to load members:', json.message);
                    if (json.message === 'Authentication required') {
                        window.location.href = 'login.php';
                        return [];
                    }
                }
                return json.success ? json.data : [];
            },
            "error": function(xhr, error, thrown) {
                console.error('DataTable AJAX error:', error);
            }
        },
        "columns": [
            { "data": "kso_id" },
            { "data": null, "render": function(data) {
                return data.first_name + ' ' + data.last_name;
            }},
            { "data": "email" },
            { "data": "phone" },
            { "data": "college" },
            { "data": "membership_type" },
            { "data": "status", "render": function(data) {
                const badges = {
                    'active': 'success',
                    'pending': 'warning',
                    'suspended': 'danger',
                    'approved': 'success'
                };
                return `<span class="badge badge-${badges[data] || 'secondary'}">${data}</span>`;
            }},
            { "data": "created_at", "render": function(data) {
                return new Date(data).toLocaleDateString();
            }},
            { "data": null, "render": function(data) {
                return `
                    <button class="btn btn-sm btn-info" onclick="viewMember(${data.id})">View</button>
                    <button class="btn btn-sm btn-warning" onclick="editMember(${data.id})">Edit</button>
                    ${data.status === 'pending' ? `<button class="btn btn-sm btn-success" onclick="approveMember(${data.id})">Approve</button>` : ''}
                `;
            }}
        ]
    });

    // Add member form submission
    $('#addMemberForm').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        $.ajax({
            url: 'api/add_member.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#addMemberModal').modal('hide');
                    table.ajax.reload();
                    loadMemberStats();
                    toastr.success('Member added successfully');
                } else {
                    toastr.error(response.message);
                }
            },
            error: function() {
                toastr.error('Error adding member');
            }
        });
    });
    
    // Print members button
    $('#printMembersBtn').on('click', function() {
        // Check if the enhanced print system is available
        if (typeof printTable === 'function') {
            printTable('#membersTable', 'KUKI STUDENTS\' ORGANISATION - Members List');
        } else if (window.ksoPrint) {
            // If window.ksoPrint is available, use it with watermark option
            const table = document.querySelector('#membersTable');
            window.ksoPrint.printTable(table, {
                title: 'KUKI STUDENTS\' ORGANISATION - Members List',
                includeHeader: true,
                includeFooter: true,
                includeWatermark: true
            });
        } else {
            // Fallback to browser printing
            window.print();
        }
    });
});

function loadMemberStats() {
    $.get('api/fetch_member_stats.php', function(data) {
        if (data.success) {
            $('#totalMembers').text(data.data.total);
            $('#activeMembers').text(data.data.active);
            $('#pendingMembers').text(data.data.pending);
            $('#suspendedMembers').text(data.data.suspended);
        } else {
            console.error('Failed to load member stats:', data.message);
            if (data.message === 'Authentication required') {
                window.location.href = 'login.php';
            }
        }
    }).fail(function() {
        console.error('Failed to load member stats');
    });
}

function viewMember(id) {
    // Implementation for viewing member details
    window.location.href = `member-details.php?id=${id}`;
}

function editMember(id) {
    // Implementation for editing member
    window.location.href = `edit-member.php?id=${id}`;
}

function approveMember(id) {
    if (confirm('Are you sure you want to approve this member?')) {
        $.post('api/approve_member.php', {id: id}, function(response) {
            if (response.success) {
                $('#membersTable').DataTable().ajax.reload();
                loadMemberStats();
                toastr.success('Member approved successfully');
            } else {
                toastr.error(response.message);
            }
        });
    }
}
</script>

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