<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";

// Check if user is logged in
if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit;
}

// Get session variables
$studentid = $_SESSION['studentid'];
$firstname = $_SESSION['firstname'] ?? '';
$lastname = $_SESSION['lastname'] ?? '';
$email = $_SESSION['email'] ?? '';
$phone = $_SESSION['phone'] ?? '';
$intake = $_SESSION['intake'] ?? '';
$program = $_SESSION['program'] ?? '';

// Define API credentials
define('API_KEY', '76d2ea13-10e0-48e7-8e0e-7261bac5ced7');
define('API_SECRET', '0b15eb80a64d3528cbfc6cd76889b7e71af204aa');
define('BASE_URL', 'https://tumeny.herokuapp.com');

// Get outstanding invoices
$outstandingQuery = "SELECT 
    ai.`id`, ai.`student_type`, ai.`description`, 
    ai.`amount`, ai.`year`, ai.`semester`, 
    ai.`due_date`, ai.`created_at`,
    COALESCE(SUM(ap.`amount`), 0) as amount_paid,
    (ai.`amount` - COALESCE(SUM(ap.`amount`), 0)) as balance
    FROM `association_invoice` ai
    LEFT JOIN `association_payment` ap 
        ON ai.`id` = ap.`invoice_id` 
        AND ap.`studentid` = '$studentid' 
        AND ap.`status` = 'paid'
    GROUP BY ai.`id`
    HAVING balance > 0 OR amount_paid IS NULL
    ORDER BY ai.`due_date` ASC";
$outstandingInvoices = mysqli_query($conn, $outstandingQuery);

// Get payment history
$paymentHistoryQuery = "SELECT 
    `id`, `invoice_id`, `amount`, `payment_method`, 
    `status`, `gateway_reference`, `payment_date`
    FROM `association_payment` 
    WHERE `studentid` = '$studentid'
    ORDER BY `payment_date` DESC
    LIMIT 10";
$paymentHistory = mysqli_query($conn, $paymentHistoryQuery);

// API Functions
function getAuthToken(): string {
    $ch = curl_init(BASE_URL . "/api/token");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'apiKey: ' . API_KEY,
        'apiSecret: ' . API_SECRET,
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($error) {
        error_log("Token Error: $error | HTTP Code: $httpCode");
        $_SESSION['payment_error'] = "Authentication failed: " . $error;
        return '';
    }

    $responseData = json_decode($response, true);
    error_log("Auth Token Response: " . json_encode($responseData));
    
    if (isset($responseData['error'])) {
        $_SESSION['payment_error'] = "Authentication failed: " . $responseData['error'];
        return '';
    }

    return $responseData['token'] ?? '';
}

function createPayment($authToken, $paymentData) {
    error_log("Creating payment with data: " . json_encode($paymentData));
    
    $ch = curl_init(BASE_URL . "/api/v1/payment");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $authToken,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paymentData));

    $response = curl_exec($ch);
    $error = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($error) {
        error_log("Payment Creation Error: $error | HTTP Code: $httpCode");
        return ['error' => true, 'message' => $error];
    }

    $responseData = json_decode($response, true);
    error_log("Payment Creation Response: " . json_encode($responseData));
    
    return $responseData;
}

function checkPaymentStatus($authToken, $paymentId) {
    $ch = curl_init(BASE_URL . "/api/v1/payment/$paymentId");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $authToken
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        error_log("Payment Status Error: $error");
        return ['error' => true];
    }

    return json_decode($response, true);
}

// Handle payment form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['make_payment'])) {
    $invoice_id = mysqli_real_escape_string($conn, $_POST['invoice_id']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    
    // Validate required fields
    if (empty($invoice_id) || empty($amount) || empty($payment_method) || empty($phone)) {
        $_SESSION['payment_error'] = "Please fill all required fields.";
        header("Location: payment.php");
        exit;
    }
    
    // Get invoice details
    $invoiceQuery = "SELECT * FROM `association_invoice` WHERE `id` = '$invoice_id'";
    $invoiceResult = mysqli_query($conn, $invoiceQuery);
    
    if (!$invoiceResult || mysqli_num_rows($invoiceResult) == 0) {
        $_SESSION['payment_error'] = "Invalid invoice selected.";
        header("Location: payment.php");
        exit;
    }
    
    $invoice = mysqli_fetch_assoc($invoiceResult);
    
    // Get current year and semester
    $current_year = date('Y');
    $current_month = date('n');
    $current_semester = ($current_month >= 1 && $current_month <= 6) ? 2 : 1;
    
    // First, save payment as 'pending' in database
    $insertPayment = "INSERT INTO `association_payment` 
                     (`studentid`, `intake`, `program`, `year`, `semester`, 
                      `invoice_id`, `amount`, `payment_method`, `phone`, 
                      `status`, `payment_date`)
                     VALUES (
                         '$studentid',
                         '$intake',
                         '$program',
                         '$current_year',
                         '$current_semester',
                         '$invoice_id',
                         '$amount',
                         '$payment_method',
                         '$phone',
                         'pending',
                         NOW()
                     )";
    
    if (mysqli_query($conn, $insertPayment)) {
        $payment_id = mysqli_insert_id($conn);
        
        // Get auth token and create payment
        $authToken = getAuthToken();

        if (!$authToken) {
            $_SESSION['payment_error'] = "Payment authentication failed. Please try again.";
            header("Location: payment.php");
            exit;
        } else {
            // Prepare payment data according to Tumeny API format
            $paymentData = [
                'description' => $invoice['description'] . ' - Invoice #' . $invoice_id,
                'customerFirstName' => !empty($firstname) ? $firstname : 'Student',
                'customerLastName' => !empty($lastname) ? $lastname : $studentid,
                'email' => !empty($email) ? $email : 'student' . $studentid . '@example.com',
                'phoneNumber' => $phone,
                'amount' => (int)$amount
            ];

            $paymentResponse = createPayment($authToken, $paymentData);

            // Debug: Log the full response
            error_log("Full Payment API Response: " . json_encode($paymentResponse));

            if (isset($paymentResponse['payment']['id']) && isset($paymentResponse['payment']['paymentUrl'])) {
                $gateway_payment_id = $paymentResponse['payment']['id'];
                $payment_url = $paymentResponse['payment']['paymentUrl'];
                
                // Update with gateway reference
                $updateQuery = "UPDATE `association_payment` 
                               SET `gateway_reference` = '$gateway_payment_id', 
                                   `payment_url` = '" . mysqli_real_escape_string($conn, $payment_url) . "'
                               WHERE `id` = $payment_id";
                mysqli_query($conn, $updateQuery);
                
                // Redirect to payment URL
                header("Location: " . $payment_url);
                exit;
            } else {
                // Update status to failed
                $updateQuery = "UPDATE `association_payment` 
                               SET `status` = 'failed' 
                               WHERE `id` = $payment_id";
                mysqli_query($conn, $updateQuery);
                
                // Provide more detailed error message
                $errorMsg = "Payment creation failed. ";
                if (isset($paymentResponse['error'])) {
                    $errorMsg .= "Error: " . $paymentResponse['error'];
                } elseif (isset($paymentResponse['message'])) {
                    $errorMsg .= "Message: " . $paymentResponse['message'];
                } else {
                    $errorMsg .= "No valid response from payment gateway.";
                }
                
                $_SESSION['payment_error'] = $errorMsg;
                error_log("Payment Creation Failed Response: " . json_encode($paymentResponse));
            }
        }
    } else {
        $_SESSION['payment_error'] = "Failed to save payment record: " . mysqli_error($conn);
    }
}

// Handle success redirect
if (isset($_GET['success'])) {
    $_SESSION['payment_success'] = "Payment completed successfully!";
}

// Clear success message after displaying
if (isset($_SESSION['payment_success'])) {
    $success_msg = $_SESSION['payment_success'];
    unset($_SESSION['payment_success']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student Payment System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { 
            background-color: #f8f9fa; 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            margin: 0;
            padding: 0;
        }
        .content {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }
        .header-card {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .invoice-card, .payment-form-card, .history-card {
            background: white;
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.08);
        }
        .btn-payment {
            background: #54B68F;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-payment:hover {
            background: #469e7a;
            transform: translateY(-2px);
        }
        .payment-method {
            border: 2px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin: 10px 0;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .payment-method:hover {
            border-color: #3498db;
            background-color: #f8fafc;
        }
        .payment-method.selected {
            border-color: #54B68F;
            background-color: #e8f6f0;
        }
        .loading { 
            display: none; 
            text-align: center; 
            margin: 20px 0;
            padding: 20px;
        }
        .alert {
            margin-bottom: 20px;
        }
        @media (max-width: 768px) {
            .content {
                padding: 15px;
            }
            .header-card, .invoice-card, .payment-form-card, .history-card {
                padding: 15px;
            }
        }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
    <!-- Success Message -->
    <?php if (isset($success_msg)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            <strong>Success!</strong> <?php echo $success_msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <!-- Error Message -->
    <?php if (isset($_SESSION['payment_error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i>
            <strong>Error!</strong> <?php echo $_SESSION['payment_error']; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['payment_error']); ?>
    <?php endif; ?>

    <!-- Header -->
    <div class="header-card">
        <h2><i class="fas fa-credit-card me-2"></i>Student Payment Portal</h2>
        <p class="mb-0">
            <i class="fas fa-user me-1"></i>
            <?php echo htmlspecialchars($firstname . ' ' . $lastname); ?> (<?php echo htmlspecialchars($studentid); ?>)
        </p>
    </div>

    <!-- Outstanding Invoices -->
    <div class="invoice-card">
        <h4 class="mb-4"><i class="fas fa-file-invoice me-2"></i>Outstanding Invoices</h4>
        
        <?php if ($outstandingInvoices && mysqli_num_rows($outstandingInvoices) > 0): ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Invoice #</th>
                            <th>Description</th>
                            <th>Amount</th>
                            <th>Amount Paid</th>
                            <th>Balance</th>
                            <th>Due Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($invoice = mysqli_fetch_assoc($outstandingInvoices)): ?>
                            <tr>
                                <td><strong>#<?php echo htmlspecialchars($invoice['id']); ?></strong></td>
                                <td><?php echo htmlspecialchars($invoice['description']); ?></td>
                                <td class="fw-bold">ZMW <?php echo number_format($invoice['amount'], 2); ?></td>
                                <td class="text-success">ZMW <?php echo number_format($invoice['amount_paid'], 2); ?></td>
                                <td class="text-danger fw-bold">ZMW <?php echo number_format($invoice['balance'], 2); ?></td>
                                <td>
                                    <?php 
                                    if (!empty($invoice['due_date']) && $invoice['due_date'] != '0000-00-00') {
                                        echo date('M d, Y', strtotime($invoice['due_date']));
                                    } else {
                                        echo 'Not set';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <button class="btn btn-payment btn-sm" 
                                            onclick="selectInvoice(<?php echo $invoice['id']; ?>, <?php echo $invoice['balance']; ?>, '<?php echo htmlspecialchars($invoice['description'], ENT_QUOTES); ?>')">
                                        <i class="fas fa-money-bill-wave me-1"></i> Pay Now
                                    </button>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-5">
                <i class="fas fa-check-circle fa-4x text-success mb-3"></i>
                <h4>No Outstanding Invoices</h4>
                <p class="text-muted">All your invoices are paid up to date.</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Payment Form -->
    <div class="payment-form-card">
        <h4 class="mb-4"><i class="fas fa-credit-card me-2"></i>Make a Payment</h4>
        
        <form method="POST" id="paymentForm" onsubmit="return validatePaymentForm()">
            <input type="hidden" name="make_payment" value="1">
            <input type="hidden" name="invoice_id" id="invoice_id">
            
            <div class="row">
                <div class="col-md-6">
                    <!-- Invoice Details -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">Selected Invoice</label>
                        <div class="alert alert-info" id="selectedInvoice">
                            <i class="fas fa-info-circle me-2"></i>
                            Please select an invoice from the list above
                        </div>
                    </div>
                    
                    <!-- Amount -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">Amount to Pay (ZMW)</label>
                        <div class="input-group input-group-lg">
                            <span class="input-group-text bg-light">ZMW</span>
                            <input type="number" 
                                   class="form-control" 
                                   id="amount" 
                                   name="amount" 
                                   min="1" 
                                   step="1" 
                                   required
                                   placeholder="0.00">
                        </div>
                        <div class="form-text">Minimum payment: ZMW 1.00</div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <!-- Payment Method -->
                    <div class="mb-4">
                        <label class="form-label fw-bold mb-3">Select Payment Method</label>
                        
                        <div class="payment-method" onclick="selectPaymentMethod('mtn')">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="payment_method" value="mtn" id="mtn" required>
                                <label class="form-check-label" for="mtn">
                                    <i class="fas fa-mobile-alt me-2 text-warning fa-lg"></i>
                                    <strong>MTN Mobile Money</strong>
                                    <p class="text-muted mb-0 small">Pay using your MTN Mobile Money account</p>
                                </label>
                            </div>
                        </div>
                        
                        <div class="payment-method" onclick="selectPaymentMethod('airtel')">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="payment_method" value="airtel" id="airtel">
                                <label class="form-check-label" for="airtel">
                                    <i class="fas fa-sim-card me-2 text-danger fa-lg"></i>
                                    <strong>Airtel Money</strong>
                                    <p class="text-muted mb-0 small">Pay using your Airtel Money account</p>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Phone Number -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">Mobile Money Number</label>
                        <input type="tel" 
                               class="form-control" 
                               name="phone" 
                               id="phone" 
                               placeholder="e.g., 0971234567" 
                               required
                               pattern="[0-9]{10}"
                               value="<?php echo htmlspecialchars($phone); ?>">
                        <div class="form-text">Enter the mobile number linked to your mobile money account</div>
                    </div>
                </div>
            </div>
            
            <!-- Submit Button -->
            <div class="text-center mt-4">
                <button type="submit" class="btn btn-payment btn-lg px-5 py-3">
                    <i class="fas fa-lock me-2"></i>
                    Proceed to Payment
                </button>
            </div>
        </form>
        
        <!-- Loading Spinner -->
        <div id="loading" class="loading">
            <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                <span class="visually-hidden">Processing...</span>
            </div>
            <p class="mt-3 fw-bold">Processing your payment. Please wait...</p>
        </div>
    </div>

    <!-- Payment History -->
    <div class="history-card">
        <h4 class="mb-4"><i class="fas fa-history me-2"></i>Payment History</h4>
        
        <?php if ($paymentHistory && mysqli_num_rows($paymentHistory) > 0): ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Invoice #</th>
                            <th>Amount</th>
                            <th>Method</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($payment = mysqli_fetch_assoc($paymentHistory)): ?>
                            <tr>
                                <td>
                                    <?php 
                                    if (!empty($payment['payment_date'])) {
                                        echo date('M d, Y', strtotime($payment['payment_date']));
                                    } else {
                                        echo 'N/A';
                                    }
                                    ?>
                                </td>
                                <td>#<?php echo htmlspecialchars($payment['invoice_id']); ?></td>
                                <td class="fw-bold">ZMW <?php echo number_format($payment['amount'], 2); ?></td>
                                <td>
                                    <span class="badge bg-info text-uppercase">
                                        <?php echo htmlspecialchars($payment['payment_method']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php 
                                    $status_class = 'secondary';
                                    if ($payment['status'] == 'paid') $status_class = 'success';
                                    if ($payment['status'] == 'pending') $status_class = 'warning';
                                    if ($payment['status'] == 'failed') $status_class = 'danger';
                                    ?>
                                    <span class="badge bg-<?php echo $status_class; ?> text-uppercase">
                                        <?php echo htmlspecialchars($payment['status']); ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-4">
                <i class="fas fa-receipt fa-4x text-muted mb-3"></i>
                <h5>No Payment History</h5>
                <p class="text-muted">You haven't made any payments yet.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function selectInvoice(invoiceId, amount, description) {
        document.getElementById('invoice_id').value = invoiceId;
        document.getElementById('amount').value = amount;
        
        const invoiceDiv = document.getElementById('selectedInvoice');
        invoiceDiv.innerHTML = `
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <i class="fas fa-file-invoice me-2"></i>
                    <strong>Invoice #${invoiceId}</strong>: ${description}
                </div>
                <div class="fw-bold">ZMW ${parseFloat(amount).toFixed(2)}</div>
            </div>
        `;
        invoiceDiv.className = 'alert alert-success';
        
        // Scroll to payment form
        document.querySelector('.payment-form-card').scrollIntoView({ 
            behavior: 'smooth',
            block: 'start'
        });
    }
    
    function selectPaymentMethod(method) {
        // Update radio button
        document.getElementById(method).checked = true;
        
        // Update visual selection
        document.querySelectorAll('.payment-method').forEach(item => {
            item.classList.remove('selected');
        });
        document.getElementById(method).closest('.payment-method').classList.add('selected');
        
        // Update phone placeholder based on method
        const phoneInput = document.getElementById('phone');
        switch(method) {
            case 'mtn':
                phoneInput.placeholder = 'e.g., 0961234567';
                break;
            case 'airtel':
                phoneInput.placeholder = 'e.g., 0971234567';
                break;
        }
    }
    
    function validatePaymentForm() {
        const invoiceId = document.getElementById('invoice_id').value;
        const amount = parseFloat(document.getElementById('amount').value);
        const paymentMethod = document.querySelector('input[name="payment_method"]:checked');
        const phone = document.getElementById('phone').value.trim();
        
        // Clear previous errors
        document.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
        document.querySelectorAll('.invalid-feedback').forEach(el => el.remove());
        
        let isValid = true;
        
        if (!invoiceId) {
            showError('selectedInvoice', 'Please select an invoice to pay');
            isValid = false;
        }
        
        if (!paymentMethod) {
            showError(document.querySelector('.payment-method').parentElement, 'Please select a payment method');
            isValid = false;
        }
        
        if (!phone || !/^(0)?(77|76|96|97|95|09)[0-9]{7}$/.test(phone)) {
            showError('phone', 'Please enter a valid Zambian phone number (e.g., 0961234567, 0971234567)');
            isValid = false;
        }
        
        if (isNaN(amount) || amount < 1) {
            showError('amount', 'Minimum payment amount is ZMW 1.00');
            isValid = false;
        }
        
        if (isValid) {
            // Show loading spinner
            document.getElementById('loading').style.display = 'block';
            document.querySelector('button[type="submit"]').disabled = true;
            document.querySelector('button[type="submit"]').innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
        }
        
        return isValid;
    }
    
    function showError(elementId, message) {
        let element = typeof elementId === 'string' ? document.getElementById(elementId) : elementId;
        if (!element) return;
        
        element.classList.add('is-invalid');
        
        const errorDiv = document.createElement('div');
        errorDiv.className = 'invalid-feedback d-block';
        errorDiv.textContent = message;
        
        element.parentNode.appendChild(errorDiv);
    }
    
    // Initialize payment method selection
    document.addEventListener('DOMContentLoaded', function() {
        const paymentMethods = document.querySelectorAll('.payment-method');
        paymentMethods.forEach(method => {
            method.addEventListener('click', function() {
                const radio = this.querySelector('input[type="radio"]');
                if (radio) {
                    radio.checked = true;
                    selectPaymentMethod(radio.value);
                }
            });
        });
        
        // Auto-select first payment method
        if (paymentMethods.length > 0) {
            const firstRadio = paymentMethods[0].querySelector('input[type="radio"]');
            if (firstRadio) {
                firstRadio.checked = true;
                selectPaymentMethod(firstRadio.value);
            }
        }
    });
</script>
</body>
</html>