<?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">Finance 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">Finance</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-money-bill-wave"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Income</span>
                            <span class="info-box-number" id="totalIncome">₹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-check-circle"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Completed</span>
                            <span class="info-box-number" id="completedTransactions">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-clock"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Pending</span>
                            <span class="info-box-number" id="pendingTransactions">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-times-circle"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Failed</span>
                            <span class="info-box-number" id="failedTransactions">0</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Finance Table -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Financial Transactions</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addTransactionModal">
                                    <i class="fas fa-plus"></i> Add Transaction
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <table id="financeTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Member</th>
                                        <th>Transaction Type</th>
                                        <th>Amount</th>
                                        <th>Payment Method</th>
                                        <th>Receipt Number</th>
                                        <th>Status</th>
                                        <th>Payment Date</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Add Transaction Modal -->
<div class="modal fade" id="addTransactionModal" 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 Transaction</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="addTransactionForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Member *</label>
                                <select class="form-control" name="member_id" required>
                                    <option value="">Select Member</option>
                                    <!-- Options will be populated via AJAX -->
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Transaction Type *</label>
                                <select class="form-control" name="transaction_type" required>
                                    <option value="">Select Type</option>
                                    <option value="membership_fee">Membership Fee</option>
                                    <option value="donation">Donation</option>
                                    <option value="event_fee">Event Fee</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Amount (₹) *</label>
                                <input type="number" step="0.01" class="form-control" name="amount" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <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="bank_transfer">Bank Transfer</option>
                                    <option value="mobile_money">Mobile Money</option>
                                    <option value="card">Card</option>
                                    <option value="cheque">Cheque</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Receipt Number</label>
                                <input type="text" class="form-control" name="receipt_number">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Payment Date *</label>
                                <input type="date" class="form-control" name="payment_date" required>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Notes</label>
                        <textarea class="form-control" name="notes" rows="2"></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">Add Transaction</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Load finance statistics
    loadFinanceStats();
    loadMembers();
    
    // Initialize DataTable
    const table = $('#financeTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "api/finance/fetch_finance.php",
            "dataSrc": function(json) {
                return json.success ? json.data : [];
            }
        },
        "columns": [
            { "data": "member_name" },
            { "data": "transaction_type" },
            { "data": "amount", "render": function(data) {
                return `₹${parseFloat(data).toFixed(2)}`;
            }},
            { "data": "payment_method" },
            { "data": "receipt_number" },
            { "data": "status", "render": function(data) {
                const badges = {
                    'completed': 'success',
                    'pending': 'warning',
                    'failed': 'danger',
                    'cancelled': 'secondary'
                };
                return `<span class="badge badge-${badges[data] || 'secondary'}">${data}</span>`;
            }},
            { "data": "payment_date" },
            { "data": null, "render": function(data) {
                return `
                    <button class="btn btn-sm btn-info" onclick="viewTransaction(${data.id})">View</button>
                    <button class="btn btn-sm btn-warning" onclick="editTransaction(${data.id})">Edit</button>
                    <button class="btn btn-sm btn-success" onclick="generateReceipt(${data.id})">Receipt</button>
                `;
            }}
        ]
    });

    // Add transaction form submission
    $('#addTransactionForm').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        $.ajax({
            url: 'api/finance/add_transaction.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#addTransactionModal').modal('hide');
                    table.ajax.reload();
                    loadFinanceStats();
                    toastr.success('Transaction added successfully');
                } else {
                    toastr.error(response.message);
                }
            },
            error: function() {
                toastr.error('Error adding transaction');
            }
        });
    });
});

function loadFinanceStats() {
    $.get('api/finance/fetch_finance_stats.php', function(data) {
        if (data.success) {
            $('#totalIncome').text('₹' + parseFloat(data.data.total_income).toLocaleString());
            $('#completedTransactions').text(data.data.completed);
            $('#pendingTransactions').text(data.data.pending);
            $('#failedTransactions').text(data.data.failed);
        }
    });
}

function loadMembers() {
    $.get('api/fetch_members_dropdown.php', function(data) {
        if (data.success) {
            const select = $('select[name="member_id"]');
            select.empty().append('<option value="">Select Member</option>');
            data.data.forEach(function(member) {
                select.append(`<option value="${member.id}">${member.kso_id} - ${member.first_name} ${member.last_name}</option>`);
            });
        }
    });
}

function viewTransaction(id) {
    window.location.href = `transaction-details.php?id=${id}`;
}

function editTransaction(id) {
    window.location.href = `edit-transaction.php?id=${id}`;
}

function generateReceipt(id) {
    window.open(`api/finance/generate_receipt.php?id=${id}`, '_blank');
}
</script>

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