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

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

$user_id = $_SESSION['user_id'];

// Get tenant's unpaid invoices
$sql = "SELECT i.*, l.lease_code, u.unit_number, p.name as property_name
        FROM invoices i
        JOIN leases l ON i.lease_id = l.id
        JOIN units u ON l.unit_id = u.id
        JOIN properties p ON u.property_id = p.id
        JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
        WHERE lt.tenant_id = (SELECT tenant_id FROM tenants WHERE user_id = ?)
        AND i.status IN ('unpaid', 'partial', 'overdue')
        ORDER BY i.due_date ASC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pay Rent')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

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

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Payments', 'title' => 'Pay Rent')); ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Outstanding Invoices</h4>
                                </div>
                                <div class="card-body">
                                    <?php if ($result && $result->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-nowrap align-middle mb-0">
                                                <thead>
                                                    <tr>
                                                        <th>Invoice #</th>
                                                        <th>Property/Unit</th>
                                                        <th>Description</th>
                                                        <th>Amount</th>
                                                        <th>Balance</th>
                                                        <th>Due Date</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while($invoice = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($invoice['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($invoice['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($invoice['description'] ?? $invoice['type']); ?></td>
                                                            <td>KES <?php echo number_format($invoice['total_amount'], 2); ?></td>
                                                            <td>
                                                                <span class="fw-semibold text-danger">KES <?php echo number_format($invoice['balance'], 2); ?></span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($invoice['due_date'])); ?></td>
                                                            <td>
                                                                <button class="btn btn-primary btn-sm" 
                                                                        onclick="openPaymentModal(<?php echo $invoice['id']; ?>, '<?php echo $invoice['invoice_number']; ?>', <?php echo $invoice['balance']; ?>)">
                                                                    <i class="ri-money-dollar-circle-line me-1"></i>Pay Now
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-4">
                                            <i class="ri-checkbox-circle-line fs-48 text-success mb-3"></i>
                                            <h5>All Paid Up!</h5>
                                            <p class="text-muted">You have no outstanding invoices.</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Payment Modal -->
    <div class="modal fade" id="paymentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Make Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="paymentForm" action="process_payment.php" method="POST">
                        <input type="hidden" id="paymentInvoiceId" name="invoice_id">
                        <div class="mb-3">
                            <label class="form-label">Invoice</label>
                            <input type="text" class="form-control" id="paymentInvoiceNumber" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Amount (KES)</label>
                            <input type="number" class="form-control" id="paymentAmount" name="amount" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Payment Method</label>
                            <select class="form-select" id="paymentMethod" name="payment_method" required>
                                <option value="">Select method...</option>
                                <option value="M-Pesa">M-Pesa</option>
                                <option value="Bank Transfer">Bank Transfer</option>
                                <option value="Cash">Cash</option>
                            </select>
                        </div>
                        <div class="mb-3" id="mpesaFields" style="display: none;">
                            <label class="form-label">Phone Number <span class="text-danger">*</span></label>
                            <input type="tel" class="form-control" name="phone_number" id="mpesaPhone" 
                                   placeholder="254XXXXXXXXX or 0XXXXXXXXX" required>
                            <small class="text-muted">You will receive an M-Pesa prompt on this number</small>
                            <div id="mpesaStatus" class="mt-2" style="display: none;"></div>
                        </div>
                        <div class="mb-3" id="bankFields" style="display: none;">
                            <label class="form-label">Reference Number</label>
                            <input type="text" class="form-control" name="reference_number">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" id="submitPaymentBtn" class="btn btn-primary" onclick="processPayment()">
                        <span id="submitBtnText">Submit Payment</span>
                        <span id="submitBtnSpinner" class="spinner-border spinner-border-sm ms-2" style="display: none;"></span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        let checkoutRequestId = null;
        let statusCheckInterval = null;
        
        function openPaymentModal(invoiceId, invoiceNumber, balance) {
            document.getElementById('paymentInvoiceId').value = invoiceId;
            document.getElementById('paymentInvoiceNumber').value = invoiceNumber;
            document.getElementById('paymentAmount').value = balance;
            document.getElementById('mpesaStatus').style.display = 'none';
            checkoutRequestId = null;
            new bootstrap.Modal(document.getElementById('paymentModal')).show();
        }

        document.getElementById('paymentMethod').addEventListener('change', function() {
            document.getElementById('mpesaFields').style.display = this.value === 'M-Pesa' ? 'block' : 'none';
            document.getElementById('bankFields').style.display = this.value === 'Bank Transfer' ? 'block' : 'none';
            document.getElementById('mpesaStatus').style.display = 'none';
        });
        
        function processPayment() {
            const form = document.getElementById('paymentForm');
            const formData = new FormData(form);
            const paymentMethod = formData.get('payment_method');
            
            if (paymentMethod === 'M-Pesa') {
                // Initiate STK Push
                initiateMpesaSTK(formData);
            } else {
                // Submit form normally for other payment methods
                form.submit();
            }
        }
        
        function initiateMpesaSTK(formData) {
            const submitBtn = document.getElementById('submitPaymentBtn');
            const submitBtnText = document.getElementById('submitBtnText');
            const submitBtnSpinner = document.getElementById('submitBtnSpinner');
            const statusDiv = document.getElementById('mpesaStatus');
            
            // Disable button and show spinner
            submitBtn.disabled = true;
            submitBtnText.textContent = 'Sending request...';
            submitBtnSpinner.style.display = 'inline-block';
            statusDiv.style.display = 'none';
            
            // Prepare data for STK push
            const invoiceId = formData.get('invoice_id');
            const data = {
                phone: formData.get('phone_number'),
                amount: formData.get('amount'),
                invoice_id: invoiceId || null,
                lease_id: null // Will be retrieved from invoice in callback
            };
            
            fetch('api/mpesa_stk_push_payment.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    checkoutRequestId = result.checkout_request_id;
                    statusDiv.innerHTML = '<div class="alert alert-info"><i class="ri-phone-line me-2"></i>' + result.message + '</div>';
                    statusDiv.style.display = 'block';
                    
                    // Start polling for payment status
                    startStatusCheck(result.transaction_id);
                } else {
                    statusDiv.innerHTML = '<div class="alert alert-danger">' + result.message + '</div>';
                    statusDiv.style.display = 'block';
                    submitBtn.disabled = false;
                    submitBtnText.textContent = 'Submit Payment';
                    submitBtnSpinner.style.display = 'none';
                }
            })
            .catch(error => {
                statusDiv.innerHTML = '<div class="alert alert-danger">Error: ' + error.message + '</div>';
                statusDiv.style.display = 'block';
                submitBtn.disabled = false;
                submitBtnText.textContent = 'Submit Payment';
                submitBtnSpinner.style.display = 'none';
            });
        }
        
        function startStatusCheck(transactionId) {
            let attempts = 0;
            const maxAttempts = 30; // Check for 30 seconds (1 second intervals)
            
            statusCheckInterval = setInterval(() => {
                attempts++;
                
                fetch('api/check_mpesa_payment_status.php?transaction_id=' + transactionId)
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            if (result.status === 'COMPLETED') {
                                clearInterval(statusCheckInterval);
                                document.getElementById('mpesaStatus').innerHTML = 
                                    '<div class="alert alert-success"><i class="ri-checkbox-circle-line me-2"></i>' + 
                                    result.message + '<br><small>Receipt: ' + result.mpesa_receipt + '</small></div>';
                                
                                // Redirect after 2 seconds
                                setTimeout(() => {
                                    window.location.href = 'my_payments.php';
                                }, 2000);
                            } else if (result.status === 'FAILED') {
                                clearInterval(statusCheckInterval);
                                document.getElementById('mpesaStatus').innerHTML = 
                                    '<div class="alert alert-danger">' + result.message + '</div>';
                                document.getElementById('submitPaymentBtn').disabled = false;
                                document.getElementById('submitBtnText').textContent = 'Try Again';
                                document.getElementById('submitBtnSpinner').style.display = 'none';
                            }
                        }
                    })
                    .catch(error => {
                        console.error('Status check error:', error);
                    });
                
                if (attempts >= maxAttempts) {
                    clearInterval(statusCheckInterval);
                    document.getElementById('mpesaStatus').innerHTML = 
                        '<div class="alert alert-warning">Payment status check timed out. Please check your M-Pesa or payment history.</div>';
                    document.getElementById('submitPaymentBtn').disabled = false;
                    document.getElementById('submitBtnText').textContent = 'Check Status';
                    document.getElementById('submitBtnSpinner').style.display = 'none';
                }
            }, 1000);
        }
    </script>
</body>
</html>
