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


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

$currentPage = 'registrations';

// 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'] ?? '';
$type_filter = $_GET['type'] ?? '';

try {
    $pdo = getDBConnection();
    
    // Build WHERE clause
    $where_conditions = [];
    $params = [];
    
    if (!empty($search)) {
        $where_conditions[] = "(contact_full_name LIKE ? OR contact_email LIKE ? OR registration_number LIKE ? OR university_name LIKE ?)";
        $search_param = "%{$search}%";
        $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    }
    
    if (!empty($status_filter)) {
        $where_conditions[] = "payment_status = ?";
        $params[] = $status_filter;
    }
    
    if (!empty($type_filter)) {
        $where_conditions[] = "delegate_type = ?";
        $params[] = $type_filter;
    }
    
    $where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
    
    // Get total count for pagination
    $count_query = "SELECT COUNT(*) FROM registrations {$where_clause}";
    $stmt = $pdo->prepare($count_query);
    $stmt->execute($params);
    $total_records = $stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);
    
    // Get registrations with pagination and gateway transaction ID
    $query = "
        SELECT 
            r.id,
            r.registration_number,
            r.delegate_type,
            r.delegate_count,
            r.has_standard_table,
            r.has_double_table,
            r.contact_full_name,
            r.contact_email,
            r.contact_mobile,
            r.university_name,
            r.country,
            r.payment_method,
            r.payment_status,
            r.total_amount,
            r.created_at,
            r.payment_deadline,
            pt.gateway_transaction_id
        FROM registrations r
        LEFT JOIN payment_transactions pt ON r.id = pt.registration_id 
            AND pt.transaction_type = 'gateway' 
            AND pt.gateway_transaction_id IS NOT NULL
        {$where_clause}
        ORDER BY r.created_at DESC 
        LIMIT {$per_page} OFFSET {$offset}
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $registrations = $stmt->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>Registrations - 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;900&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($_GET['success']) && $_GET['success'] === 'registration_deleted'): ?>
            <div class="alert alert-success mb-4">
                Registration <?php echo htmlspecialchars($_GET['reg_number'] ?? 'N/A'); ?> has been successfully deleted along with all related data.
            </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error mb-4"><?php echo htmlspecialchars($error); ?></div>
        <?php else: ?>
        
        <!-- 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, email, registration #, university..." 
                               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="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="paid" <?php echo $status_filter === 'paid' ? 'selected' : ''; ?>>Paid</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="type" class="filter-label">Delegate Type</label>
                        <select id="type" name="type" class="filter-input">
                            <option value="">All Types</option>
                            <option value="earlyBird" <?php echo $type_filter === 'earlyBird' ? 'selected' : ''; ?>>Early Bird</option>
                            <option value="standard" <?php echo $type_filter === 'standard' ? 'selected' : ''; ?>>Standard</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="registrations.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>

        <!-- Registrations Table -->
        <div class="data-table">
            <h2>All Registrations (<?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>Delegates</th>
                            <th>Amount</th>
                            <th>Method</th>
                            <th>Gateway ID</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($registrations)): ?>
                        <tr>
                            <td colspan="10" class="empty-state muted">
                                No registrations found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($registrations as $reg): ?>
                        <tr>
                            <td>
                                <a href="registration-details.php?id=<?php echo urlencode($reg['registration_number']); ?>" 
                                   class="link link-strong">
                                    <?php echo htmlspecialchars($reg['registration_number']); ?>
                                </a>
                            </td>
                            <td>
                                <div><?php echo htmlspecialchars($reg['contact_full_name']); ?></div>
                                <div class="text-xs muted">
                                    <?php echo htmlspecialchars($reg['contact_email']); ?>
                                </div>
                            </td>
                            <td><?php echo htmlspecialchars($reg['university_name']); ?></td>
                            <td><?php echo number_format($reg['delegate_count']); ?></td>
                            <td>$<?php echo number_format($reg['total_amount']); ?></td>
                            <td>
                                <span class="method-badge">
                                    <?php 
                                    switch($reg['payment_method']) {
                                        case 'gateway':
                                            echo '💳 Online';
                                            break;
                                        case 'tt':
                                            echo '🏦 Bank Transfer';
                                            break;
                                        default:
                                            echo '—';
                                    }
                                    ?>
                                </span>
                            </td>
                            <td>
                                <?php if (!empty($reg['gateway_transaction_id'])): ?>
                                    <a href="https://dashboard.stripe.com/payments/<?php echo urlencode($reg['gateway_transaction_id']); ?>" 
                                       target="_blank" 
                                       style="color: #635bff; text-decoration: none; font-size: 0.9em;"
                                       title="View payment in Stripe Dashboard">
                                        🔗 Stripe
                                    </a>
                                <?php else: ?>
                                    <span class="text-xs muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $reg['payment_status']; ?>">
                                    <?php echo ucfirst($reg['payment_status']); ?>
                                </span>
                            </td>
                            <td>
                                <div><?php echo date('M j, Y', strtotime($reg['created_at'])); ?></div>
                                <div class="text-xxs muted">
                                    <?php echo date('H:i', strtotime($reg['created_at'])); ?>
                                </div>
                            </td>
                            <td>
                                <a href="registration-details.php?id=<?php echo urlencode($reg['registration_number']); ?>" 
                                   class="btn 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); ?>&type=<?php echo urlencode($type_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); ?>&type=<?php echo urlencode($type_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); ?>&type=<?php echo urlencode($type_filter); ?>">
                    Next
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
    </div>

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