<?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">Membership Fee 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"><a href="finance.php">Finance</a></li>
                        <li class="breadcrumb-item active">Membership Fees</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Fee Statistics -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3 id="paidFees">0</h3>
                            <p>Paid Memberships</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-warning">
                        <div class="inner">
                            <h3 id="pendingFees">0</h3>
                            <p>Pending Payments</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-clock"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-danger">
                        <div class="inner">
                            <h3 id="overdueFees">0</h3>
                            <p>Overdue Payments</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3 id="totalRevenue">₹0</h3>
                            <p>Total Revenue</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-rupee-sign"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Fee Settings -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Fee Structure</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#feeSettingsModal">
                                    <i class="fas fa-edit"></i> Update Fees
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Membership Type</th>
                                        <th>Duration</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody id="feeStructureTable">
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Payment Methods</h3>
                        </div>
                        <div class="card-body">
                            <canvas id="paymentMethodChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Membership Fees Table -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Membership Fee Records</h3>
                            <div class="card-tools">
                                <div class="input-group input-group-sm" style="width: 300px;">
                                    <select id="statusFilter" class="form-control">
                                        <option value="">All Status</option>
                                        <option value="paid">Paid</option>
                                        <option value="pending">Pending</option>
                                        <option value="overdue">Overdue</option>
                                    </select>
                                    <select id="typeFilter" class="form-control ml-2">
                                        <option value="">All Types</option>
                                        <option value="individual">Individual</option>
                                        <option value="family">Family</option>
                                        <option value="student">Student</option>
                                        <option value="senior">Senior</option>
                                    </select>
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-default" onclick="loadMembershipFees()">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <table id="membershipFeesTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Member ID</th>
                                        <th>Member Name</th>
                                        <th>Membership Type</th>
                                        <th>Fee Amount</th>
                                        <th>Due Date</th>
                                        <th>Payment Status</th>
                                        <th>Payment Method</th>
                                        <th>Transaction ID</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Fee Settings Modal -->
<div class="modal fade" id="feeSettingsModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Update Fee Structure</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="feeSettingsForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h5>Individual Membership</h5>
                            <div class="form-group">
                                <label>1 Year (₹)</label>
                                <input type="number" class="form-control" name="individual_1_year" value="500">
                            </div>
                            <div class="form-group">
                                <label>2 Years (₹)</label>
                                <input type="number" class="form-control" name="individual_2_years" value="900">
                            </div>
                            <div class="form-group">
                                <label>3 Years (₹)</label>
                                <input type="number" class="form-control" name="individual_3_years" value="1300">
                            </div>
                            <div class="form-group">
                                <label>5 Years (₹)</label>
                                <input type="number" class="form-control" name="individual_5_years" value="2000">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h5>Family Membership</h5>
                            <div class="form-group">
                                <label>1 Year (₹)</label>
                                <input type="number" class="form-control" name="family_1_year" value="1000">
                            </div>
                            <div class="form-group">
                                <label>2 Years (₹)</label>
                                <input type="number" class="form-control" name="family_2_years" value="1800">
                            </div>
                            <div class="form-group">
                                <label>3 Years (₹)</label>
                                <input type="number" class="form-control" name="family_3_years" value="2500">
                            </div>
                            <div class="form-group">
                                <label>5 Years (₹)</label>
                                <input type="number" class="form-control" name="family_5_years" value="3800">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <h5>Student Membership</h5>
                            <div class="form-group">
                                <label>1 Year (₹)</label>
                                <input type="number" class="form-control" name="student_1_year" value="300">
                            </div>
                            <div class="form-group">
                                <label>2 Years (₹)</label>
                                <input type="number" class="form-control" name="student_2_years" value="550">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h5>Senior Citizen</h5>
                            <div class="form-group">
                                <label>1 Year (₹)</label>
                                <input type="number" class="form-control" name="senior_1_year" value="400">
                            </div>
                            <div class="form-group">
                                <label>Lifetime (₹)</label>
                                <input type="number" class="form-control" name="senior_lifetime" value="5000">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <h5>Additional Fees</h5>
                            <div class="form-group">
                                <label>Late Fee (₹)</label>
                                <input type="number" class="form-control" name="late_fee" value="100">
                            </div>
                            <div class="form-group">
                                <label>Processing Fee (₹)</label>
                                <input type="number" class="form-control" name="processing_fee" value="50">
                            </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">Update Fees</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Payment Record Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Record Payment</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="paymentForm">
                <div class="modal-body">
                    <input type="hidden" id="member_id" name="member_id">
                    <div class="form-group">
                        <label>Payment Amount (₹)</label>
                        <input type="number" class="form-control" name="amount" step="0.01" required>
                    </div>
                    <div class="form-group">
                        <label>Payment Method</label>
                        <select class="form-control" name="payment_method" required>
                            <option value="">Select Method</option>
                            <option value="cash">Cash</option>
                            <option value="upi">UPI</option>
                            <option value="card">Card</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="cheque">Cheque</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Transaction ID</label>
                        <input type="text" class="form-control" name="transaction_id">
                    </div>
                    <div class="form-group">
                        <label>Payment Date</label>
                        <input type="date" class="form-control" name="payment_date" required>
                    </div>
                    <div class="form-group">
                        <label>Notes</label>
                        <textarea class="form-control" name="notes" rows="3"></textarea>
                    </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">Record Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    loadMembershipStats();
    loadFeeStructure();
    loadMembershipFees();
    initializeChart();
    
    // Initialize DataTable
    $('#membershipFeesTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "api/finance/fetch_membership_fees.php",
            "data": function(d) {
                d.status = $('#statusFilter').val();
                d.type = $('#typeFilter').val();
            }
        },
        "columns": [
            { "data": "kso_id" },
            { "data": "member_name" },
            { "data": "membership_type" },
            { "data": "fee_amount", "render": function(data) {
                return '₹' + parseFloat(data).toLocaleString();
            }},
            { "data": "due_date" },
            { "data": "payment_status", "render": function(data) {
                const badges = {
                    'paid': 'badge-success',
                    'pending': 'badge-warning',
                    'overdue': 'badge-danger'
                };
                return `<span class="badge ${badges[data]}">${data.toUpperCase()}</span>`;
            }},
            { "data": "payment_method" },
            { "data": "transaction_id" },
            { "data": null, "render": function(data) {
                let actions = '';
                if (data.payment_status !== 'paid') {
                    actions += `<button class="btn btn-sm btn-success" onclick="recordPayment(${data.member_id}, '${data.member_name}', ${data.fee_amount})">
                        <i class="fas fa-money-bill"></i> Pay
                    </button> `;
                }
                actions += `<button class="btn btn-sm btn-info" onclick="viewPaymentHistory(${data.member_id})">
                    <i class="fas fa-history"></i> History
                </button>`;
                return actions;
            }}
        ]
    });
});

function loadMembershipStats() {
    $.get('api/finance/fetch_membership_stats.php', function(response) {
        if (response.success) {
            const stats = response.data;
            $('#paidFees').text(stats.paid_fees);
            $('#pendingFees').text(stats.pending_fees);
            $('#overdueFees').text(stats.overdue_fees);
            $('#totalRevenue').text('₹' + parseFloat(stats.total_revenue).toLocaleString());
        }
    });
}

function loadFeeStructure() {
    $.get('api/fetch_fee_structure.php', function(response) {
        if (response.success) {
            let html = '';
            response.data.forEach(function(fee) {
                html += `<tr>
                    <td>${fee.membership_type}</td>
                    <td>${fee.duration}</td>
                    <td>₹${parseFloat(fee.amount).toLocaleString()}</td>
                    <td><span class="badge badge-${fee.status === 'active' ? 'success' : 'secondary'}">${fee.status}</span></td>
                </tr>`;
            });
            $('#feeStructureTable').html(html);
        }
    });
}

function loadMembershipFees() {
    $('#membershipFeesTable').DataTable().ajax.reload();
}

function recordPayment(memberId, memberName, amount) {
    $('#member_id').val(memberId);
    $('#paymentForm input[name="amount"]').val(amount);
    $('#paymentModal .modal-title').text(`Record Payment - ${memberName}`);
    $('#paymentModal').modal('show');
}

function viewPaymentHistory(memberId) {
    window.location.href = `member-payment-history.php?member_id=${memberId}`;
}

function initializeChart() {
    const ctx = document.getElementById('paymentMethodChart').getContext('2d');
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['UPI', 'Cash', 'Card', 'Bank Transfer', 'Cheque'],
            datasets: [{
                data: [40, 25, 20, 10, 5],
                backgroundColor: [
                    '#007bff',
                    '#28a745',
                    '#ffc107',
                    '#17a2b8',
                    '#6c757d'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
}

// Form submissions
$('#feeSettingsForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'api/update_fee_structure.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            if (response.success) {
                toastr.success('Fee structure updated successfully');
                $('#feeSettingsModal').modal('hide');
                loadFeeStructure();
            } else {
                toastr.error(response.message);
            }
        },
        error: function() {
            toastr.error('Error updating fee structure');
        }
    });
});

$('#paymentForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'api/record_payment.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            if (response.success) {
                toastr.success('Payment recorded successfully');
                $('#paymentModal').modal('hide');
                loadMembershipFees();
                loadMembershipStats();
            } else {
                toastr.error(response.message);
            }
        },
        error: function() {
            toastr.error('Error recording payment');
        }
    });
});
</script>

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