<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';


// Require admin login
requirePermission('payments', 'view');

$currentPage = 'payments';

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Search and filter
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$method_filter = $_GET['method'] ?? '';

try {
    $pdo = getDBConnection();
    
    // Build WHERE clause
    $where_conditions = [];
    $params = [];
    
    if (!empty($search)) {
        $where_conditions[] = "(r.contact_full_name LIKE ? OR r.registration_number LIKE ? OR r.payment_reference LIKE ?)";
        $search_param = "%{$search}%";
        $params = array_merge($params, [$search_param, $search_param, $search_param]);
    }
    
    if (!empty($status_filter)) {
        $where_conditions[] = "r.payment_status = ?";
        $params[] = $status_filter;
    }
    
    if (!empty($method_filter)) {
        $where_conditions[] = "r.payment_method = ?";
        $params[] = $method_filter;
    }
    
    $where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
    
    // Get total count for pagination
    $count_query = "SELECT COUNT(*) FROM registrations r {$where_clause}";
    $stmt = $pdo->prepare($count_query);
    $stmt->execute($params);
    $total_records = $stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);
    
    // Get payment data
    $query = "
        SELECT 
            r.registration_number,
            r.contact_full_name,
            r.university_name,
            r.payment_method,
            r.payment_status,
            r.payment_reference,
            r.total_amount,
            r.payment_deadline,
            r.created_at,
            r.updated_at
        FROM registrations r 
        {$where_clause}
        ORDER BY r.created_at DESC 
        LIMIT {$per_page} OFFSET {$offset}
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get payment summary statistics
    $summary_query = "
        SELECT 
            payment_method,
            payment_status,
            COUNT(*) as count,
            SUM(total_amount) as total_amount
        FROM registrations 
        GROUP BY payment_method, payment_status
        ORDER BY payment_method, payment_status
    ";
    $payment_summary = $pdo->query($summary_query)->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "Database error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payments - XChange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;909&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <?php if (isset($error)): ?>
            <div class="alert alert-error mb-4"><?php echo htmlspecialchars($error); ?></div>
        <?php else: ?>
        
        <!-- Payment Summary -->
        <div class="summary-grid">
            <?php 
            $summary_totals = [];
            foreach ($payment_summary as $item) {
                $key = $item['payment_method'] . '_' . $item['payment_status'];
                $summary_totals[$key] = $item;
            }
            ?>
            
            <div class="summary-card">
                <h4>Gateway Paid</h4>
                <div class="amount">$<?php echo number_format($summary_totals['gateway_paid']['total_amount'] ?? 0); ?></div>
                <div class="count"><?php echo number_format($summary_totals['gateway_paid']['count'] ?? 0); ?> payments</div>
            </div>
            
            <div class="summary-card">
                <h4>Gateway Pending</h4>
                <div class="amount">$<?php echo number_format($summary_totals['gateway_pending']['total_amount'] ?? 0); ?></div>
                <div class="count"><?php echo number_format($summary_totals['gateway_pending']['count'] ?? 0); ?> payments</div>
            </div>
            
            <div class="summary-card">
                <h4>Bank Transfer Paid</h4>
                <div class="amount">$<?php echo number_format($summary_totals['tt_paid']['total_amount'] ?? 0); ?></div>
                <div class="count"><?php echo number_format($summary_totals['tt_paid']['count'] ?? 0); ?> payments</div>
            </div>
            
            <div class="summary-card">
                <h4>Bank Transfer Pending</h4>
                <div class="amount">$<?php echo number_format($summary_totals['tt_pending']['total_amount'] ?? 0); ?></div>
                <div class="count"><?php echo number_format($summary_totals['tt_pending']['count'] ?? 0); ?> payments</div>
            </div>
        </div>
        
        <!-- Filters -->
        <div class="filters">
            <form method="GET" class="filter-form">
                <div class="filter-row">
                    <div class="filter-field">
                        <label for="search" class="filter-label">Search</label>
                        <input type="text" id="search" name="search" class="filter-input" 
                               placeholder="Name, registration #, payment reference..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="filter-field">
                        <label for="status" class="filter-label">Payment Status</label>
                        <select id="status" name="status" class="filter-input">
                            <option value="">All Statuses</option>
                            <option value="paid" <?php echo $status_filter === 'paid' ? 'selected' : ''; ?>>Paid</option>
                            <option value="complimentary" <?php echo $status_filter === 'complimentary' ? 'selected' : ''; ?>>Complimentary</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="expired" <?php echo $status_filter === 'expired' ? 'selected' : ''; ?>>Expired</option>
                            <option value="cancelled" <?php echo $status_filter === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    
                    <div class="filter-field">
                        <label for="method" class="filter-label">Payment Method</label>
                        <select id="method" name="method" class="filter-input">
                            <option value="">All Methods</option>
                            <option value="gateway" <?php echo $method_filter === 'gateway' ? 'selected' : ''; ?>>Online Payment</option>
                            <option value="tt" <?php echo $method_filter === 'tt' ? 'selected' : ''; ?>>Bank Transfer</option>
                        </select>
                    </div>
                    
                    <div class="filter-actions">
                        <button type="submit" class="btn btn-primary">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/>
                            </svg>
                            Filter
                        </button>
                        <a href="payments.php" class="btn btn-secondary">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M3 6h18l-2 13H5L3 6z"/>
                                <path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                            </svg>
                            Reset
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Payments Table -->
        <div class="data-table">
            <h2>Payment Records (<?php echo number_format($total_records); ?> total)</h2>
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Registration #</th>
                            <th>Contact</th>
                            <th>University</th>
                            <th>Method</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Reference</th>
                            <th>Deadline</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($payments)): ?>
                        <tr>
                            <td colspan="10" class="empty-state muted">
                                No payment records found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($payments as $payment): ?>
                        <tr>
                            <td>
                                <a href="registration-details.php?id=<?php echo urlencode($payment['registration_number']); ?>" 
                                   class="link link-strong">
                                    <?php echo htmlspecialchars($payment['registration_number']); ?>
                                </a>
                            </td>
                            <td>
                                <div><?php echo htmlspecialchars($payment['contact_full_name']); ?></div>
                            </td>
                            <td><?php echo htmlspecialchars($payment['university_name']); ?></td>
                            <td>
                                <span class="method-badge">
                                    <?php echo $payment['payment_method'] === 'gateway' ? 'Online' : 'Bank Transfer'; ?>
                                </span>
                            </td>
                            <td>$<?php echo number_format($payment['total_amount']); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $payment['payment_status']; ?>">
                                    <?php echo ucfirst($payment['payment_status']); ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($payment['payment_reference'] ?: '—'); ?></td>
                            <td>
                                <?php if ($payment['payment_deadline']): ?>
                                    <?php 
                                    $deadline = strtotime($payment['payment_deadline']);
                                    $now = time();
                                    $is_overdue = $deadline < $now && $payment['payment_status'] === 'pending';
                                    ?>
                                    <span class="<?php echo $is_overdue ? 'text-red-600' : 'text-slate-600'; ?>">
                                        <?php echo date('M j, Y', $deadline); ?>
                                        <?php if ($is_overdue): ?>
                                            <br><small class="text-red-500">OVERDUE</small>
                                        <?php endif; ?>
                                    </span>
                                <?php else: ?>
                                    —
                                <?php endif; ?>
                            </td>
                            <td>
                                <div><?php echo date('M j, Y', strtotime($payment['created_at'])); ?></div>
                                <div class="text-xxs muted">
                                    <?php echo date('H:i', strtotime($payment['created_at'])); ?>
                                </div>
                            </td>
                            <td>
                                <a href="registration-details.php?id=<?php echo urlencode($payment['registration_number']); ?>" 
                                   class="btn btn-secondary btn-compact">
                                    View
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>&method=<?php echo urlencode($method_filter); ?>">
                    Previous
                </a>
            <?php endif; ?>
            
            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <?php if ($i === $page): ?>
                    <span class="current"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>&method=<?php echo urlencode($method_filter); ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endif; ?>
            <?php endfor; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>&method=<?php echo urlencode($method_filter); ?>">
                    Next
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
    </div>

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