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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK', 'ACCOUNTANT', 'RECEPTIONIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: index.php');
    exit();
}

$page_title = "Record Payment";
$success_message = '';
$error_message = '';

// Get invoice if specified
$invoice_id = isset($_GET['invoice_id']) ? intval($_GET['invoice_id']) : 0;
$invoice_data = null;

if ($invoice_id) {
    $invoice_query = "SELECT i.*, p.patient_number, u.full_name as patient_name, u.phone_number
                      FROM invoices i
                      JOIN patients p ON i.patient_id = p.patient_id
                      JOIN users u ON p.user_id = u.user_id
                      WHERE i.invoice_id = $invoice_id";
    $invoice_result = mysqli_query($conn, $invoice_query);
    $invoice_data = mysqli_fetch_assoc($invoice_result);
}

// Get all unpaid invoices for dropdown - using exact schema
$invoices_query = "SELECT i.invoice_id, i.invoice_number, i.patient_id, u.full_name as patient_name,
                   i.total_amount, i.amount_paid, i.balance
                   FROM invoices i
                   JOIN patients p ON i.patient_id = p.patient_id
                   JOIN users u ON p.user_id = u.user_id
                   WHERE i.balance > 0 AND i.status != 'CANCELLED'
                   ORDER BY i.created_at DESC";
$invoices_result = mysqli_query($conn, $invoices_query);

// Generate payment number function
function generatePaymentNumber($conn) {
    $prefix = "PAY";
    $date = date('Ymd');
    
    $query = "SELECT COUNT(*) as count FROM payments WHERE DATE(created_at) = CURDATE()";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);
    $sequence = str_pad($row['count'] + 1, 4, '0', STR_PAD_LEFT);
    
    return $prefix . $date . $sequence;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['record_payment'])) {
    $invoice_id = mysqli_real_escape_string($conn, $_POST['invoice_id']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $amount = floatval($_POST['amount']);
    $payment_reference = mysqli_real_escape_string($conn, $_POST['payment_reference']);
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    
    // Optional fields based on payment method
    $card_last_four = isset($_POST['card_last_four']) ? mysqli_real_escape_string($conn, $_POST['card_last_four']) : NULL;
    $transaction_id = isset($_POST['transaction_id']) ? mysqli_real_escape_string($conn, $_POST['transaction_id']) : NULL;
    $mpesa_account_number = isset($_POST['mpesa_account_number']) ? mysqli_real_escape_string($conn, $_POST['mpesa_account_number']) : NULL;
    
    mysqli_begin_transaction($conn);
    
    try {
        // Get invoice details
        $inv_query = "SELECT balance, patient_id FROM invoices WHERE invoice_id = '$invoice_id'";
        $inv_result = mysqli_query($conn, $inv_query);
        $invoice = mysqli_fetch_assoc($inv_result);
        
        if ($amount > $invoice['balance']) {
            throw new Exception("Payment amount (KES " . number_format($amount, 2) . ") cannot exceed invoice balance (KES " . number_format($invoice['balance'], 2) . ")");
        }
        
        $payment_number = generatePaymentNumber($conn);
        
        // Insert payment - using exact schema columns
        $insert_payment = "INSERT INTO payments (
                          payment_number, invoice_id, patient_id, payment_method, 
                          payment_reference, amount, currency, exchange_rate,
                          mpesa_account_number, card_last_four, transaction_id,
                          received_by, status, notes
                          ) VALUES (
                          '$payment_number', '$invoice_id', '{$invoice['patient_id']}', '$payment_method',
                          " . ($payment_reference ? "'$payment_reference'" : "NULL") . ", 
                          '$amount', 'KES', 1.0000,
                          " . ($mpesa_account_number ? "'$mpesa_account_number'" : "NULL") . ",
                          " . ($card_last_four ? "'$card_last_four'" : "NULL") . ",
                          " . ($transaction_id ? "'$transaction_id'" : "NULL") . ",
                          {$_SESSION['user_id']}, 'COMPLETED', " . ($notes ? "'$notes'" : "NULL") . "
                          )";
        
        if (!mysqli_query($conn, $insert_payment)) {
            throw new Exception("Error recording payment: " . mysqli_error($conn));
        }
        
        $payment_id = mysqli_insert_id($conn);
        
        // Update invoice
        $new_amount_paid = "amount_paid + $amount";
        $new_balance = "balance - $amount";
        $new_status = $invoice['balance'] - $amount > 0.01 ? "'PARTIAL_PAYMENT'" : "'PAID'";
        
        $update_invoice = "UPDATE invoices SET 
                          amount_paid = $new_amount_paid,
                          balance = $new_balance,
                          status = $new_status
                          WHERE invoice_id = '$invoice_id'";
        
        if (!mysqli_query($conn, $update_invoice)) {
            throw new Exception("Error updating invoice: " . mysqli_error($conn));
        }
        
        mysqli_commit($conn);
        $_SESSION['success_message'] = "Payment $payment_number recorded successfully!";
        header("Location: list_payments.php");
        exit();
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error_message = $e->getMessage();
    }
}

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <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" />
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #047857 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .chart-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .summary-card {
            position: sticky;
            top: 20px;
            background: linear-gradient(135deg, #059669 0%, #047857 100%);
            border-radius: 12px;
            padding: 1.5rem;
            color: white;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .payment-method-option {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .payment-method-option:hover {
            border-color: #059669;
            background: #f0fdf4;
        }
        
        .payment-method-option.active {
            border-color: #059669;
            background: #dcfce7;
        }
        
        .method-extra-fields {
            display: none;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px dashed #e2e8f0;
        }
    </style>
</head>

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

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <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"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="financial_dashboard.php">Financial</a></li>
                                        <li class="breadcrumb-item"><a href="list_payments.php">Payments</a></li>
                                        <li class="breadcrumb-item active">Record</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-money-dollar-circle-line me-2"></i>Record Payment</h4>
                                <p class="mb-0">Process payment against patient invoice</p>
                            </div>
                            <a href="list_payments.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i> Back to Payments
                            </a>
                        </div>
                    </div>

                    <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <form method="POST" id="paymentForm">
                        <div class="row">
                            <!-- Payment Details -->
                            <div class="col-lg-8">
                                <!-- Invoice Selection -->
                                <div class="chart-card">
                                    <h5 class="mb-3"><i class="ri-file-text-line me-2"></i>Invoice Information</h5>
                                    
                                    <div class="row mb-3">
                                        <div class="col-md-12">
                                            <label class="form-label">Select Invoice <span class="text-danger">*</span></label>
                                            <select class="form-select select2" name="invoice_id" id="invoice_id" required>
                                                <option value="">Search and select invoice...</option>
                                                <?php 
                                                mysqli_data_seek($invoices_result, 0);
                                                while ($inv = mysqli_fetch_assoc($invoices_result)): 
                                                ?>
                                                <option value="<?php echo $inv['invoice_id']; ?>"
                                                        data-balance="<?php echo $inv['balance']; ?>"
                                                        data-patient="<?php echo htmlspecialchars($inv['patient_name']); ?>"
                                                        data-total="<?php echo $inv['total_amount']; ?>"
                                                        data-paid="<?php echo $inv['amount_paid']; ?>"
                                                        <?php echo ($invoice_data && $inv['invoice_id'] == $invoice_data['invoice_id']) ? 'selected' : ''; ?>>
                                                    <?php echo $inv['invoice_number'] . ' - ' . $inv['patient_name'] . ' (Balance: KES ' . number_format($inv['balance'], 2) . ')'; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>

                                    <!-- Invoice Details Display -->
                                    <div id="invoiceDetails" style="display: <?php echo $invoice_data ? 'block' : 'none'; ?>;">
                                        <div class="alert alert-info">
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <strong>Patient:</strong><br>
                                                    <span id="display_patient"><?php echo $invoice_data ? htmlspecialchars($invoice_data['patient_name']) : ''; ?></span>
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Total Amount:</strong><br>
                                                    <span id="display_total">KES <?php echo $invoice_data ? number_format($invoice_data['total_amount'], 2) : '0.00'; ?></span>
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Amount Paid:</strong><br>
                                                    <span id="display_paid" class="text-success">KES <?php echo $invoice_data ? number_format($invoice_data['amount_paid'], 2) : '0.00'; ?></span>
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Balance Due:</strong><br>
                                                    <span id="display_balance" class="text-danger fw-bold">KES <?php echo $invoice_data ? number_format($invoice_data['balance'], 2) : '0.00'; ?></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Payment Amount (KES) <span class="text-danger">*</span></label>
                                            <input type="number" class="form-control form-control-lg" name="amount" id="amount" 
                                                   min="0" step="0.01" required
                                                   value="<?php echo $invoice_data ? $invoice_data['balance'] : ''; ?>"
                                                   placeholder="0.00">
                                            <small class="text-muted">Maximum: <span id="max_amount">KES 0.00</span></small>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Payment Reference</label>
                                            <input type="text" class="form-control" name="payment_reference" 
                                                   placeholder="Receipt No, Transaction ID, etc.">
                                        </div>
                                    </div>
                                </div>

                                <!-- Payment Method Selection -->
                                <div class="chart-card">
                                    <h5 class="mb-3"><i class="ri-bank-card-line me-2"></i>Payment Method</h5>
                                    
                                    <div class="payment-method-option" data-method="CASH">
                                        <div class="d-flex align-items-center">
                                            <input type="radio" name="payment_method" value="CASH" id="method_cash" required>
                                            <label for="method_cash" class="ms-3 mb-0 flex-grow-1">
                                                <div class="d-flex align-items-center">
                                                    <i class="ri-money-dollar-circle-line fs-3 text-success me-3"></i>
                                                    <div>
                                                        <strong>Cash</strong>
                                                        <p class="mb-0 text-muted small">Physical cash payment</p>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>

                                    <div class="payment-method-option" data-method="MPESA">
                                        <div class="d-flex align-items-center">
                                            <input type="radio" name="payment_method" value="MPESA" id="method_mpesa" required>
                                            <label for="method_mpesa" class="ms-3 mb-0 flex-grow-1">
                                                <div class="d-flex align-items-center">
                                                    <i class="ri-smartphone-line fs-3 text-success me-3"></i>
                                                    <div>
                                                        <strong>M-Pesa</strong>
                                                        <p class="mb-0 text-muted small">Mobile money payment</p>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                        <div class="method-extra-fields" id="mpesa_fields">
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <label class="form-label">M-Pesa Phone Number</label>
                                                    <input type="text" class="form-control" name="mpesa_account_number" 
                                                           placeholder="254712345678">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="payment-method-option" data-method="CARD">
                                        <div class="d-flex align-items-center">
                                            <input type="radio" name="payment_method" value="CARD" id="method_card" required>
                                            <label for="method_card" class="ms-3 mb-0 flex-grow-1">
                                                <div class="d-flex align-items-center">
                                                    <i class="ri-bank-card-2-line fs-3 text-primary me-3"></i>
                                                    <div>
                                                        <strong>Card Payment</strong>
                                                        <p class="mb-0 text-muted small">Debit or Credit Card</p>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                        <div class="method-extra-fields" id="card_fields">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <label class="form-label">Last 4 Digits</label>
                                                    <input type="text" class="form-control" name="card_last_four" 
                                                           maxlength="4" placeholder="1234">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Transaction ID</label>
                                                    <input type="text" class="form-control" name="transaction_id" 
                                                           placeholder="TXN123456">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="payment-method-option" data-method="BANK_TRANSFER">
                                        <div class="d-flex align-items-center">
                                            <input type="radio" name="payment_method" value="BANK_TRANSFER" id="method_bank" required>
                                            <label for="method_bank" class="ms-3 mb-0 flex-grow-1">
                                                <div class="d-flex align-items-center">
                                                    <i class="ri-bank-line fs-3 text-info me-3"></i>
                                                    <div>
                                                        <strong>Bank Transfer</strong>
                                                        <p class="mb-0 text-muted small">Direct bank transfer</p>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>

                                    <div class="payment-method-option" data-method="CHEQUE">
                                        <div class="d-flex align-items-center">
                                            <input type="radio" name="payment_method" value="CHEQUE" id="method_cheque" required>
                                            <label for="method_cheque" class="ms-3 mb-0 flex-grow-1">
                                                <div class="d-flex align-items-center">
                                                    <i class="ri-file-list-line fs-3 text-warning me-3"></i>
                                                    <div>
                                                        <strong>Cheque</strong>
                                                        <p class="mb-0 text-muted small">Cheque payment</p>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>

                                    <div class="payment-method-option" data-method="INSURANCE_DIRECT">
                                        <div class="d-flex align-items-center">
                                            <input type="radio" name="payment_method" value="INSURANCE_DIRECT" id="method_insurance" required>
                                            <label for="method_insurance" class="ms-3 mb-0 flex-grow-1">
                                                <div class="d-flex align-items-center">
                                                    <i class="ri-shield-check-line fs-3 text-purple me-3"></i>
                                                    <div>
                                                        <strong>Insurance Direct Payment</strong>
                                                        <p class="mb-0 text-muted small">Direct from insurance company</p>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                <!-- Payment Notes -->
                                <div class="chart-card">
                                    <h5 class="mb-3"><i class="ri-file-text-line me-2"></i>Additional Information</h5>
                                    <div class="mb-0">
                                        <label class="form-label">Payment Notes (Optional)</label>
                                        <textarea class="form-control" name="notes" rows="3" 
                                                  placeholder="Any additional notes about this payment..."></textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Right Column - Summary -->
                            <div class="col-lg-4">
                                <div class="summary-card">
                                    <h5 class="mb-3 text-white"><i class="ri-calculator-line me-2"></i>Payment Summary</h5>
                                    
                                    <div class="mb-3 pb-3 border-bottom border-light border-opacity-25">
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Payment Amount:</span>
                                            <strong id="summary_amount">KES 0.00</strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Payment Method:</span>
                                            <strong id="summary_method">Not selected</strong>
                                        </div>
                                    </div>

                                    <div class="mb-3 pb-3 border-bottom border-light border-opacity-25">
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Invoice Balance:</span>
                                            <span id="summary_balance">KES 0.00</span>
                                        </div>
                                        <div class="d-flex justify-content-between">
                                            <span>After This Payment:</span>
                                            <strong id="summary_remaining">KES 0.00</strong>
                                        </div>
                                    </div>
                                    
                                    <div class="d-grid gap-2">
                                        <button type="submit" name="record_payment" class="btn btn-light btn-lg">
                                            <i class="ri-check-line me-2"></i>Record Payment
                                        </button>
                                        <button type="button" class="btn btn-outline-light" id="printReceipt">
                                            <i class="ri-printer-line me-2"></i>Print Receipt
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                    
                </div>
            </div>
        </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize Select2
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%',
            placeholder: 'Search and select invoice...'
        });

        let invoiceBalance = 0;

        // Handle invoice selection
        $('#invoice_id').on('change', function() {
            const selected = $(this).find(':selected');
            const balance = parseFloat(selected.data('balance')) || 0;
            const patient = selected.data('patient') || '';
            const total = parseFloat(selected.data('total')) || 0;
            const paid = parseFloat(selected.data('paid')) || 0;

            if ($(this).val()) {
                invoiceBalance = balance;
                $('#invoiceDetails').show();
                $('#display_patient').text(patient);
                $('#display_total').text('KES ' + total.toFixed(2));
                $('#display_paid').text('KES ' + paid.toFixed(2));
                $('#display_balance').text('KES ' + balance.toFixed(2));
                $('#max_amount').text('KES ' + balance.toFixed(2));
                $('#amount').val(balance.toFixed(2)).attr('max', balance);
                updateSummary();
            } else {
                $('#invoiceDetails').hide();
                invoiceBalance = 0;
            }
        });

        // Handle payment amount changes
        $('#amount').on('input', function() {
            const amount = parseFloat($(this).val()) || 0;
            if (amount > invoiceBalance) {
                $(this).val(invoiceBalance.toFixed(2));
                Swal.fire({
                    icon: 'warning',
                    title: 'Amount Exceeded',
                    text: 'Payment amount cannot exceed invoice balance'
                });
            }
            updateSummary();
        });

        // Handle payment method selection
        $('.payment-method-option').on('click', function() {
            $('.payment-method-option').removeClass('active');
            $(this).addClass('active');
            $(this).find('input[type="radio"]').prop('checked', true);
            
            // Hide all extra fields
            $('.method-extra-fields').hide();
            
            // Show relevant extra fields
            const method = $(this).data('method');
            if (method === 'MPESA') {
                $('#mpesa_fields').show();
            } else if (method === 'CARD') {
                $('#card_fields').show();
            }
            
            updateSummary();
        });

        // Update summary
        function updateSummary() {
            const amount = parseFloat($('#amount').val()) || 0;
            const method = $('input[name="payment_method"]:checked').next('label').find('strong').text() || 'Not selected';
            const remaining = invoiceBalance - amount;

            $('#summary_amount').text('KES ' + amount.toFixed(2));
            $('#summary_method').text(method);
            $('#summary_balance').text('KES ' + invoiceBalance.toFixed(2));
            $('#summary_remaining').text('KES ' + remaining.toFixed(2));
        }

        // Form validation
        $('#paymentForm').on('submit', function(e) {
            if (!$('#invoice_id').val()) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Invoice Required',
                    text: 'Please select an invoice'
                });
                return false;
            }

            const amount = parseFloat($('#amount').val()) || 0;
            if (amount <= 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Amount',
                    text: 'Payment amount must be greater than zero'
                });
                return false;
            }

            if (!$('input[name="payment_method"]:checked').val()) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Payment Method Required',
                    text: 'Please select a payment method'
                });
                return false;
            }
        });

        // Trigger change if invoice preselected
        <?php if ($invoice_data): ?>
        $('#invoice_id').trigger('change');
        <?php endif; ?>
    });
    </script>
</body>
</html>