<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Get search parameters
$search = $_GET['search'] ?? '';
$relationship_filter = $_GET['relationship_filter'] ?? '';
$trust_level_filter = $_GET['trust_level_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query with filters
$where_conditions = array("1=1");
$params = array();
$param_types = "";

if (!empty($search)) {
    $where_conditions[] = "(first_name LIKE ? OR last_name LIKE ? OR contributor_number LIKE ? OR phone_primary LIKE ? OR email LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param]);
    $param_types .= "sssss";
}

if (!empty($relationship_filter)) {
    $where_conditions[] = "relationship = ?";
    $params[] = $relationship_filter;
    $param_types .= "s";
}

if (!empty($trust_level_filter)) {
    $where_conditions[] = "trust_level = ?";
    $params[] = $trust_level_filter;
    $param_types .= "s";
}

if (!empty($status_filter)) {
    if ($status_filter == 'ACTIVE') {
        $where_conditions[] = "is_active = 1";
    } else {
        $where_conditions[] = "is_active = 0";
    }
}

$where_clause = implode(" AND ", $where_conditions);

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total FROM contributors WHERE $where_clause";
$count_stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_contributors = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_contributors / $limit);

// Get contributors with pagination
$query = "SELECT c.*, 
                 (SELECT COUNT(*) FROM fund_transactions ft WHERE ft.contributor_id = c.contributor_id) as total_transactions,
                 (SELECT MAX(transaction_date) FROM fund_transactions ft WHERE ft.contributor_id = c.contributor_id) as last_transaction_date
          FROM contributors c 
          WHERE $where_clause
          ORDER BY c.created_at DESC 
          LIMIT ? OFFSET ?";

$stmt = $conn->prepare($query);
$params[] = $limit;
$params[] = $offset;
$param_types .= "ii";

if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$contributors = $stmt->get_result();

// Get summary statistics
$stats_query = "SELECT 
    COUNT(*) as total_contributors,
    SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_contributors,
    SUM(total_contributed) as total_contributions,
    SUM(current_balance) as total_current_balance
    FROM contributors";
$stats = $conn->query($stats_query)->fetch_assoc();

// Get relationship counts
$relationship_counts_query = "SELECT relationship, COUNT(*) as count FROM contributors WHERE is_active = 1 GROUP BY relationship";
$relationship_counts_result = $conn->query($relationship_counts_query);
$relationship_counts = [];
while ($row = $relationship_counts_result->fetch_assoc()) {
    $relationship_counts[$row['relationship']] = $row['count'];
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Contributors - Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Filter Card */
        .filter-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Table Card */
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        
        /* Trust Level Badges */
        .trust-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .trust-high { background: #dcfce7; color: #166534; }
        .trust-medium { background: #fef3c7; color: #92400e; }
        .trust-low { background: #fee2e2; color: #991b1b; }
        
        /* Relationship Badges */
        .relationship-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .relationship-family { background: #e0e7ff; color: #3730a3; }
        .relationship-friend { background: #ddd6fe; color: #5b21b6; }
        .relationship-business { background: #fef3c7; color: #92400e; }
        .relationship-investor { background: #dcfce7; color: #166534; }
        .relationship-colleague { background: #f0f9ff; color: #0369a1; }
        .relationship-other { background: #f1f5f9; color: #475569; }
        
        /* Action Buttons */
        .btn-action {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin: 0 0.25rem;
            transition: all 0.2s ease;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-primary:hover { background: #1d4ed8; color: white; }
        
        .btn-success { background: #059669; color: white; }
        .btn-success:hover { background: #047857; color: white; }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; color: white; }
        
        .btn-info { background: #0891b2; color: white; }
        .btn-info:hover { background: #0e7490; color: white; }
        
        /* Pagination */
        .pagination-wrapper {
            padding: 1.5rem;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .pagination-info {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .pagination {
            display: flex;
            gap: 0.5rem;
            margin: 0;
        }
        
        .page-link {
            padding: 0.5rem 0.75rem;
            background: white;
            border: 1px solid #e2e8f0;
            color: #374151;
            text-decoration: none;
            border-radius: 6px;
            font-size: 0.875rem;
        }
        
        .page-link:hover {
            background: #f8fafc;
            border-color: #3b82f6;
            color: #3b82f6;
        }
        
        .page-link.active {
            background: #3b82f6;
            border-color: #3b82f6;
            color: white;
        }
        
        /* Form Controls */
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        /* Avatar */
        .contributor-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #059669;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        /* Success Message */
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            border: 1px solid;
        }
        
        .alert-success {
            background: #dcfce7;
            border-color: #bbf7d0;
            color: #166534;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .table-header {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
            
            .data-table {
                font-size: 0.75rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.5rem;
            }
        }
        
        /* Footer spacing fix */
        .main-content {
            padding-bottom: 2rem;
        }
        
        .page-content {
            margin-bottom: 3rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Contributors Management</h1>
                        <p class="page-subtitle">Manage contributors and track their fund contributions</p>
                    </div>

                    <!-- Success Message -->
                    <?php if (isset($_GET['success'])): ?>
                        <div class="alert alert-success">
                            Contributor added successfully!
                        </div>
                    <?php endif; ?>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['total_contributors'] ?? 0); ?></div>
                            <div class="stat-label">Total Contributors</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['active_contributors'] ?? 0); ?></div>
                            <div class="stat-label">Active Contributors</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_contributions'] ?? 0); ?></div>
                            <div class="stat-label">Total Contributions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_current_balance'] ?? 0); ?></div>
                            <div class="stat-label">Current Balance</div>
                        </div>
                    </div>

                    <!-- Filter Card -->
                    <div class="filter-card">
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search name, number, phone...">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Relationship</label>
                                <select class="form-select" name="relationship_filter">
                                    <option value="">All Relationships</option>
                                    <option value="FAMILY" <?php echo $relationship_filter == 'FAMILY' ? 'selected' : ''; ?>>Family</option>
                                    <option value="FRIEND" <?php echo $relationship_filter == 'FRIEND' ? 'selected' : ''; ?>>Friend</option>
                                    <option value="BUSINESS_PARTNER" <?php echo $relationship_filter == 'BUSINESS_PARTNER' ? 'selected' : ''; ?>>Business Partner</option>
                                    <option value="PERSONAL_INVESTOR" <?php echo $relationship_filter == 'PERSONAL_INVESTOR' ? 'selected' : ''; ?>>Personal Investor</option>
                                    <option value="COLLEAGUE" <?php echo $relationship_filter == 'COLLEAGUE' ? 'selected' : ''; ?>>Colleague</option>
                                    <option value="OTHER" <?php echo $relationship_filter == 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Trust Level</label>
                                <select class="form-select" name="trust_level_filter">
                                    <option value="">All Levels</option>
                                    <option value="HIGH" <?php echo $trust_level_filter == 'HIGH' ? 'selected' : ''; ?>>High</option>
                                    <option value="MEDIUM" <?php echo $trust_level_filter == 'MEDIUM' ? 'selected' : ''; ?>>Medium</option>
                                    <option value="LOW" <?php echo $trust_level_filter == 'LOW' ? 'selected' : ''; ?>>Low</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status_filter">
                                    <option value="">All Status</option>
                                    <option value="ACTIVE" <?php echo $status_filter == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                    <option value="INACTIVE" <?php echo $status_filter == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">Filter</button>
                                    <a href="list_contributors.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Contributors Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Contributors List (<?php echo $total_contributors; ?> total)</h3>
                            <div class="d-flex gap-2">
                                <a href="add_contributor.php" class="btn btn-success">
                                    <i class="ph-plus me-1"></i> Add Contributor
                                </a>
                                <a href="fund_transactions.php" class="btn btn-info">
                                    <i class="ph-currency-circle-dollar me-1"></i> View Transactions
                                </a>
                            </div>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Contributor</th>
                                    <th>Contact Info</th>
                                    <th>Relationship</th>
                                    <th>Financial Summary</th>
                                    <th>Trust Level</th>
                                    <th>Activity</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($contributors->num_rows > 0): ?>
                                    <?php while ($contributor = $contributors->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="contributor-avatar me-3">
                                                    <?php echo strtoupper(substr($contributor['first_name'], 0, 1) . substr($contributor['last_name'], 0, 1)); ?>
                                                </div>
                                                <div>
                                                    <div style="font-weight: 600; color: #1e293b;">
                                                        <?php echo htmlspecialchars($contributor['first_name'] . ' ' . $contributor['last_name']); ?>
                                                    </div>
                                                    <div style="color: #64748b; font-size: 0.75rem;">
                                                        <?php echo htmlspecialchars($contributor['contributor_number']); ?>
                                                    </div>
                                                    <?php if ($contributor['middle_name']): ?>
                                                        <div style="color: #64748b; font-size: 0.75rem;">
                                                            <?php echo htmlspecialchars($contributor['middle_name']); ?>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div style="font-weight: 500; color: #1e293b;">
                                                <?php echo htmlspecialchars($contributor['phone_primary']); ?>
                                            </div>
                                            <?php if ($contributor['email']): ?>
                                                <div style="color: #64748b; font-size: 0.75rem;">
                                                    <?php echo htmlspecialchars($contributor['email']); ?>
                                                </div>
                                            <?php endif; ?>
                                            <?php if ($contributor['phone_secondary']): ?>
                                                <div style="color: #64748b; font-size: 0.75rem;">
                                                    Alt: <?php echo htmlspecialchars($contributor['phone_secondary']); ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php 
                                            $relationship_class = match($contributor['relationship']) {
                                                'FAMILY' => 'relationship-family',
                                                'FRIEND' => 'relationship-friend',
                                                'BUSINESS_PARTNER' => 'relationship-business',
                                                'PERSONAL_INVESTOR' => 'relationship-investor',
                                                'COLLEAGUE' => 'relationship-colleague',
                                                default => 'relationship-other'
                                            };
                                            ?>
                                            <span class="relationship-badge <?php echo $relationship_class; ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', strtolower($contributor['relationship']))); ?>
                                            </span>
                                            <?php if ($contributor['relationship_details']): ?>
                                                <div style="color: #64748b; font-size: 0.75rem; margin-top: 0.25rem;">
                                                    <?php echo htmlspecialchars($contributor['relationship_details']); ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div style="font-weight: 600; color: #059669;">
                                                Contributed: KES <?php echo number_format($contributor['total_contributed']); ?>
                                            </div>
                                            <?php if ($contributor['total_withdrawn'] > 0): ?>
                                                <div style="color: #dc2626; font-size: 0.75rem;">
                                                    Withdrawn: KES <?php echo number_format($contributor['total_withdrawn']); ?>
                                                </div>
                                            <?php endif; ?>
                                            <div style="color: #1e293b; font-size: 0.75rem; font-weight: 500;">
                                                Balance: KES <?php echo number_format($contributor['current_balance']); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php 
                                            $trust_class = match($contributor['trust_level']) {
                                                'HIGH' => 'trust-high',
                                                'MEDIUM' => 'trust-medium',
                                                'LOW' => 'trust-low',
                                                default => 'trust-medium'
                                            };
                                            ?>
                                            <span class="trust-badge <?php echo $trust_class; ?>">
                                                <?php echo ucfirst(strtolower($contributor['trust_level'])); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div style="font-weight: 500; color: #1e293b;">
                                                <?php echo $contributor['total_transactions']; ?> transactions
                                            </div>
                                            <?php if ($contributor['last_transaction_date']): ?>
                                                <div style="color: #64748b; font-size: 0.75rem;">
                                                    Last: <?php echo date('M j, Y', strtotime($contributor['last_transaction_date'])); ?>
                                                </div>
                                            <?php else: ?>
                                                <div style="color: #64748b; font-size: 0.75rem;">
                                                    No transactions yet
                                                </div>
                                            <?php endif; ?>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                Joined: <?php echo date('M j, Y', strtotime($contributor['created_at'])); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php 
                                            $status_class = $contributor['is_active'] ? 'status-active' : 'status-inactive';
                                            $status_text = $contributor['is_active'] ? 'Active' : 'Inactive';
                                            ?>
                                            <span class="status-badge <?php echo $status_class; ?>">
                                                <?php echo $status_text; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="d-flex gap-1">
                                                <a href="view_contributor.php?id=<?php echo $contributor['contributor_id']; ?>" class="btn-action btn-primary" title="View Details">
                                                    <i class="ph-eye"></i>
                                                </a>
                                                <a href="edit_contributor.php?id=<?php echo $contributor['contributor_id']; ?>" class="btn-action btn-warning" title="Edit Contributor">
                                                    <i class="ph-pencil"></i>
                                                </a>
                                                <a href="contributor_transactions.php?id=<?php echo $contributor['contributor_id']; ?>" class="btn-action btn-info" title="View Transactions">
                                                    <i class="ph-currency-circle-dollar"></i>
                                                </a>
                                                <a href="add_transaction.php?contributor_id=<?php echo $contributor['contributor_id']; ?>" class="btn-action btn-success" title="Add Transaction">
                                                    <i class="ph-plus"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="8" class="text-center" style="padding: 3rem;">
                                            <div style="color: #64748b;">
                                                <i class="ph-users" style="font-size: 3rem; margin-bottom: 1rem; display: block;"></i>
                                                <h4>No contributors found</h4>
                                                <p>Start by adding your first contributor to the system.</p>
                                                <a href="add_contributor.php" class="btn btn-success mt-2">
                                                    <i class="ph-plus me-1"></i> Add First Contributor
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>

                        <!-- Pagination -->
                        <?php if ($total_contributors > 0): ?>
                            <div class="pagination-wrapper">
                                <div class="pagination-info">
                                    Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_contributors); ?> of <?php echo $total_contributors; ?> entries
                                </div>
                                
                                <?php if ($total_pages > 1): ?>
                                    <div class="pagination">
                                        <?php if ($page > 1): ?>
                                            <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&relationship_filter=<?php echo $relationship_filter; ?>&trust_level_filter=<?php echo $trust_level_filter; ?>&status_filter=<?php echo $status_filter; ?>" class="page-link">
                                                <i class="ph-caret-left"></i>
                                            </a>
                                        <?php endif; ?>
                                        
                                        <?php 
                                        $start = max(1, $page - 2);
                                        $end = min($total_pages, $page + 2);
                                        
                                        for ($i = $start; $i <= $end; $i++): 
                                        ?>
                                            <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&relationship_filter=<?php echo $relationship_filter; ?>&trust_level_filter=<?php echo $trust_level_filter; ?>&status_filter=<?php echo $status_filter; ?>" 
                                               class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                                                <?php echo $i; ?>
                                            </a>
                                        <?php endfor; ?>
                                        
                                        <?php if ($page < $total_pages): ?>
                                            <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&relationship_filter=<?php echo $relationship_filter; ?>&trust_level_filter=<?php echo $trust_level_filter; ?>&status_filter=<?php echo $status_filter; ?>" class="page-link">
                                                <i class="ph-caret-right"></i>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Quick Stats Summary -->
                    <?php if ($total_contributors > 0): ?>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="table-card">
                                    <div class="table-header">
                                        <h3 class="table-title">Relationship Breakdown</h3>
                                    </div>
                                    <div style="padding: 1.5rem;">
                                        <?php if (!empty($relationship_counts)): ?>
                                            <?php foreach ($relationship_counts as $relationship => $count): ?>
                                                <div class="d-flex justify-content-between align-items-center mb-2">
                                                    <span><?php echo ucfirst(str_replace('_', ' ', strtolower($relationship))); ?></span>
                                                    <span class="relationship-badge relationship-<?php echo strtolower(str_replace('_', '-', $relationship)); ?>">
                                                        <?php echo $count; ?>
                                                    </span>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <p class="text-muted">No relationship data available</p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="table-card">
                                    <div class="table-header">
                                        <h3 class="table-title">Recent Activity</h3>
                                    </div>
                                    <div style="padding: 1.5rem;">
                                        <?php
                                        // Get recent activity
                                        $recent_activity_query = "SELECT c.first_name, c.last_name, c.created_at 
                                                                FROM contributors c 
                                                                WHERE c.is_active = 1 
                                                                ORDER BY c.created_at DESC 
                                                                LIMIT 5";
                                        $recent_activity = $conn->query($recent_activity_query);
                                        ?>
                                        <?php if ($recent_activity->num_rows > 0): ?>
                                            <?php while ($activity = $recent_activity->fetch_assoc()): ?>
                                                <div class="d-flex justify-content-between align-items-center mb-2">
                                                    <div>
                                                        <span style="font-weight: 500;"><?php echo htmlspecialchars($activity['first_name'] . ' ' . $activity['last_name']); ?></span>
                                                        <small class="text-muted d-block">joined the system</small>
                                                    </div>
                                                    <small class="text-muted">
                                                        <?php echo date('M j, Y', strtotime($activity['created_at'])); ?>
                                                    </small>
                                                </div>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <p class="text-muted">No recent activity</p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Auto-submit form on filter change
            $('.form-select').on('change', function() {
                $(this).closest('form').submit();
            });
            
            // Search on enter key
            $('input[name="search"]').on('keypress', function(e) {
                if (e.which === 13) {
                    $(this).closest('form').submit();
                }
            });
            
            // Clear search button functionality
            $('.btn-outline-secondary').on('click', function(e) {
                if ($(this).text().trim() === 'Clear') {
                    e.preventDefault();
                    window.location.href = 'list_contributors.php';
                }
            });
            
            // Tooltip initialization for action buttons
            $('[title]').tooltip();
            
            // Confirmation for delete actions (if you add delete functionality later)
            $('.btn-danger').on('click', function(e) {
                if (!confirm('Are you sure you want to delete this contributor? This action cannot be undone.')) {
                    e.preventDefault();
                }
            });
            
            // Auto-hide success messages after 5 seconds
            $('.alert-success').delay(5000).fadeOut();
            
            // Add loading state to buttons
            $('.btn').on('click', function() {
                var $btn = $(this);
                if (!$btn.hasClass('btn-outline-secondary')) {
                    $btn.prop('disabled', true);
                    setTimeout(function() {
                        $btn.prop('disabled', false);
                    }, 2000);
                }
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>