<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Payments';

if (!$auth->hasPermission('can_manage_payments') && !$auth->hasRole('super_admin')) {
    $_SESSION['error'] = "You don't have permission to access this page";
    header('Location: dashboard.php');
    exit;
}

// Filters
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';
$method_filter = $_GET['method'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page_num = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;
$offset = ($page_num - 1) * $limit;

// Build query
$where = [];
$params = [];

if ($search) {
    $where[] = "(transaction_reference LIKE ? OR p.id LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $where[] = "p.status = ?";
    $params[] = $status_filter;
}

if ($type_filter) {
    $where[] = "payment_type = ?";
    $params[] = $type_filter;
}

if ($method_filter) {
    $where[] = "payment_method = ?";
    $params[] = $method_filter;
}

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

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

$where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Get total
$count_sql = "SELECT COUNT(*) as total FROM payments p $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

// Get payments
$sql = "SELECT p.*, CONCAT(u.first_name, ' ', u.last_name) as user_name, u.email as user_email
        FROM payments p
        LEFT JOIN users u ON p.user_id = u.id
        $where_sql
        ORDER BY p.created_at DESC
        LIMIT $limit OFFSET $offset";

$payments = $db->fetchAll($sql, $params);

// Statistics
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total_revenue,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed,
    AVG(CASE WHEN status = 'completed' THEN amount ELSE NULL END) as avg_amount
    FROM payments";
$stats = $db->fetchOne($stats_sql);

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Payment Management</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Payments</li>
        </ol>
    </nav>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card stat-card">
            <div class="stat-icon" style="background: rgba(40, 167, 69, 0.1); color: #28a745;">
                <i class="fas fa-money-bill-wave"></i>
            </div>
            <div class="stat-info text-end">
                <h3>₦<?php echo number_format($stats['total_revenue']); ?></h3>
                <p>Total Revenue</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card">
            <div class="stat-icon" style="background: rgba(0, 123, 255, 0.1); color: #007bff;">
                <i class="fas fa-receipt"></i>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['total']); ?></h3>
                <p>Total Transactions</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card">
            <div class="stat-icon" style="background: rgba(255, 193, 7, 0.1); color: #ffc107;">
                <i class="fas fa-clock"></i>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['pending']); ?></h3>
                <p>Pending Payments</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card">
            <div class="stat-icon" style="background: rgba(108, 117, 125, 0.1); color: #6c757d;">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-info text-end">
                <h3>₦<?php echo number_format($stats['avg_amount']); ?></h3>
                <p>Average Transaction</p>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-credit-card"></i> All Payments</h5>
        <button class="btn btn-sm btn-success" onclick="exportPayments()">
            <i class="fas fa-file-excel"></i> Export to Excel
        </button>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-2">
                    <input type="text" name="search" class="form-control" placeholder="Search..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="col-md-2">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Failed</option>
                        <option value="refunded" <?php echo $status_filter === 'refunded' ? 'selected' : ''; ?>>Refunded</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="type" class="form-select">
                        <option value="">All Types</option>
                        <option value="commission" <?php echo $type_filter === 'commission' ? 'selected' : ''; ?>>Commission</option>
                        <option value="rent" <?php echo $type_filter === 'rent' ? 'selected' : ''; ?>>Rent</option>
                        <option value="purchase" <?php echo $type_filter === 'purchase' ? 'selected' : ''; ?>>Purchase</option>
                        <option value="verification" <?php echo $type_filter === 'verification' ? 'selected' : ''; ?>>Verification</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="method" class="form-select">
                        <option value="">All Methods</option>
                        <option value="paystack" <?php echo $method_filter === 'paystack' ? 'selected' : ''; ?>>Paystack</option>
                        <option value="flutterwave" <?php echo $method_filter === 'flutterwave' ? 'selected' : ''; ?>>Flutterwave</option>
                        <option value="bank_transfer" <?php echo $method_filter === 'bank_transfer' ? 'selected' : ''; ?>>Bank Transfer</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <input type="date" name="date_from" class="form-control" value="<?php echo $date_from; ?>">
                </div>
                <div class="col-md-1">
                    <button type="submit" class="btn btn-primary w-100"><i class="fas fa-filter"></i></button>
                </div>
            </div>
        </form>
        
        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Transaction #</th>
                        <th>User</th>
                        <th>Type</th>
                        <th>Amount</th>
                        <th>Method</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($payments)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No payments found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($payments as $payment): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($payment['transaction_reference']); ?></strong>
                                <br>
                                <small class="text-muted">ID: <?php echo $payment['id']; ?></small>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($payment['user_name']); ?>
                                <br>
                                <small class="text-muted"><?php echo htmlspecialchars($payment['user_email']); ?></small>
                            </td>
                            <td>
                                <span class="badge bg-info">
                                    <?php echo ucfirst($payment['payment_type']); ?>
                                </span>
                            </td>
                            <td><strong>₦<?php echo number_format($payment['amount'], 2); ?></strong></td>
                            <td>
                                <?php
                                $method_icon = [
                                    'paystack' => 'credit-card',
                                    'flutterwave' => 'credit-card',
                                    'bank_transfer' => 'university',
                                    'ussd' => 'mobile-alt',
                                    'cash' => 'money-bill'
                                ][$payment['payment_method']] ?? 'money-bill';
                                ?>
                                <i class="fas fa-<?php echo $method_icon; ?>"></i>
                                <?php echo ucfirst(str_replace('_', ' ', $payment['payment_method'])); ?>
                            </td>
                            <td>
                                <?php
                                $badge_class = [
                                    'completed' => 'success',
                                    'pending' => 'warning',
                                    'processing' => 'info',
                                    'failed' => 'danger',
                                    'refunded' => 'secondary'
                                ][$payment['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $badge_class; ?>">
                                    <?php echo ucfirst($payment['status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php echo date('M d, Y H:i', strtotime($payment['created_at'])); ?>
                                <?php if ($payment['paid_at']): ?>
                                <br><small class="text-muted">Paid: <?php echo date('M d, H:i', strtotime($payment['paid_at'])); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button type="button" class="btn btn-sm btn-outline-primary view-payment" 
                                        data-id="<?php echo $payment['id']; ?>"
                                        data-bs-toggle="tooltip" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-info" 
                                        onclick="window.open('generate-receipt.php?id=<?php echo $payment['id']; ?>', '_blank')"
                                        data-bs-toggle="tooltip" title="Download Receipt">
                                    <i class="fas fa-receipt"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav>
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo $page_num <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page_num - 1])); ?>">Previous</a>
                </li>
                <?php for ($i = max(1, $page_num - 2); $i <= min($total_pages, $page_num + 2); $i++): ?>
                <li class="page-item <?php echo $i === $page_num ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                <li class="page-item <?php echo $page_num >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page_num + 1])); ?>">Next</a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
</div>

<!-- Payment Details 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">Payment Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="paymentModalBody">
                <div class="text-center"><i class="fas fa-spinner fa-spin fa-3x"></i></div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        $('.view-payment').click(function() {
            const paymentId = $(this).data('id');
            $('#paymentModal').modal('show');
            
            $.get('ajax/get-payment-details.php', { id: paymentId }, function(data) {
                $('#paymentModalBody').html(data);
            });
        });
        
        $('[data-bs-toggle="tooltip"]').tooltip();
    });
    
    function exportPayments() {
        const params = new URLSearchParams(window.location.search);
        window.location.href = 'export-payments.php?' + params.toString();
    }
</script>

<?php include 'includes/footer.php'; ?>