<?php
/**
 * ADMIN PAYMENTS MANAGEMENT PAGE
 * File: admin/payments.php
 * Payment gateway analytics, transaction management, and refunds
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

$page_title = "Payments Management";
$active_menu = "payments";

// Initialize models
$db = Database::getInstance();

// Get filter parameters
$gateway = $_GET['gateway'] ?? 'all';
$status = $_GET['status'] ?? 'all';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;

// Build WHERE clause
$where_conditions = [];
$params = [];

if ($gateway !== 'all') {
    $where_conditions[] = "p.payment_gateway = ?";
    $params[] = $gateway;
}

if ($status !== 'all') {
    $where_conditions[] = "p.status = ?";
    $params[] = $status;
}

if (!empty($search)) {
    $where_conditions[] = "(p.transaction_reference LIKE ? OR o.order_number LIKE ? OR p.gateway_reference LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(p.created_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(p.created_at) <= ?";
    $params[] = $date_to;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count
$count_sql = "SELECT COUNT(*) as total 
              FROM payments p
              LEFT JOIN orders o ON p.order_id = o.id
              $where_clause";
$count_result = $db->fetch($count_sql, $params);
$total_payments = ($count_result && isset($count_result['total'])) ? intval($count_result['total']) : 0;
$total_pages = ceil($total_payments / $per_page);
$offset = ($page - 1) * $per_page;

// Get payments with order and user details
$payments_sql = "SELECT p.*, o.order_number, o.total_amount as order_amount,
                 v.business_name as vendor_name,
                 CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                 u.email as customer_email
                 FROM payments p
                 LEFT JOIN orders o ON p.order_id = o.id
                 LEFT JOIN vendors v ON o.vendor_id = v.id
                 LEFT JOIN customers c ON o.customer_id = c.id
                 LEFT JOIN users u ON c.user_id = u.id
                 $where_clause
                 ORDER BY p.created_at DESC
                 LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;
$payments = $db->fetchAll($payments_sql, $params);

// Get payment statistics
$stats_sql = "SELECT 
              COUNT(*) as total_payments,
              COALESCE(SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END), 0) as total_completed,
              COALESCE(SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END), 0) as total_pending,
              COALESCE(SUM(CASE WHEN status = 'failed' THEN amount ELSE 0 END), 0) as total_failed,
              COALESCE(SUM(CASE WHEN status = 'refunded' THEN refund_amount ELSE 0 END), 0) as total_refunded,
              COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_count,
              COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
              COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_count
              FROM payments p
              LEFT JOIN orders o ON p.order_id = o.id
              $where_clause";
$stats = $db->fetch($stats_sql, array_slice($params, 0, -2)); // Remove LIMIT and OFFSET

// Ensure stats has default values
if (!$stats || !is_array($stats)) {
    $stats = [];
}

$stats = array_merge([
    'total_payments' => 0,
    'total_completed' => 0.00,
    'total_pending' => 0.00,
    'total_failed' => 0.00,
    'total_refunded' => 0.00,
    'completed_count' => 0,
    'pending_count' => 0,
    'failed_count' => 0
], $stats);

// Get payment gateway breakdown
$gateway_sql = "SELECT 
                payment_gateway,
                COUNT(*) as total_transactions,
                COALESCE(SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END), 0) as total_amount,
                COALESCE(SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END), 0) as successful_transactions,
                ROUND(COALESCE(SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 0), 2) as success_rate
                FROM payments p
                WHERE DATE(p.created_at) BETWEEN ? AND ?
                GROUP BY payment_gateway
                ORDER BY total_amount DESC";
$gateway_stats = $db->fetchAll($gateway_sql, [$date_from ?: date('Y-m-01'), $date_to ?: date('Y-m-d')]);

// Get daily payment chart data (last 30 days)
$chart_sql = "SELECT 
              DATE(p.created_at) as date,
              COUNT(*) as transactions,
              COALESCE(SUM(CASE WHEN p.status = 'completed' THEN p.amount ELSE 0 END), 0) as amount,
              COALESCE(SUM(CASE WHEN p.status = 'completed' THEN 1 ELSE 0 END), 0) as successful
              FROM payments p
              WHERE DATE(p.created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
              GROUP BY DATE(p.created_at)
              ORDER BY date ASC";
$chart_data = $db->fetchAll($chart_sql);

// Get recent failed payments that need attention
$failed_payments_sql = "SELECT p.*, o.order_number, v.business_name as vendor_name
                       FROM payments p
                       LEFT JOIN orders o ON p.order_id = o.id
                       LEFT JOIN vendors v ON o.vendor_id = v.id
                       WHERE p.status = 'failed'
                       ORDER BY p.created_at DESC
                       LIMIT 10";
$failed_payments = $db->fetchAll($failed_payments_sql);

// Handle payment actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $payment_id = (int)$_POST['payment_id'];
    $action = $_POST['action'];
    
    switch ($action) {
        case 'refund':
            $refund_amount = (float)$_POST['refund_amount'];
            $refund_reason = trim($_POST['refund_reason']);
            
            if ($refund_amount > 0 && !empty($refund_reason)) {
                try {
                    // Update payment status
                    $update_sql = "UPDATE payments 
                                  SET status = 'refunded', 
                                      refund_amount = ?, 
                                      refund_reason = ?, 
                                      refunded_at = NOW()
                                  WHERE id = ?";
                    $db->execute($update_sql, [$refund_amount, $refund_reason, $payment_id]);
                    
                    flash('message', ['type' => 'success', 'message' => 'Refund processed successfully']);
                } catch (Exception $e) {
                    flash('message', ['type' => 'danger', 'message' => 'Error processing refund: ' . $e->getMessage()]);
                }
            } else {
                flash('message', ['type' => 'danger', 'message' => 'Invalid refund amount or reason']);
            }
            break;
            
        case 'retry':
            try {
                $update_sql = "UPDATE payments SET status = 'pending' WHERE id = ?";
                $db->execute($update_sql, [$payment_id]);
                flash('message', ['type' => 'success', 'message' => 'Payment marked for retry']);
            } catch (Exception $e) {
                flash('message', ['type' => 'danger', 'message' => 'Error updating payment: ' . $e->getMessage()]);
            }
            break;
    }
    
    header('Location: payments.php');
    exit;
}

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

    <!-- Page Header -->
    <div style="padding: 30px; background: white; border-bottom: 1px solid #eee;">
        <h1 style="font-size: 28px; font-weight: 700; color: var(--dark); margin-bottom: 5px;">
            <i class="fas fa-credit-card"></i> Payments Management
        </h1>
        <div style="display: flex; gap: 8px; font-size: 14px; color: #666;">
            <a href="index.php" style="color: var(--primary); text-decoration: none;">Home</a>
            <span>/</span>
            <span>Payments</span>
        </div>
    </div>
    
    <!-- Content -->
    <div style="padding: 30px;">
        
        <!-- Flash Messages -->
        <?php if ($flash_message): ?>
            <div class="alert alert-<?= $flash_message['type'] ?>">
                <?= Security::escapeOutput($flash_message['message']) ?>
            </div>
        <?php endif; ?>
        
        <!-- Payment Statistics -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px;">
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="background: var(--primary); color: white; width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px;">
                        <i class="fas fa-credit-card"></i>
                    </div>
                    <div>
                        <div style="font-size: 24px; font-weight: 700; color: var(--dark);"><?= number_format($stats['total_payments'] ?? 0) ?></div>
                        <div style="font-size: 14px; color: #666;">Total Payments</div>
                    </div>
                </div>
            </div>
            
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="background: var(--success); color: white; width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px;">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div>
                        <div style="font-size: 24px; font-weight: 700; color: var(--dark);"><?= format_money($stats['total_completed'] ?? 0) ?></div>
                        <div style="font-size: 14px; color: #666;">Completed Amount</div>
                    </div>
                </div>
            </div>
            
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="background: var(--warning); color: white; width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px;">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div>
                        <div style="font-size: 24px; font-weight: 700; color: var(--dark);"><?= format_money($stats['total_pending'] ?? 0) ?></div>
                        <div style="font-size: 14px; color: #666;">Pending Amount</div>
                    </div>
                </div>
            </div>
            
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <div style="background: var(--info); color: white; width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px;">
                        <i class="fas fa-undo"></i>
                    </div>
                    <div>
                        <div style="font-size: 24px; font-weight: 700; color: var(--dark);"><?= format_money($stats['total_refunded'] ?? 0) ?></div>
                        <div style="font-size: 14px; color: #666;">Total Refunded</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Filters -->
        <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px;">
            <form method="GET">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end;">
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Payment Gateway</label>
                        <select name="gateway" class="form-control">
                            <option value="all" <?= $gateway === 'all' ? 'selected' : '' ?>>All Gateways</option>
                            <option value="paystack" <?= $gateway === 'paystack' ? 'selected' : '' ?>>Paystack</option>
                            <option value="flutterwave" <?= $gateway === 'flutterwave' ? 'selected' : '' ?>>Flutterwave</option>
                            <option value="wallet" <?= $gateway === 'wallet' ? 'selected' : '' ?>>Wallet</option>
                        </select>
                    </div>
                    
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Status</label>
                        <select name="status" class="form-control">
                            <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All Status</option>
                            <option value="completed" <?= $status === 'completed' ? 'selected' : '' ?>>Completed</option>
                            <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="failed" <?= $status === 'failed' ? 'selected' : '' ?>>Failed</option>
                            <option value="refunded" <?= $status === 'refunded' ? 'selected' : '' ?>>Refunded</option>
                        </select>
                    </div>
                    
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Date From</label>
                        <input type="date" name="date_from" class="form-control" value="<?= $date_from ?>">
                    </div>
                    
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Date To</label>
                        <input type="date" name="date_to" class="form-control" value="<?= $date_to ?>">
                    </div>
                    
                    <div>
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Search</label>
                        <input type="text" name="search" class="form-control" 
                               placeholder="Transaction ref, order #..." 
                               value="<?= Security::escapeOutput($search) ?>">
                    </div>
                    
                    <div>
                        <button type="submit" class="btn btn-primary" style="width: 100%;">
                            <i class="fas fa-search"></i> Filter
                        </button>
                    </div>
                </div>
            </form>
        </div>
        
        <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 30px; margin-bottom: 30px;">
            <!-- Payment Gateway Analytics -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                    <i class="fas fa-chart-pie"></i> Gateway Performance
                </h3>
                
                <?php if (empty($gateway_stats)): ?>
                    <p style="color: #999; text-align: center; padding: 20px;">No gateway data available</p>
                <?php else: ?>
                    <div style="overflow-x: auto;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <thead>
                                <tr style="background: #f8f9fa;">
                                    <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Gateway</th>
                                    <th style="padding: 12px 15px; text-align: center; font-size: 13px; font-weight: 600; color: #666;">Transactions</th>
                                    <th style="padding: 12px 15px; text-align: center; font-size: 13px; font-weight: 600; color: #666;">Success Rate</th>
                                    <th style="padding: 12px 15px; text-align: right; font-size: 13px; font-weight: 600; color: #666;">Total Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($gateway_stats as $gateway_data): ?>
                                    <tr style="border-bottom: 1px solid #f0f0f0;">
                                        <td style="padding: 15px;">
                                            <strong><?= ucfirst($gateway_data['payment_gateway']) ?></strong>
                                        </td>
                                        <td style="padding: 15px; text-align: center;">
                                            <?= number_format($gateway_data['total_transactions']) ?>
                                        </td>
                                        <td style="padding: 15px; text-align: center;">
                                            <span style="background: <?= $gateway_data['success_rate'] >= 90 ? 'var(--success)' : ($gateway_data['success_rate'] >= 70 ? 'var(--warning)' : 'var(--danger)') ?>; 
                                                         color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 600;">
                                                <?= $gateway_data['success_rate'] ?>%
                                            </span>
                                        </td>
                                        <td style="padding: 15px; text-align: right; font-weight: 600;">
                                            <?= format_money($gateway_data['total_amount']) ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Failed Payments Alert -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                    <i class="fas fa-exclamation-triangle" style="color: var(--warning);"></i> Failed Payments
                </h3>
                
                <?php if (empty($failed_payments)): ?>
                    <p style="color: var(--success); text-align: center; padding: 20px;">
                        <i class="fas fa-check-circle" style="font-size: 24px;"></i><br>
                        No failed payments
                    </p>
                <?php else: ?>
                    <div style="max-height: 300px; overflow-y: auto;">
                        <?php foreach ($failed_payments as $failed): ?>
                            <div style="border-bottom: 1px solid #f0f0f0; padding: 15px 0;">
                                <div style="font-weight: 600; margin-bottom: 5px;">
                                    <?= Security::escapeOutput($failed['order_number']) ?>
                                </div>
                                <div style="font-size: 12px; color: #666; margin-bottom: 5px;">
                                    <?= Security::escapeOutput($failed['vendor_name']) ?>
                                </div>
                                <div style="font-size: 14px; font-weight: 600; color: var(--danger);">
                                    <?= format_money($failed['amount']) ?>
                                </div>
                                <div style="margin-top: 10px;">
                                    <button onclick="retryPayment(<?= $failed['id'] ?>)" 
                                            class="btn btn-sm btn-primary">
                                        <i class="fas fa-redo"></i> Retry
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Payments Chart -->
        <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px;">
            <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                <i class="fas fa-chart-line"></i> Payment Trends (Last 30 Days)
            </h3>
            <canvas id="paymentChart" height="80"></canvas>
        </div>
        
        <!-- Payments Table -->
        <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="font-size: 18px; font-weight: 600; color: var(--dark); margin: 0;">
                    <i class="fas fa-list"></i> Payment Transactions
                </h3>
                <div style="color: #666; font-size: 14px;">
                    Total: <?= number_format($stats['total_payments'] ?? 0, 2) ?> payments
                </div>
            </div>
            
            <div style="overflow-x: auto;">
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="background: #f8f9fa;">
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Transaction</th>
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Order #</th>
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Customer</th>
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Vendor</th>
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Gateway</th>
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Amount</th>
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Status</th>
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Date</th>
                            <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($payments)): ?>
                            <tr>
                                <td colspan="9" style="padding: 30px; text-align: center; color: #999;">
                                    <i class="fas fa-credit-card fa-3x mb-3"></i>
                                    <p>No payments found</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($payments as $payment): ?>
                                <tr style="border-bottom: 1px solid #f0f0f0;">
                                    <td style="padding: 15px;">
                                        <strong><?= Security::escapeOutput($payment['transaction_reference']) ?></strong><br>
                                        <?php if (!empty($payment['gateway_reference'])): ?>
                                            <small style="color: #666;">Ref: <?= Security::escapeOutput($payment['gateway_reference']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td style="padding: 15px;">
                                        <strong><?= Security::escapeOutput($payment['order_number']) ?></strong>
                                    </td>
                                    <td style="padding: 15px;">
                                        <div><?= Security::escapeOutput($payment['customer_name']) ?></div>
                                        <small style="color: #666;"><?= Security::escapeOutput($payment['customer_email']) ?></small>
                                    </td>
                                    <td style="padding: 15px;">
                                        <?= Security::escapeOutput($payment['vendor_name']) ?>
                                    </td>
                                    <td style="padding: 15px;">
                                        <span class="gateway-badge <?= $payment['payment_gateway'] ?>">
                                            <?= ucfirst($payment['payment_gateway']) ?>
                                        </span>
                                    </td>
                                    <td style="padding: 15px;">
                                        <strong><?= format_money($payment['amount']) ?></strong><br>
                                        <?php if ($payment['payment_type'] === 'refund'): ?>
                                            <small style="color: var(--info);">Refund</small>
                                        <?php endif; ?>
                                    </td>
                                    <td style="padding: 15px;">
                                        <?php
                                        $status_class = '';
                                        switch($payment['status']) {
                                            case 'completed':
                                                $status_class = 'status-success';
                                                break;
                                            case 'pending':
                                                $status_class = 'status-pending';
                                                break;
                                            case 'failed':
                                                $status_class = 'status-rejected';
                                                break;
                                            case 'refunded':
                                                $status_class = 'status-info';
                                                break;
                                        }
                                        ?>
                                        <span class="status-badge <?= $status_class ?>">
                                            <?= ucfirst($payment['status']) ?>
                                        </span>
                                    </td>
                                    <td style="padding: 15px;">
                                        <small><?= format_date($payment['created_at'], 'M d, Y') ?></small><br>
                                        <small style="color: #666;"><?= format_date($payment['created_at'], 'h:i A') ?></small>
                                    </td>
                                    <td style="padding: 15px;">
                                        <div class="action-buttons">
                                            <?php if ($payment['status'] === 'completed'): ?>
                                                <button onclick="showRefundModal(<?= $payment['id'] ?>, <?= $payment['amount'] ?>)" 
                                                        class="btn-action btn-warning" 
                                                        title="Process Refund">
                                                    <i class="fas fa-undo"></i>
                                                </button>
                                            <?php elseif ($payment['status'] === 'failed'): ?>
                                                <button onclick="retryPayment(<?= $payment['id'] ?>)" 
                                                        class="btn-action btn-primary" 
                                                        title="Retry Payment">
                                                    <i class="fas fa-redo"></i>
                                                </button>
                                            <?php endif; ?>
                                            
                                            <button onclick="viewPaymentDetails(<?= $payment['id'] ?>)" 
                                                    class="btn-action btn-info" 
                                                    title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div style="margin-top: 20px; text-align: center;">
                    <ul class="pagination">
                        <?php if ($page > 1): ?>
                            <li><a href="?page=<?= $page - 1 ?>&gateway=<?= $gateway ?>&status=<?= $status ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&search=<?= urlencode($search) ?>">&laquo; Previous</a></li>
                        <?php endif; ?>
                        
                        <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                            <li class="<?= $i == $page ? 'active' : '' ?>">
                                <a href="?page=<?= $i ?>&gateway=<?= $gateway ?>&status=<?= $status ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>
                        
                        <?php if ($page < $total_pages): ?>
                            <li><a href="?page=<?= $page + 1 ?>&gateway=<?= $gateway ?>&status=<?= $status ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&search=<?= urlencode($search) ?>">Next &raquo;</a></li>
                        <?php endif; ?>
                    </ul>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Refund Modal -->
<div id="refundModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 100px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 400px;">
        <h3 style="margin-bottom: 20px; font-size: 20px; font-weight: 600;">Process Refund</h3>
        
        <form method="POST" id="refundForm">
            <input type="hidden" name="action" value="refund">
            <input type="hidden" name="payment_id" id="refundPaymentId">
            
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600;">Refund Amount</label>
                <input type="number" 
                       name="refund_amount" 
                       id="refundAmount"
                       class="form-control" 
                       step="0.01"
                       min="0"
                       required>
                <small style="color: #666; font-size: 12px;">Maximum: <span id="maxRefund"></span></small>
            </div>
            
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600;">Reason *</label>
                <textarea name="refund_reason" 
                          class="form-control" 
                          rows="3" 
                          placeholder="Enter refund reason"
                          required></textarea>
            </div>
            
            <div style="display: flex; gap: 15px; justify-content: flex-end;">
                <button type="button" onclick="closeRefundModal()" class="btn btn-secondary">Cancel</button>
                <button type="submit" class="btn btn-warning">Process Refund</button>
            </div>
        </form>
    </div>
</div>

<!-- Payment Details Modal -->
<div id="detailsModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 50px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 600px; max-height: 90vh; overflow-y: auto;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
            <h3 style="margin: 0; font-size: 20px; font-weight: 600;">Payment Details</h3>
            <button onclick="closeDetailsModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
        </div>
        
        <div id="paymentDetails">
            <!-- Details will be loaded via AJAX -->
        </div>
    </div>
</div>

<style>
.modal {
    animation: fadeIn 0.3s;
}

.modal-content {
    animation: slideIn 0.3s;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideIn {
    from { transform: translateY(-50px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.status-success {
    background: var(--success);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-pending {
    background: var(--warning);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-rejected {
    background: var(--danger);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-info {
    background: var(--info);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.gateway-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    color: white;
}

.gateway-badge.paystack {
    background: #673ab7;
}

.gateway-badge.flutterwave {
    background: #00d2d3;
}

.gateway-badge.wallet {
    background: #4caf50;
}

.action-buttons {
    display: flex;
    gap: 5px;
}

.btn-action {
    background: none;
    border: 1px solid #ddd;
    padding: 8px;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s;
    color: #666;
    font-size: 14px;
}

.btn-action:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.btn-primary:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.btn-info:hover {
    border-color: var(--info);
    color: var(--info);
}

.btn-warning:hover {
    border-color: var(--warning);
    color: var(--warning);
}

.form-control {
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 10px 12px;
    font-size: 14px;
    transition: border-color 0.3s;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.btn {
    border: none;
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
}

.btn-primary {
    background: var(--primary);
    color: white;
}

.btn-primary:hover {
    background: #0056b3;
    transform: translateY(-2px);
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn-warning {
    background: var(--warning);
    color: white;
}

.btn-warning:hover {
    background: #e0a800;
}

.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.pagination {
    list-style: none;
    padding: 0;
    margin: 20px 0;
    display: flex;
    justify-content: center;
    gap: 5px;
}

.pagination li {
    display: inline;
}

.pagination a,
.pagination span {
    display: inline-block;
    padding: 8px 12px;
    border: 1px solid #ddd;
    color: var(--dark);
    text-decoration: none;
    border-radius: 4px;
    transition: all 0.3s;
}

.pagination a:hover {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}

.pagination .active span {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Menu Toggle
document.getElementById('menuToggle')?.addEventListener('click', function() {
    document.getElementById('sidebar').classList.toggle('active');
});

// Payment Chart
const chartData = <?= json_encode($chart_data) ?>;
const ctx = document.getElementById('paymentChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: chartData.map(d => d.date),
        datasets: [{
            label: 'Total Amount',
            data: chartData.map(d => d.amount),
            borderColor: '#28a745',
            backgroundColor: 'rgba(40, 167, 69, 0.1)',
            tension: 0.4,
            fill: true
        }, {
            label: 'Successful Payments',
            data: chartData.map(d => d.successful),
            borderColor: '#007bff',
            backgroundColor: 'rgba(0, 123, 255, 0.1)',
            tension: 0.4,
            fill: true
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
            legend: {
                position: 'top'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '₦' + value.toLocaleString();
                    }
                }
            }
        }
    }
});

// Refund Modal Functions
function showRefundModal(paymentId, maxAmount) {
    document.getElementById('refundPaymentId').value = paymentId;
    document.getElementById('refundAmount').max = maxAmount;
    document.getElementById('maxRefund').textContent = '₦' + parseFloat(maxAmount).toLocaleString();
    document.getElementById('refundModal').style.display = 'block';
}

function closeRefundModal() {
    document.getElementById('refundModal').style.display = 'none';
    document.getElementById('refundForm').reset();
}

// Payment Details Modal
function viewPaymentDetails(paymentId) {
    // Implementation would load details via AJAX
    document.getElementById('detailsModal').style.display = 'block';
    document.getElementById('paymentDetails').innerHTML = '<p>Loading payment details...</p>';
    
    // AJAX call to get payment details
    fetch('payment-details.php?id=' + paymentId)
        .then(response => response.text())
        .then(data => {
            document.getElementById('paymentDetails').innerHTML = data;
        })
        .catch(error => {
            document.getElementById('paymentDetails').innerHTML = '<p>Error loading payment details</p>';
        });
}

function closeDetailsModal() {
    document.getElementById('detailsModal').style.display = 'none';
}

// Retry Payment
function retryPayment(paymentId) {
    if (confirm('Mark this payment for retry?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="retry">
            <input type="hidden" name="payment_id" value="${paymentId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Close modals when clicking outside
window.onclick = function(event) {
    const refundModal = document.getElementById('refundModal');
    const detailsModal = document.getElementById('detailsModal');
    
    if (event.target === refundModal) {
        closeRefundModal();
    }
    if (event.target === detailsModal) {
        closeDetailsModal();
    }
}

// Auto-hide success messages
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-success');
    alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 500);
    });
}, 3000);
</script>

<?php include '../templates/layouts/admin/footer.php'; ?>