<?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'] ?? '';
$payment_method_filter = $_GET['payment_method'] ?? '';

// Handle status filter - can be array (status[]) or single value (status)
if (is_array($status_filter)) {
    $status_filter = array_filter($status_filter); // Remove empty values
    if (empty($status_filter)) {
        $status_filter = '';
    }
}

// Handle payment method filter - can be array (payment_method[]) or single value (payment_method)
if (is_array($payment_method_filter)) {
    $payment_method_filter = array_filter($payment_method_filter); // Remove empty values
    if (empty($payment_method_filter)) {
        $payment_method_filter = '';
    }
}

try {
    $pdo = getDBConnection();
    
    // Build WHERE clause
    $where_conditions = [];
    $params = [];
    
    if (!empty($search)) {
        $where_conditions[] = "(r.contact_full_name LIKE ? OR r.contact_email LIKE ? OR r.registration_number LIKE ? OR r.university_name LIKE ?)";
        $search_param = "%{$search}%";
        $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    }
    
    if (!empty($status_filter)) {
        if (is_array($status_filter)) {
            // Multiple status filters
            $placeholders = implode(',', array_fill(0, count($status_filter), '?'));
            $where_conditions[] = "r.payment_status IN ($placeholders)";
            $params = array_merge($params, $status_filter);
        } else {
            // Single status filter (backward compatible)
            $where_conditions[] = "r.payment_status = ?";
            $params[] = $status_filter;
        }
    }
    
    if (!empty($payment_method_filter)) {
        if (is_array($payment_method_filter)) {
            // Multiple payment method filters
            $placeholders = implode(',', array_fill(0, count($payment_method_filter), '?'));
            $where_conditions[] = "r.payment_method IN ($placeholders)";
            $params = array_merge($params, $payment_method_filter);
        } else {
            // Single payment method filter (backward compatible)
            $where_conditions[] = "r.payment_method = ?";
            $params[] = $payment_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 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" id="status-filter-field" style="position: relative;">
                        <label for="status" class="filter-label">Payment Status</label>
                        <div class="filter-input" onclick="toggleStatusDropdown()" style="cursor: pointer; display: flex; justify-content: space-between; align-items: center; position: relative;">
                            <span id="status-text">
                                <?php
                                if (!empty($status_filter)) {
                                    if (is_array($status_filter)) {
                                        $selected_text = [];
                                        foreach ($status_filter as $s) {
                                            $labels = [
                                                'paid' => 'Paid',
                                                'pending' => 'Pending',
                                                'failed' => 'Failed',
                                                'expired' => 'Expired',
                                                'cancelled' => 'Cancelled'
                                            ];
                                            $selected_text[] = $labels[$s] ?? ucfirst($s);
                                        }
                                        echo count($status_filter) === 1 ? $selected_text[0] : (count($selected_text) . ' selected');
                                    } else {
                                        $labels = [
                                            'paid' => 'Paid',
                                            'pending' => 'Pending',
                                            'failed' => 'Failed',
                                            'expired' => 'Expired',
                                            'cancelled' => 'Cancelled'
                                        ];
                                        echo $labels[$status_filter] ?? ucfirst($status_filter);
                                    }
                                } else {
                                    echo 'All Statuses';
                                }
                                ?>
                            </span>
                            <span style="color: #9ca3af;">▼</span>
                        </div>
                        <div id="status-dropdown" class="multiselect-dropdown" onclick="event.stopPropagation();" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #d1d5db; border-radius: 6px; margin-top: 2px; max-height: 250px; overflow-y: auto; z-index: 1000; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                            <div style="padding: 8px;">
                                <label style="display: flex; align-items: center; padding: 6px 8px; cursor: pointer; border-radius: 4px; margin-bottom: 2px;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='transparent'">
                                    <input type="checkbox" name="status[]" value="paid" <?php echo (is_array($status_filter) && in_array('paid', $status_filter)) || $status_filter === 'paid' ? 'checked' : ''; ?> 
                                           onchange="updateStatusText()" style="margin-right: 8px;">
                                    <span style="color: #059669; font-weight: 500;">Paid</span>
                                </label>
                                <label style="display: flex; align-items: center; padding: 6px 8px; cursor: pointer; border-radius: 4px; margin-bottom: 2px;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='transparent'">
                                    <input type="checkbox" name="status[]" value="pending" <?php echo (is_array($status_filter) && in_array('pending', $status_filter)) || $status_filter === 'pending' ? 'checked' : ''; ?> 
                                           onchange="updateStatusText()" style="margin-right: 8px;">
                                    <span style="color: #d97706; font-weight: 500;">Pending</span>
                                </label>
                                <label style="display: flex; align-items: center; padding: 6px 8px; cursor: pointer; border-radius: 4px; margin-bottom: 2px;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='transparent'">
                                    <input type="checkbox" name="status[]" value="failed" <?php echo (is_array($status_filter) && in_array('failed', $status_filter)) || $status_filter === 'failed' ? 'checked' : ''; ?> 
                                           onchange="updateStatusText()" style="margin-right: 8px;">
                                    <span style="color: #dc2626; font-weight: 500;">Failed</span>
                                </label>
                                <label style="display: flex; align-items: center; padding: 6px 8px; cursor: pointer; border-radius: 4px; margin-bottom: 2px;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='transparent'">
                                    <input type="checkbox" name="status[]" value="expired" <?php echo (is_array($status_filter) && in_array('expired', $status_filter)) || $status_filter === 'expired' ? 'checked' : ''; ?> 
                                           onchange="updateStatusText()" style="margin-right: 8px;">
                                    <span style="color: #64748b; font-weight: 500;">Expired</span>
                                </label>
                                <label style="display: flex; align-items: center; padding: 6px 8px; cursor: pointer; border-radius: 4px; margin-bottom: 2px;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='transparent'">
                                    <input type="checkbox" name="status[]" value="cancelled" <?php echo (is_array($status_filter) && in_array('cancelled', $status_filter)) || $status_filter === 'cancelled' ? 'checked' : ''; ?> 
                                           onchange="updateStatusText()" style="margin-right: 8px;">
                                    <span style="color: #dc2626; font-weight: 500;">Cancelled</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="filter-field" id="payment-method-filter-field" style="position: relative;">
                        <label for="payment_method" class="filter-label">Payment Method</label>
                        <div class="filter-input" onclick="togglePaymentMethodDropdown()" style="cursor: pointer; display: flex; justify-content: space-between; align-items: center; position: relative;">
                            <span id="payment-method-text">
                                <?php
                                if (!empty($payment_method_filter)) {
                                    if (is_array($payment_method_filter)) {
                                        $selected_text = [];
                                        foreach ($payment_method_filter as $pm) {
                                            $labels = [
                                                'gateway' => '💳 Online Payment',
                                                'tt' => '🏦 Bank Transfer'
                                            ];
                                            $selected_text[] = $labels[$pm] ?? ucfirst($pm);
                                        }
                                        echo count($payment_method_filter) === 1 ? $selected_text[0] : (count($selected_text) . ' selected');
                                    } else {
                                        $labels = [
                                            'gateway' => '💳 Online Payment',
                                            'tt' => '🏦 Bank Transfer'
                                        ];
                                        echo $labels[$payment_method_filter] ?? ucfirst($payment_method_filter);
                                    }
                                } else {
                                    echo 'All Methods';
                                }
                                ?>
                            </span>
                            <span style="color: #9ca3af;">▼</span>
                        </div>
                        <div id="payment-method-dropdown" class="multiselect-dropdown" onclick="event.stopPropagation();" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #d1d5db; border-radius: 6px; margin-top: 2px; max-height: 250px; overflow-y: auto; z-index: 1000; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                            <div style="padding: 8px;">
                                <label style="display: flex; align-items: center; padding: 6px 8px; cursor: pointer; border-radius: 4px; margin-bottom: 2px;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='transparent'">
                                    <input type="checkbox" name="payment_method[]" value="gateway" <?php echo (is_array($payment_method_filter) && in_array('gateway', $payment_method_filter)) || $payment_method_filter === 'gateway' ? 'checked' : ''; ?> 
                                           onchange="updatePaymentMethodText()" style="margin-right: 8px;">
                                    <span style="color: #059669; font-weight: 500;">💳 Online Payment</span>
                                </label>
                                <label style="display: flex; align-items: center; padding: 6px 8px; cursor: pointer; border-radius: 4px; margin-bottom: 2px;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='transparent'">
                                    <input type="checkbox" name="payment_method[]" value="tt" <?php echo (is_array($payment_method_filter) && in_array('tt', $payment_method_filter)) || $payment_method_filter === 'tt' ? 'checked' : ''; ?> 
                                           onchange="updatePaymentMethodText()" style="margin-right: 8px;">
                                    <span style="color: #1e40af; font-weight: 500;">🏦 Bank Transfer</span>
                                </label>
                            </div>
                        </div>
                    </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): ?>
        <?php
        // Build status filter query string
        $status_query = '';
        if (!empty($status_filter)) {
            if (is_array($status_filter)) {
                foreach ($status_filter as $status) {
                    $status_query .= '&status[]=' . urlencode($status);
                }
            } else {
                $status_query .= '&status[]=' . urlencode($status_filter);
            }
        }
        
        // Build payment method filter query string
        $payment_method_query = '';
        if (!empty($payment_method_filter)) {
            if (is_array($payment_method_filter)) {
                foreach ($payment_method_filter as $pm) {
                    $payment_method_query .= '&payment_method[]=' . urlencode($pm);
                }
            } else {
                $payment_method_query .= '&payment_method[]=' . urlencode($payment_method_filter);
            }
        }
        
        $query_params = 'page=' . ($page - 1) . '&search=' . urlencode($search) . $status_query . $payment_method_query;
        ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?<?php echo $query_params; ?>">
                    Previous
                </a>
            <?php endif; ?>
            
            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <?php
                $page_query = 'page=' . $i . '&search=' . urlencode($search) . $status_query . $payment_method_query;
                ?>
                <?php if ($i === $page): ?>
                    <span class="current"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="?<?php echo $page_query; ?>">
                        <?php echo $i; ?>
                    </a>
                <?php endif; ?>
            <?php endfor; ?>
            
            <?php if ($page < $total_pages): ?>
                <?php
                $next_query = 'page=' . ($page + 1) . '&search=' . urlencode($search) . $status_query . $payment_method_query;
                ?>
                <a href="?<?php echo $next_query; ?>">
                    Next
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
    </div>

<script>
function toggleStatusDropdown() {
    const dropdown = document.getElementById('status-dropdown');
    dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
}

function updateStatusText() {
    const checkboxes = document.querySelectorAll('input[name="status[]"]:checked');
    const statusText = document.getElementById('status-text');
    
    const labels = {
        'paid': 'Paid',
        'pending': 'Pending',
        'failed': 'Failed',
        'expired': 'Expired',
        'cancelled': 'Cancelled'
    };
    
    if (checkboxes.length === 0) {
        statusText.textContent = 'All Statuses';
    } else if (checkboxes.length === 1) {
        statusText.textContent = labels[checkboxes[0].value] || 'Unknown';
    } else {
        statusText.textContent = checkboxes.length + ' selected';
    }
}

function togglePaymentMethodDropdown() {
    const dropdown = document.getElementById('payment-method-dropdown');
    dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
}

function updatePaymentMethodText() {
    const checkboxes = document.querySelectorAll('input[name="payment_method[]"]:checked');
    const paymentMethodText = document.getElementById('payment-method-text');
    
    const labels = {
        'gateway': '💳 Online Payment',
        'tt': '🏦 Bank Transfer'
    };
    
    if (checkboxes.length === 0) {
        paymentMethodText.textContent = 'All Methods';
    } else if (checkboxes.length === 1) {
        paymentMethodText.textContent = labels[checkboxes[0].value] || 'Unknown';
    } else {
        paymentMethodText.textContent = checkboxes.length + ' selected';
    }
}

// Close dropdowns when clicking outside
document.addEventListener('click', function(event) {
    const statusDropdown = document.getElementById('status-dropdown');
    const statusFilterField = event.target.closest('#status-filter-field');
    
    if (statusDropdown && !statusFilterField && statusDropdown.style.display === 'block') {
        statusDropdown.style.display = 'none';
    }
    
    const paymentMethodDropdown = document.getElementById('payment-method-dropdown');
    const paymentMethodFilterField = event.target.closest('#payment-method-filter-field');
    
    if (paymentMethodDropdown && !paymentMethodFilterField && paymentMethodDropdown.style.display === 'block') {
        paymentMethodDropdown.style.display = 'none';
    }
});
</script>

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