<?php
session_start();
include 'layouts/main.php';
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch unmatched M-Pesa transactions
$sql = "SELECT * FROM mpesa_transactions WHERE visit_id IS NULL OR status = 'PENDING' ORDER BY transaction_date DESC";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'M-Pesa Reconciliation')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">M-Pesa Reconciliation</h4>
                                <div class="page-title-right">
                                    <div class="alert alert-info py-1 mb-0">Showing Unlinked Transactions</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Unmatched Payments</h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($result && $result->num_rows > 0): ?>
                                        <table id="mpesaReconTable"
                                            class="table table-bordered dt-responsive nowrap table-striped align-middle"
                                            style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>Receipt #</th>
                                                    <th>Phone Number</th>
                                                    <th>Name</th>
                                                    <th>Amount</th>
                                                    <th>Date</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($row = $result->fetch_assoc()): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($row['mpesa_receipt_number']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['phone_number']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>
                                                        </td>
                                                        <td>KES <?php echo number_format($row['amount'], 2); ?></td>
                                                        <td><?php echo date('d M Y H:i', strtotime($row['transaction_date'])); ?>
                                                        </td>
                                                        <td>
                                                            <button class="btn btn-sm btn-primary link-mpesa-btn" 
                                                                data-transaction-id="<?php echo $row['id']; ?>"
                                                                data-receipt="<?php echo htmlspecialchars($row['mpesa_receipt_number']); ?>"
                                                                data-amount="<?php echo $row['amount']; ?>"
                                                                data-phone="<?php echo htmlspecialchars($row['phone_number']); ?>"
                                                                data-name="<?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>">
                                                                <i class="ri-link"></i> Link to Invoice
                                                            </button>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="ri-checkbox-circle-line display-4 text-success"></i>
                                            <h5 class="mt-3">All Transactions Reconciled</h5>
                                            <p class="text-muted">There are no unmatched M-Pesa transactions at the moment.</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Link M-Pesa Modal -->
    <div class="modal fade" id="linkModal" tabindex="-1" aria-labelledby="linkModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="linkModalLabel">Link M-Pesa Payment to Invoice</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="linkMpesaForm">
                        <input type="hidden" id="transaction_id" name="transaction_id">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">M-Pesa Receipt</label>
                                <input type="text" class="form-control" id="mpesa_receipt" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Amount Paid</label>
                                <input type="text" class="form-control" id="mpesa_amount" readonly>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Phone Number</label>
                                <input type="text" class="form-control" id="mpesa_phone" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Customer Name</label>
                                <input type="text" class="form-control" id="mpesa_name" readonly>
                            </div>
                        </div>

                        <hr>

                        <div class="mb-3">
                            <label for="search_patient" class="form-label">Search Patient/Invoice <span class="text-danger">*</span></label>
                            <select class="form-select" id="search_patient" name="visit_id" required>
                                <option value="">Type to search by patient name, phone or invoice number...</option>
                            </select>
                            <small class="text-muted">Search for unpaid or partially paid invoices</small>
                        </div>

                        <div id="invoice_details" style="display:none;">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title">Invoice Details</h6>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>Invoice #:</strong> <span id="invoice_number"></span></p>
                                            <p><strong>Patient:</strong> <span id="patient_name"></span></p>
                                            <p><strong>Total Amount:</strong> <span id="invoice_total"></span></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>Paid:</strong> <span id="invoice_paid"></span></p>
                                            <p><strong>Balance:</strong> <span id="invoice_balance" class="text-danger fw-bold"></span></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="notes" class="form-label">Notes (Optional)</label>
                            <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="confirmLinkBtn">
                        <i class="ri-link"></i> Link Payment
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <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.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function () {
            // Initialize DataTable only if table exists
            <?php if ($result && $result->num_rows > 0): ?>
            $('#mpesaReconTable').DataTable({
                responsive: true,
                order: [[4, 'desc']],
                language: {
                    emptyTable: "No unmatched transactions available"
                }
            });
            <?php endif; ?>

            // Initialize Select2 for patient search
            $('#search_patient').select2({
                theme: 'bootstrap-5',
                dropdownParent: $('#linkModal'),
                ajax: {
                    url: 'ajax/search_unpaid_invoices.php',
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            search: params.term
                        };
                    },
                    processResults: function (data) {
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                minimumInputLength: 2,
                placeholder: 'Type to search...'
            });

            // When Link button is clicked
            $(document).on('click', '.link-mpesa-btn', function() {
                const transactionId = $(this).data('transaction-id');
                const receipt = $(this).data('receipt');
                const amount = $(this).data('amount');
                const phone = $(this).data('phone');
                const name = $(this).data('name');

                $('#transaction_id').val(transactionId);
                $('#mpesa_receipt').val(receipt);
                $('#mpesa_amount').val('KES ' + parseFloat(amount).toLocaleString('en-KE', {minimumFractionDigits: 2}));
                $('#mpesa_phone').val(phone);
                $('#mpesa_name').val(name);
                
                // Reset form
                $('#search_patient').val(null).trigger('change');
                $('#invoice_details').hide();
                $('#notes').val('');

                // Show modal
                const modal = new bootstrap.Modal(document.getElementById('linkModal'));
                modal.show();
            });

            // When invoice is selected
            $('#search_patient').on('change', function() {
                const visitId = $(this).val();
                
                if (visitId) {
                    $.ajax({
                        url: 'ajax/get_invoice_details.php',
                        method: 'POST',
                        data: { visit_id: visitId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                $('#invoice_number').text(response.data.invoice_number);
                                $('#patient_name').text(response.data.patient_name);
                                $('#invoice_total').text('KES ' + parseFloat(response.data.total_amount).toLocaleString('en-KE', {minimumFractionDigits: 2}));
                                $('#invoice_paid').text('KES ' + parseFloat(response.data.paid_amount).toLocaleString('en-KE', {minimumFractionDigits: 2}));
                                $('#invoice_balance').text('KES ' + parseFloat(response.data.balance).toLocaleString('en-KE', {minimumFractionDigits: 2}));
                                $('#invoice_details').slideDown();
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Failed to load invoice details'
                            });
                        }
                    });
                } else {
                    $('#invoice_details').slideUp();
                }
            });

            // Confirm link
            $('#confirmLinkBtn').on('click', function() {
                const visitId = $('#search_patient').val();
                
                if (!visitId) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Missing Information',
                        text: 'Please select an invoice to link this payment to.'
                    });
                    return;
                }

                const formData = {
                    transaction_id: $('#transaction_id').val(),
                    visit_id: visitId,
                    notes: $('#notes').val()
                };

                Swal.fire({
                    title: 'Confirm Linking',
                    text: 'Link this M-Pesa payment to the selected invoice?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Link It',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#667eea'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Show loading
                        Swal.fire({
                            title: 'Processing...',
                            text: 'Linking payment to invoice',
                            allowOutsideClick: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });

                        $.ajax({
                            url: 'ajax/link_mpesa_payment.php',
                            method: 'POST',
                            data: formData,
                            dataType: 'json',
                            success: function(response) {
                                if (response.success) {
                                    Swal.fire({
                                        icon: 'success',
                                        title: 'Payment Linked',
                                        text: response.message,
                                        timer: 2000,
                                        showConfirmButton: false
                                    }).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Error',
                                        text: response.message
                                    });
                                }
                            },
                            error: function(xhr, status, error) {
                                console.error('Error:', error);
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: 'An error occurred while linking the payment. Please try again.'
                                });
                            }
                        });
                    }
                });
            });
        });
    </script>
</body>

</html>