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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Handle payment processing
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['process_payment'])) {
    $invoice_id = $_POST['invoice_id'];
    $amount = $_POST['amount'];
    $payment_method = $_POST['payment_method'];
    $reference_number = $_POST['reference_number'];
    $notes = $_POST['notes'];
    
    // Generate payment number
    $payment_number = 'PAY' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    // Get invoice currency
    $invoice_currency_sql = "SELECT s.currency FROM invoices i 
                            LEFT JOIN invoice_items ii ON i.invoice_id = ii.invoice_id 
                            LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id 
                            WHERE i.invoice_id = ? 
                            LIMIT 1";
    $stmt_currency = $conn->prepare($invoice_currency_sql);
    $stmt_currency->bind_param("i", $invoice_id);
    $stmt_currency->execute();
    $currency_result = $stmt_currency->get_result()->fetch_assoc();
    $currency = $currency_result['currency'] ?? 'KES';
    
    // Insert payment
    $sql_payment = "INSERT INTO payments (payment_number, invoice_id, customer_id, payment_date, payment_method, amount, reference_number, notes, created_by) 
                    SELECT ?, ?, customer_id, CURDATE(), ?, ?, ?, ?, ?
                    FROM invoices WHERE invoice_id = ?";
    $stmt_payment = $conn->prepare($sql_payment);
    $stmt_payment->bind_param("sisdsisi", $payment_number, $invoice_id, $payment_method, $amount, $reference_number, $notes, $user_id, $invoice_id);
    
    if ($stmt_payment->execute()) {
        // Update invoice paid amount
        $sql_update = "UPDATE invoices SET 
                       paid_amount = paid_amount + ?, 
                       balance_amount = total_amount - (paid_amount + ?), 
                       status = CASE 
                         WHEN (paid_amount + ?) >= total_amount THEN 'PAID' 
                         WHEN (paid_amount + ?) > 0 THEN 'PARTIAL' 
                         ELSE status 
                       END 
                       WHERE invoice_id = ?";
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("ddddi", $amount, $amount, $amount, $amount, $invoice_id);
        $stmt_update->execute();
        
        $success_message = "Payment of " . number_format($amount, 2) . " " . $currency . " processed successfully!";
    } else {
        $error_message = "Error processing payment: " . $conn->error;
    }
}

// Filter parameters
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-t');
$payment_method = $_GET['payment_method'] ?? '';
$payment_status = $_GET['payment_status'] ?? '';
$currency_filter = $_GET['currency_filter'] ?? '';

// Build where conditions
$where_conditions = ["p.payment_date BETWEEN ? AND ?"];
$params = [$date_from, $date_to];
$param_types = 'ss';

if (!empty($payment_method)) {
    $where_conditions[] = "p.payment_method = ?";
    $params[] = $payment_method;
    $param_types .= 's';
}

if (!empty($payment_status)) {
    $where_conditions[] = "p.status = ?";
    $params[] = $payment_status;
    $param_types .= 's';
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

// Get all payments with invoice and customer details
$sql_payments = "SELECT p.*, 
                        i.invoice_number,
                        s.currency,
                        c.first_name, c.last_name, c.company_name, c.customer_type, c.customer_code,
                        u.full_name as processed_by_name
                 FROM payments p
                 LEFT JOIN invoices i ON p.invoice_id = i.invoice_id
                 LEFT JOIN invoice_items ii ON i.invoice_id = ii.invoice_id
                 LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id
                 LEFT JOIN customers c ON p.customer_id = c.customer_id
                 LEFT JOIN users u ON p.created_by = u.user_id
                 $where_clause
                 GROUP BY p.payment_id
                 ORDER BY p.payment_date DESC, p.created_at DESC";

$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param($param_types, ...$params);
$stmt_payments->execute();
$payments = $stmt_payments->get_result();

// Get outstanding invoices for payment processing
$sql_outstanding = "SELECT i.*, 
                           c.first_name, c.last_name, c.company_name, c.customer_type,
                           GROUP_CONCAT(DISTINCT s.currency) as currencies
                    FROM invoices i
                    LEFT JOIN customers c ON i.customer_id = c.customer_id
                    LEFT JOIN invoice_items ii ON i.invoice_id = ii.invoice_id
                    LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id
                    WHERE i.status IN ('SENT', 'PARTIAL', 'OVERDUE') AND i.balance_amount > 0
                    GROUP BY i.invoice_id
                    ORDER BY i.due_date ASC
                    LIMIT 20";
$outstanding_invoices = $conn->query($sql_outstanding);

// Get payment summary statistics
$sql_stats = "SELECT 
                COUNT(*) as total_payments,
                SUM(p.amount) as total_amount,
                COUNT(CASE WHEN p.status = 'CONFIRMED' THEN 1 END) as confirmed_payments,
                COUNT(CASE WHEN p.status = 'PENDING' THEN 1 END) as pending_payments,
                COUNT(CASE WHEN DATE(p.payment_date) = CURDATE() THEN 1 END) as today_payments,
                SUM(CASE WHEN DATE(p.payment_date) = CURDATE() THEN p.amount ELSE 0 END) as today_amount
              FROM payments p
              LEFT JOIN invoices i ON p.invoice_id = i.invoice_id
              LEFT JOIN invoice_items ii ON i.invoice_id = ii.invoice_id
              LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id
              $where_clause";

$stmt_stats = $conn->prepare($sql_stats);
$stmt_stats->bind_param($param_types, ...$params);
$stmt_stats->execute();
$payment_stats = $stmt_stats->get_result()->fetch_assoc();

// Get payment methods statistics
$sql_methods = "SELECT 
                  p.payment_method,
                  COUNT(*) as method_count,
                  SUM(p.amount) as method_total,
                  AVG(p.amount) as method_average
                FROM payments p
                LEFT JOIN invoices i ON p.invoice_id = i.invoice_id
                LEFT JOIN invoice_items ii ON i.invoice_id = ii.invoice_id
                LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id
                $where_clause
                GROUP BY p.payment_method
                ORDER BY method_total DESC";

$stmt_methods = $conn->prepare($sql_methods);
$stmt_methods->bind_param($param_types, ...$params);
$stmt_methods->execute();
$payment_methods = $stmt_methods->get_result();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Payment Processing - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css">
    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .page-content {
            padding: 1.5rem;
        }
        
        .card {
            border: none;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            border-radius: 10px;
        }
        
        .card-header {
            background: linear-gradient(45deg, #f8f9fa, #e9ecef);
            border-bottom: 1px solid #dee2e6;
            border-radius: 10px 10px 0 0;
        }
        
        .filter-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .method-card {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            transition: transform 0.2s;
        }
        
        .method-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            border-top: none;
        }
        
        .badge {
            font-size: 0.75rem;
            padding: 0.5rem 0.75rem;
            border-radius: 6px;
        }
        
        .status-confirmed { background-color: #28a745; }
        .status-pending { background-color: #ffc107; color: #000; }
        .status-failed { background-color: #dc3545; }
        .status-cancelled { background-color: #6c757d; }
        
        .amount-cell {
            font-weight: 600;
            font-family: 'Courier New', monospace;
        }
        
        .currency-flag {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            background: #007bff;
            color: white;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
            margin-right: 0.5rem;
        }
        
        .quick-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        
        .payment-form {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 2rem;
        }
        
        @media print {
            .no-print { display: none !important; }
            .card { box-shadow: none; border: 1px solid #dee2e6; }
        }
    </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">Payment Processing</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Payment Processing</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if (isset($success_message)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="ri-check-line align-middle me-2"></i>
                        <?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

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

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="text-white-50 mb-1">Total Payments</h6>
                                        <h4 class="text-white mb-0"><?php echo number_format($payment_stats['total_payments']); ?></h4>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-white bg-opacity-25 rounded">
                                            <i class="ri-money-dollar-circle-line fs-4"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="text-white-50 mb-1">Total Amount</h6>
                                        <h4 class="text-white mb-0"><?php echo number_format($payment_stats['total_amount'], 2); ?></h4>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-white bg-opacity-25 rounded">
                                            <i class="ri-coins-line fs-4"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="text-white-50 mb-1">Today's Payments</h6>
                                        <h4 class="text-white mb-0"><?php echo number_format($payment_stats['today_payments']); ?></h4>
                                        <small class="text-white-50"><?php echo number_format($payment_stats['today_amount'], 2); ?></small>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-white bg-opacity-25 rounded">
                                            <i class="ri-calendar-check-line fs-4"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="text-white-50 mb-1">Pending Payments</h6>
                                        <h4 class="text-white mb-0"><?php echo number_format($payment_stats['pending_payments']); ?></h4>
                                        <small class="text-white-50">Need attention</small>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-white bg-opacity-25 rounded">
                                            <i class="ri-time-line fs-4"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card filter-card no-print">
                                <div class="card-header">
                                    <h4 class="card-title mb-0 text-white">
                                        <i class="ri-filter-line me-2"></i>Filter Payments
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label text-white">Date From</label>
                                            <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label text-white">Date To</label>
                                            <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label text-white">Payment Method</label>
                                            <select class="form-control" name="payment_method">
                                                <option value="">All Methods</option>
                                                <option value="CASH" <?php echo $payment_method === 'CASH' ? 'selected' : ''; ?>>Cash</option>
                                                <option value="BANK_TRANSFER" <?php echo $payment_method === 'BANK_TRANSFER' ? 'selected' : ''; ?>>Bank Transfer</option>
                                                <option value="CARD" <?php echo $payment_method === 'CARD' ? 'selected' : ''; ?>>Credit/Debit Card</option>
                                                <option value="MOBILE_MONEY" <?php echo $payment_method === 'MOBILE_MONEY' ? 'selected' : ''; ?>>Mobile Money</option>
                                                <option value="CHEQUE" <?php echo $payment_method === 'CHEQUE' ? 'selected' : ''; ?>>Cheque</option>
                                                <option value="OTHER" <?php echo $payment_method === 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label text-white">Status</label>
                                            <select class="form-control" name="payment_status">
                                                <option value="">All Status</option>
                                                <option value="CONFIRMED" <?php echo $payment_status === 'CONFIRMED' ? 'selected' : ''; ?>>Confirmed</option>
                                                <option value="PENDING" <?php echo $payment_status === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="FAILED" <?php echo $payment_status === 'FAILED' ? 'selected' : ''; ?>>Failed</option>
                                                <option value="CANCELLED" <?php echo $payment_status === 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                            </select>
                                        </div>
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-light">
                                                <i class="ri-search-line me-1"></i> Filter
                                            </button>
                                            <a href="payments.php" class="btn btn-outline-light">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </a>
                                            <button type="button" class="btn btn-outline-light" onclick="exportData()">
                                                <i class="ri-download-line me-1"></i> Export
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Payment Processing -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-flashlight-line me-2"></i>Quick Payment Processing
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Invoice #</th>
                                                    <th>Customer</th>
                                                    <th>Currency</th>
                                                    <th>Due Date</th>
                                                    <th>Balance Due</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($invoice = $outstanding_invoices->fetch_assoc()): ?>
                                                <tr>
                                                    <td><strong><?php echo $invoice['invoice_number']; ?></strong></td>
                                                    <td>
                                                        <?php 
                                                        if ($invoice['customer_type'] === 'CORPORATE') {
                                                            echo $invoice['company_name'];
                                                        } else {
                                                            echo $invoice['first_name'] . ' ' . $invoice['last_name'];
                                                        }
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $currencies = explode(',', $invoice['currencies']);
                                                        foreach ($currencies as $curr):
                                                        ?>
                                                        <span class="currency-flag"><?php echo $curr; ?></span>
                                                        <?php endforeach; ?>
                                                    </td>
                                                    <td><?php echo date('M j, Y', strtotime($invoice['due_date'])); ?></td>
                                                    <td class="amount-cell text-danger">
                                                        <strong><?php echo number_format($invoice['balance_amount'], 2); ?></strong>
                                                    </td>
                                                    <td>
                                                        <button type="button" class="btn btn-primary btn-sm" onclick="processPayment(<?php echo $invoice['invoice_id']; ?>, '<?php echo $invoice['invoice_number']; ?>', <?php echo $invoice['balance_amount']; ?>, '<?php echo addslashes($invoice['customer_type'] === 'CORPORATE' ? $invoice['company_name'] : $invoice['first_name'] . ' ' . $invoice['last_name']); ?>', '<?php echo $currencies[0]; ?>')">
                                                            <i class="ri-money-dollar-circle-line"></i> Pay
                                                        </button>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Payment Methods Statistics -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-pie-chart-line me-2"></i>Payment Methods Analysis
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php while ($method = $payment_methods->fetch_assoc()): ?>
                                        <div class="col-xl-4 col-md-6">
                                            <div class="method-card text-center">
                                                <i class="ri-money-dollar-circle-line fs-2 text-primary mb-3"></i>
                                                <h6 class="mb-1"><?php echo str_replace('_', ' ', $method['payment_method']); ?></h6>
                                                <p class="text-muted mb-2"><?php echo $method['method_count']; ?> payments</p>
                                                <h5 class="mb-1"><?php echo number_format($method['method_total'], 2); ?></h5>
                                                <small class="text-muted">Avg: <?php echo number_format($method['method_average'], 2); ?></small>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Payment History Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-history-line me-2"></i>Payment History
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <table id="paymentsTable" class="table table-striped table-hover dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Payment #</th>
                                                <th>Date</th>
                                                <th>Invoice</th>
                                                <th>Customer</th>
                                                <th>Currency</th>
                                                <th>Method</th>
                                                <th>Amount</th>
                                                <th>Reference</th>
                                                <th>Status</th>
                                                <th>Processed By</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($payment = $payments->fetch_assoc()): ?>
                                            <tr>
                                                <td><strong><?php echo $payment['payment_number']; ?></strong></td>
                                                <td><?php echo date('M j, Y H:i', strtotime($payment['payment_date'])); ?></td>
                                                <td>
                                                    <?php if ($payment['invoice_number']): ?>
                                                        <a href="view_invoice.php?id=<?php echo $payment['invoice_id']; ?>" class="text-primary">
                                                            <?php echo $payment['invoice_number']; ?>
                                                        </a>
                                                    <?php else: ?>
                                                        <span class="text-muted">N/A</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php 
                                                    if ($payment['customer_type'] === 'CORPORATE') {
                                                        echo '<strong>' . $payment['company_name'] . '</strong>';
                                                    } else {
                                                        echo '<strong>' . $payment['first_name'] . ' ' . $payment['last_name'] . '</strong>';
                                                    }
                                                    ?>
                                                    <br><small class="text-muted"><?php echo $payment['customer_code']; ?></small>
                                                </td>
                                                <td>
                                                    <span class="currency-flag"><?php echo $payment['currency'] ?? 'KES'; ?></span>
                                                </td>
                                                <td><?php echo str_replace('_', ' ', $payment['payment_method']); ?></td>
                                                <td class="amount-cell">
                                                    <strong><?php echo number_format($payment['amount'], 2); ?></strong>
                                                </td>
                                                <td>
                                                    <?php echo $payment['reference_number'] ?: '<span class="text-muted">-</span>'; ?>
                                                </td>
                                                <td>
                                                    <span class="badge status-<?php echo strtolower($payment['status']); ?>">
                                                        <?php echo $payment['status']; ?>
                                                    </span>
                                                </td>
                                                <td><?php echo $payment['processed_by_name']; ?></td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </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 modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Process Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="invoice_id" id="invoice_id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Invoice Number</label>
                                    <input type="text" class="form-control" id="invoice_number" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Customer</label>
                                    <input type="text" class="form-control" id="customer_name" readonly>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Currency</label>
                                    <input type="text" class="form-control" id="payment_currency" readonly>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Outstanding Balance</label>
                                    <input type="text" class="form-control" id="balance_amount" readonly>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Payment Amount *</label>
                                    <input type="number" class="form-control" name="amount" id="payment_amount" step="0.01" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Payment Method *</label>
                                    <select class="form-control" name="payment_method" required>
                                        <option value="">Select Method</option>
                                        <option value="CASH">Cash</option>
                                        <option value="BANK_TRANSFER">Bank Transfer</option>
                                        <option value="CARD">Credit/Debit Card</option>
                                        <option value="MOBILE_MONEY">Mobile Money</option>
                                        <option value="CHEQUE">Cheque</option>
                                        <option value="OTHER">Other</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Reference Number</label>
                                    <input type="text" class="form-control" name="reference_number" placeholder="Transaction reference">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Payment notes or remarks"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="process_payment" class="btn btn-primary">
                            <i class="ri-money-dollar-circle-line"></i> Process Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- DataTables JS -->
    <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.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTables
            $('#paymentsTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[1, 'desc']], // Sort by date descending
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'excel',
                        text: '<i class="ri-file-excel-line"></i> Excel',
                        className: 'btn btn-success btn-sm'
                    },
                    {
                        extend: 'csv',
                        text: '<i class="ri-file-text-line"></i> CSV',
                        className: 'btn btn-info btn-sm'
                    },
                    {
                        extend: 'print',
                        text: '<i class="ri-printer-line"></i> Print',
                        className: 'btn btn-secondary btn-sm'
                    }
                ],
                columnDefs: [
                    { targets: [6], className: 'text-end' },
                    { targets: [8], className: 'text-center' }
                ]
            });
        });
        
        function processPayment(invoiceId, invoiceNumber, balanceAmount, customerName, currency) {
            $('#invoice_id').val(invoiceId);
            $('#invoice_number').val(invoiceNumber);
            $('#customer_name').val(customerName);
            $('#payment_currency').val(currency);
            $('#balance_amount').val(balanceAmount.toFixed(2) + ' ' + currency);
            $('#payment_amount').val(balanceAmount.toFixed(2));
            $('#payment_amount').attr('max', balanceAmount);
            $('#paymentModal').modal('show');
        }
        
        // Validate payment amount
        $('#payment_amount').on('input', function() {
            const amount = parseFloat($(this).val());
            const maxAmount = parseFloat($(this).attr('max'));
            
            if (amount > maxAmount) {
                $(this).addClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
                $(this).after('<div class="invalid-feedback">Amount cannot exceed outstanding balance</div>');
            } else {
                $(this).removeClass('is-invalid');
                $(this).siblings('.invalid-feedback').remove();
            }
        });
        
        function exportData() {
            Swal.fire({
                title: 'Export Data',
                text: 'Choose export format:',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Excel',
                cancelButtonText: 'CSV',
                showDenyButton: true,
                denyButtonText: 'PDF'
            }).then((result) => {
                if (result.isConfirmed) {
                    $('#paymentsTable').DataTable().button('.buttons-excel').trigger();
                } else if (result.isDenied) {
                    Swal.fire('PDF export functionality can be implemented here', '', 'info');
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    $('#paymentsTable').DataTable().button('.buttons-csv').trigger();
                }
            });
        }
        
        // Show success message with SweetAlert
        <?php if (isset($success_message)): ?>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $success_message; ?>',
            timer: 3000,
            showConfirmButton: false
        });
        <?php endif; ?>
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>