Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/portal/modules/membership/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/portal/modules/membership/duplicate-entries.php

<?php
require_once '../../config/config.php';
checkLogin();
checkAccess('assembly');

$pageTitle = "Duplicate Member Entries - " . APP_NAME;
$db = Database::getInstance()->getConnection();

// Get user access parameters
$accessLevel = $_SESSION['access_level'] ?? 'assembly';
$areaId = $_SESSION['area_id'] ?? null;
$districtId = $_SESSION['district_id'] ?? null;
$assemblyId = $_SESSION['assembly_id'] ?? null;

// Load districts and assemblies for filters
$districts = [];
$assemblies = [];
try {
    $districtsStmt = $db->query("SELECT id, district_name FROM districts WHERE is_active = 1 ORDER BY district_name");
    $districts = $districtsStmt->fetchAll();
} catch (PDOException $e) {
    // ignore if table not ready
}

try {
    $assembliesStmt = $db->query("SELECT id, assembly_name, district_id FROM assemblies WHERE is_active = 1 ORDER BY assembly_name");
    $assemblies = $assembliesStmt->fetchAll();
} catch (PDOException $e) {
    // ignore if table not ready
}

// Build WHERE clause for access level
$accessWhere = '';
$accessParams = [];
if ($accessLevel === 'assembly') {
    $accessWhere .= " AND m.assembly_id = :assembly_id";
    $accessParams['assembly_id'] = $assemblyId;
} elseif ($accessLevel === 'district') {
    $accessWhere .= " AND m.district_id = :district_id";
    $accessParams['district_id'] = $districtId;
} elseif ($accessLevel === 'area') {
    $accessWhere .= " AND m.area_id = :area_id";
    $accessParams['area_id'] = $areaId;
}

// Additional filters
$filterWhere = '';
$filterParams = [];

if (isset($_GET['district_filter']) && $_GET['district_filter'] !== '') {
    $filterWhere .= " AND m.district_id = :filter_district_id";
    $filterParams['filter_district_id'] = (int)$_GET['district_filter'];
}

if (isset($_GET['assembly_filter']) && $_GET['assembly_filter'] !== '') {
    $filterWhere .= " AND m.assembly_id = :filter_assembly_id";
    $filterParams['filter_assembly_id'] = (int)$_GET['assembly_filter'];
}

// Search filter
$searchWhere = '';
$searchParams = [];
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = '%' . $_GET['search'] . '%';
    $searchWhere .= " AND (m.first_name LIKE :search1 OR m.last_name LIKE :search2 OR m.email LIKE :search3)";
    $searchParams['search1'] = $search;
    $searchParams['search2'] = $search;
    $searchParams['search3'] = $search;
}

// Create duplicate parameters for subquery (since same params are used twice)
$subqueryParams = [];
$subqueryAccessWhere = '';
$subqueryFilterWhere = '';
$subquerySearchWhere = '';

// Duplicate access params with 'sub_' prefix
if (!empty($accessWhere)) {
    $subqueryAccessWhere = $accessWhere;
    foreach ($accessParams as $key => $value) {
        $subqueryParams['sub_' . $key] = $value;
        $subqueryAccessWhere = str_replace(':' . $key, ':sub_' . $key, $subqueryAccessWhere);
    }
}

// Duplicate filter params with 'sub_' prefix
if (!empty($filterWhere)) {
    $subqueryFilterWhere = $filterWhere;
    foreach ($filterParams as $key => $value) {
        $subqueryParams['sub_' . $key] = $value;
        $subqueryFilterWhere = str_replace(':' . $key, ':sub_' . $key, $subqueryFilterWhere);
    }
}

// Duplicate search params with 'sub_' prefix
if (!empty($searchWhere)) {
    $subquerySearchWhere = $searchWhere;
    foreach ($searchParams as $key => $value) {
        $subqueryParams['sub_' . $key] = $value;
        $subquerySearchWhere = str_replace(':' . $key, ':sub_' . $key, $subquerySearchWhere);
    }
}

// Combine all parameters (original + duplicated for subquery)
$allParams = array_merge($accessParams, $filterParams, $searchParams, $subqueryParams);

// Query to find duplicate members
// Duplicates are identified by having the same first_name, last_name, and date_of_birth
$duplicateQuery = "
    SELECT 
        m.id,
        m.first_name,
        m.middle_name,
        m.last_name,
        m.title,
        m.date_of_birth,
        m.gender,
        m.phone,
        m.email,
        m.member_type,
        m.profile_photo,
        m.created_at,
        m.is_active,
        a.area_name,
        d.district_name,
        asm.assembly_name,
        ma.id as account_id,
        ma.username,
        CONCAT(LOWER(TRIM(m.first_name)), '|', LOWER(TRIM(m.last_name)), '|', COALESCE(m.date_of_birth, 'NULL')) as dup_key
    FROM members m
    JOIN areas a ON m.area_id = a.id
    JOIN districts d ON m.district_id = d.id
    JOIN assemblies asm ON m.assembly_id = asm.id
    LEFT JOIN member_accounts ma ON m.id = ma.member_id
    WHERE CONCAT(LOWER(TRIM(m.first_name)), '|', LOWER(TRIM(m.last_name)), '|', COALESCE(m.date_of_birth, 'NULL')) IN (
        SELECT CONCAT(LOWER(TRIM(first_name)), '|', LOWER(TRIM(last_name)), '|', COALESCE(date_of_birth, 'NULL'))
        FROM members
        WHERE 1=1 {$subqueryAccessWhere} {$subqueryFilterWhere} {$subquerySearchWhere}
        GROUP BY CONCAT(LOWER(TRIM(first_name)), '|', LOWER(TRIM(last_name)), '|', COALESCE(date_of_birth, 'NULL'))
        HAVING COUNT(*) > 1
    )
    {$accessWhere} {$filterWhere} {$searchWhere}
    ORDER BY m.first_name, m.last_name, m.date_of_birth, m.created_at
";

$stmt = $db->prepare($duplicateQuery);
$stmt->execute($allParams);
$duplicates = $stmt->fetchAll();

// Debug: Log query and results
error_log("Duplicate query executed with " . count($duplicates) . " results");
error_log("Query: " . $duplicateQuery);
error_log("Params: " . print_r($allParams, true));

// Group duplicates by their key
$groupedDuplicates = [];
foreach ($duplicates as $member) {
    $key = $member['dup_key'];
    if (!isset($groupedDuplicates[$key])) {
        $groupedDuplicates[$key] = [];
    }
    $groupedDuplicates[$key][] = $member;
}

// Debug: Log grouping results
error_log("Grouped duplicates: " . count($groupedDuplicates) . " groups");
if (count($groupedDuplicates) > 0) {
    error_log("First group key: " . array_key_first($groupedDuplicates));
    error_log("First group count: " . count($groupedDuplicates[array_key_first($groupedDuplicates)]));
}

// Count statistics
$totalDuplicateGroups = count($groupedDuplicates);
$totalDuplicateMembers = count($duplicates);
$membersWithoutAccounts = count(array_filter($duplicates, fn($m) => empty($m['account_id'])));

include '../../includes/header.php';
?>

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

<!-- Main Content -->
<main class="flex-1 md:ml-64 mt-16">
<div class="container mx-auto px-4 py-8">
    <!-- Success/Error Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded-lg shadow-md" role="alert">
            <div class="flex items-center">
                <i class="fas fa-check-circle text-2xl mr-3"></i>
                <div>
                    <p class="font-bold">Success!</p>
                    <p><?php echo htmlspecialchars($_SESSION['success']); unset($_SESSION['success']); ?></p>
                </div>
            </div>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded-lg shadow-md" role="alert">
            <div class="flex items-center">
                <i class="fas fa-exclamation-circle text-2xl mr-3"></i>
                <div>
                    <p class="font-bold">Error!</p>
                    <p><?php echo htmlspecialchars($_SESSION['error']); unset($_SESSION['error']); ?></p>
                </div>
            </div>
        </div>
    <?php endif; ?>
    
    <!-- Page Header -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
        <div>
            <h1 class="text-3xl font-bold text-gray-800">
                <i class="fas fa-copy mr-2 text-yellow-500"></i>Duplicate Member Entries
            </h1>
            <p class="text-gray-600 mt-2">Review and manage duplicate member records</p>
        </div>
        <div class="flex gap-3">
            <a href="index.php" class="bg-gray-600 text-white px-6 py-3 rounded-full font-semibold transition shadow-lg hover:bg-gray-700">
                <i class="fas fa-arrow-left mr-2"></i>Back to Members
            </a>
        </div>
    </div>
    
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow p-4 border-l-4 border-yellow-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">Duplicate Groups</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo $totalDuplicateGroups; ?></p>
                </div>
                <i class="fas fa-layer-group text-3xl text-yellow-500"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-4 border-l-4 border-orange-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">Total Duplicates</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo $totalDuplicateMembers; ?></p>
                </div>
                <i class="fas fa-users text-3xl text-orange-500"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-4 border-l-4 border-red-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">Without Accounts</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo $membersWithoutAccounts; ?></p>
                </div>
                <i class="fas fa-user-times text-3xl text-red-500"></i>
            </div>
        </div>
    </div>
    
    <!-- Search and Filters -->
    <div class="bg-white rounded-lg shadow-lg p-6 mb-6">
        <form method="GET" action="" class="flex flex-col md:flex-row gap-4 items-center">
            <div class="flex-1 w-full">
                <div class="relative">
                    <input type="text" 
                           name="search" 
                           placeholder="Search by name or email..." 
                           value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>"
                           class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-yellow-500 focus:border-transparent">
                    <i class="fas fa-search absolute left-3 top-4 text-gray-400"></i>
                </div>
            </div>

            <div class="flex items-center space-x-3">
                <div>
                    <label class="block text-xs font-semibold text-gray-600 mb-1">District</label>
                    <select name="district_filter" id="filterDistrictSelect" class="px-3 py-2 border border-gray-300 rounded-lg text-sm">
                        <option value="">All Districts</option>
                        <?php foreach ($districts as $dist): ?>
                            <option value="<?php echo $dist['id']; ?>" <?php echo (isset($_GET['district_filter']) && $_GET['district_filter'] == $dist['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($dist['district_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-gray-600 mb-1">Assembly</label>
                    <select name="assembly_filter" id="filterAssemblySelect" class="px-3 py-2 border border-gray-300 rounded-lg text-sm">
                        <option value="">All Assemblies</option>
                        <?php foreach ($assemblies as $asm): ?>
                            <option value="<?php echo $asm['id']; ?>" data-district-id="<?php echo $asm['district_id']; ?>" <?php echo (isset($_GET['assembly_filter']) && $_GET['assembly_filter'] == $asm['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($asm['assembly_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <button type="submit" class="bg-yellow-500 text-white px-6 py-3 rounded-lg hover:bg-yellow-600 transition mt-5">
                    <i class="fas fa-filter mr-2"></i>Filter
                </button>
                <a href="duplicate-entries.php" class="bg-gray-500 text-white px-6 py-3 rounded-lg hover:bg-gray-600 transition text-center mt-5">
                    <i class="fas fa-redo mr-2"></i>Reset
                </a>
            </div>
        </form>
    </div>
    
    <!-- Global Actions -->
    <?php if (!empty($groupedDuplicates)): ?>
    <div class="bg-white rounded-lg shadow-lg p-4 mb-6">
        <div class="flex justify-between items-center">
            <div class="flex gap-3">
                <button type="button" onclick="selectAllDuplicates()" 
                        class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-semibold">
                    <i class="fas fa-check-double mr-2"></i>Select All Duplicates
                </button>
                <button type="button" onclick="selectAllWithoutAccounts()" 
                        class="bg-orange-600 text-white px-6 py-3 rounded-lg hover:bg-orange-700 transition font-semibold">
                    <i class="fas fa-user-times mr-2"></i>Select All Without Accounts
                </button>
                <button type="button" onclick="deselectAllDuplicates()" 
                        class="bg-gray-600 text-white px-6 py-3 rounded-lg hover:bg-gray-700 transition font-semibold">
                    <i class="fas fa-times mr-2"></i>Deselect All
                </button>
            </div>
            <div>
                <button type="button" onclick="deleteAllSelected()" 
                        class="bg-red-600 text-white px-6 py-3 rounded-lg hover:bg-red-700 transition font-semibold">
                    <i class="fas fa-trash-alt mr-2"></i>Delete All Selected
                </button>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Debug Info (remove after fixing) -->
    <?php if (isset($_GET['debug'])): ?>
    <div class="bg-yellow-100 border-l-4 border-yellow-500 p-4 mb-6">
        <h3 class="font-bold text-lg mb-2">Debug Information:</h3>
        <p><strong>Total Duplicates Array:</strong> <?php echo count($duplicates); ?> records</p>
        <p><strong>Grouped Duplicates:</strong> <?php echo count($groupedDuplicates); ?> groups</p>
        <p><strong>Is Empty Check:</strong> <?php echo empty($groupedDuplicates) ? 'TRUE (empty)' : 'FALSE (has data)'; ?></p>
        <?php if (!empty($duplicates) && count($duplicates) > 0): ?>
            <p><strong>First Duplicate Record:</strong></p>
            <pre class="bg-white p-2 rounded text-xs overflow-auto"><?php print_r(array_slice($duplicates, 0, 1)); ?></pre>
        <?php endif; ?>
        <?php if (!empty($groupedDuplicates)): ?>
            <p><strong>First Group:</strong></p>
            <pre class="bg-white p-2 rounded text-xs overflow-auto"><?php print_r(array_slice($groupedDuplicates, 0, 1, true)); ?></pre>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <!-- Duplicate Groups -->
    <?php if (count($groupedDuplicates) === 0): ?>
        <div class="bg-white rounded-lg shadow-lg p-12 text-center">
            <i class="fas fa-check-circle text-6xl text-green-500 mb-4"></i>
            <h3 class="text-2xl font-bold text-gray-800 mb-2">No Duplicate Entries Found</h3>
            <p class="text-gray-600">All member records are unique. Great job maintaining clean data!</p>
            <?php if (count($duplicates) > 0): ?>
                <div class="mt-4 p-4 bg-red-50 rounded">
                    <p class="text-red-700 font-semibold">⚠️ Debug Note: Found <?php echo count($duplicates); ?> duplicate records but grouping failed.</p>
                    <p class="text-sm mt-2"><a href="?debug=1" class="text-blue-600 underline">Click here to see debug info</a></p>
                </div>
            <?php endif; ?>
            <a href="index.php" class="text-blue-500 hover:text-blue-600 mt-4 inline-block">
                <i class="fas fa-arrow-left mr-1"></i>Back to Member Management
            </a>
        </div>
    <?php else: ?>
        <!-- Found <?php echo count($groupedDuplicates); ?> groups to display -->
        <div class="bg-blue-100 border-l-4 border-blue-500 p-4 mb-6">
            <p class="font-semibold text-blue-800">
                <i class="fas fa-info-circle mr-2"></i>
                Displaying <?php echo count($groupedDuplicates); ?> duplicate groups below...
            </p>
        </div>
        <?php 
        $groupCounter = 0;
        foreach ($groupedDuplicates as $key => $group): 
            $groupCounter++;
            $keyParts = explode('|', $key);
            $firstName = $keyParts[0] ?? '';
            $lastName = $keyParts[1] ?? '';
            $dob = $keyParts[2] ?? 'N/A';
        ?>
            <div class="bg-white rounded-lg shadow-lg overflow-hidden mb-6 border-l-4 border-yellow-500">
                <div class="bg-gradient-to-r from-yellow-500 to-orange-500 px-6 py-4">
                    <div class="flex justify-between items-center">
                        <div class="text-white">
                            <h3 class="text-xl font-bold">
                                <i class="fas fa-exclamation-triangle mr-2"></i>
                                <?php echo htmlspecialchars($firstName . ' ' . $lastName); ?>
                            </h3>
                            <p class="text-sm mt-1">
                                <i class="fas fa-calendar mr-1"></i>Date of Birth: <?php echo htmlspecialchars($dob); ?> 
                                <span class="ml-4"><i class="fas fa-clone mr-1"></i><?php echo count($group); ?> duplicate(s) found</span>
                            </p>
                        </div>
                        <div class="flex gap-2">
                            <button type="button" onclick="selectAllInGroup('group_<?php echo md5($key); ?>')" 
                                    class="bg-white text-yellow-600 px-4 py-2 rounded-lg hover:bg-yellow-50 transition font-semibold text-sm">
                                <i class="fas fa-check-square mr-1"></i>Select All
                            </button>
                            <button type="button" onclick="deleteSelectedInGroup('group_<?php echo md5($key); ?>')" 
                                    class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition font-semibold text-sm">
                                <i class="fas fa-trash mr-1"></i>Delete Selected
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="overflow-x-auto">
                    <form class="duplicate-form" data-group="group_<?php echo md5($key); ?>">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    <input type="checkbox" class="group-select-all rounded" data-group="group_<?php echo md5($key); ?>">
                                </th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Member Details</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Contact</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Location</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Account Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Created</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($group as $member): ?>
                                <tr class="<?php echo empty($member['account_id']) ? 'bg-red-50' : 'hover:bg-gray-50'; ?> transition">
                                    <td class="px-4 py-4 whitespace-nowrap">
                                        <input type="checkbox" name="member_ids[]" value="<?php echo $member['id']; ?>" 
                                               class="duplicate-checkbox rounded" 
                                               data-group="group_<?php echo md5($key); ?>"
                                               data-has-account="<?php echo !empty($member['account_id']) ? '1' : '0'; ?>">
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="flex items-center">
                                            <img src="<?php echo !empty($member['profile_photo']) ? BASE_URL . 'uploads/members/' . $member['profile_photo'] : BASE_URL . 'assets/images/default-avatar.png'; ?>" 
                                                 alt="<?php echo htmlspecialchars($member['first_name']); ?>"
                                                 class="w-12 h-12 rounded-full object-cover mr-3 border-2 border-yellow-200">
                                            <div>
                                                <div class="font-semibold text-gray-800">
                                                    <?php echo htmlspecialchars(($member['title'] ?? '') . ' ' . $member['first_name'] . ' ' . ($member['middle_name'] ?? '') . ' ' . $member['last_name']); ?>
                                                </div>
                                                <div class="text-sm text-gray-500">
                                                    <?php echo htmlspecialchars($member['member_type']); ?> • 
                                                    <?php echo htmlspecialchars($member['gender']); ?>
                                                </div>
                                                <div class="text-xs text-gray-400">ID: <?php echo $member['id']; ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm">
                                            <div class="text-gray-800">
                                                <i class="fas fa-phone text-yellow-500 mr-1"></i>
                                                <?php echo htmlspecialchars($member['phone'] ?: 'N/A'); ?>
                                            </div>
                                            <div class="text-gray-500 mt-1">
                                                <i class="fas fa-envelope text-yellow-500 mr-1"></i>
                                                <?php echo htmlspecialchars($member['email'] ?: 'N/A'); ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm">
                                            <div class="text-gray-800 font-medium">
                                                <?php echo htmlspecialchars($member['assembly_name']); ?>
                                            </div>
                                            <div class="text-gray-500 text-xs mt-1">
                                                <?php echo htmlspecialchars($member['district_name']); ?>
                                            </div>
                                            <div class="text-gray-400 text-xs">
                                                <?php echo htmlspecialchars($member['area_name']); ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <?php if (!empty($member['account_id'])): ?>
                                            <div class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800">
                                                <i class="fas fa-check-circle mr-1"></i>Has Account
                                            </div>
                                            <div class="text-xs text-gray-500 mt-1">
                                                @<?php echo htmlspecialchars($member['username']); ?>
                                            </div>
                                        <?php else: ?>
                                            <div class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-red-100 text-red-800">
                                                <i class="fas fa-times-circle mr-1"></i>No Account
                                            </div>
                                            <div class="text-xs text-gray-500 mt-1">Account not created</div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-800">
                                            <?php echo date('M d, Y', strtotime($member['created_at'])); ?>
                                        </div>
                                        <div class="text-xs text-gray-500">
                                            <?php echo date('h:i A', strtotime($member['created_at'])); ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm">
                                        <div class="flex space-x-2">
                                            <a href="view.php?id=<?php echo $member['id']; ?>" 
                                               class="text-blue-600 hover:text-blue-800 transition" 
                                               title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="edit.php?id=<?php echo $member['id']; ?>" 
                                               class="text-yellow-600 hover:text-yellow-800 transition" 
                                               title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button onclick="deleteMember(<?php echo $member['id']; ?>)" 
                                                    class="text-red-600 hover:text-red-800 transition" 
                                                    title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    </form>
                </div>
            </div>
        <?php endforeach; ?>
        <div class="bg-green-100 border-l-4 border-green-500 p-4 mb-6">
            <p class="font-semibold text-green-800">
                <i class="fas fa-check-circle mr-2"></i>
                Successfully displayed <?php echo $groupCounter; ?> duplicate groups.
            </p>
        </div>
    <?php endif; ?>
    
    <!-- Legend -->
    <?php if (!empty($groupedDuplicates)): ?>
    <div class="bg-white rounded-lg shadow-lg p-6">
        <h4 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-info-circle mr-2 text-blue-500"></i>Legend
        </h4>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="flex items-center">
                <div class="w-4 h-4 bg-red-50 border border-red-200 rounded mr-3"></div>
                <span class="text-sm text-gray-700">Member without account (highlighted in red)</span>
            </div>
            <div class="flex items-center">
                <div class="w-4 h-4 bg-white border border-gray-200 rounded mr-3"></div>
                <span class="text-sm text-gray-700">Member with account</span>
            </div>
        </div>
        <div class="mt-4 p-4 bg-yellow-50 border-l-4 border-yellow-500 rounded">
            <p class="text-sm text-gray-700 mb-3">
                <i class="fas fa-lightbulb text-yellow-500 mr-2"></i>
                <strong>Note:</strong> Duplicates are identified by matching first name, last name, and date of birth. 
                Review each entry carefully before taking action. Members highlighted in red don't have login accounts yet.
            </p>
            <p class="text-sm text-gray-700">
                <i class="fas fa-info-circle text-blue-500 mr-2"></i>
                <strong>Deletion Options:</strong> Use checkboxes to select specific members, "Select All" in each group to select all duplicates in that group, 
                "Select All Duplicates" to select across all groups, or "Select All Without Accounts" to select only highlighted members without login accounts. 
                Click "Delete Selected" to remove selected members.
            </p>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
    function deleteMember(id) {
        confirmAction('Are you sure you want to delete this member? This action cannot be undone.', function() {
            window.location.href = 'delete.php?id=' + id;
        });
    }

    // Select all checkboxes in a specific group
    function selectAllInGroup(groupId) {
        const checkboxes = document.querySelectorAll(`input.duplicate-checkbox[data-group="${groupId}"]`);
        checkboxes.forEach(cb => cb.checked = true);
    }

    // Delete selected members in a specific group
    function deleteSelectedInGroup(groupId) {
        const checkboxes = document.querySelectorAll(`input.duplicate-checkbox[data-group="${groupId}"]:checked`);
        const memberIds = Array.from(checkboxes).map(cb => cb.value);
        
        if (memberIds.length === 0) {
            alert('Please select at least one member to delete.');
            return;
        }
        
        confirmAction(`Are you sure you want to delete ${memberIds.length} selected member(s)? This action cannot be undone.`, function() {
            deleteMembersById(memberIds);
        });
    }

    // Select all duplicates across all groups
    function selectAllDuplicates() {
        const checkboxes = document.querySelectorAll('input.duplicate-checkbox');
        checkboxes.forEach(cb => cb.checked = true);
    }

    // Select all members without accounts (highlighted in red)
    function selectAllWithoutAccounts() {
        // First, deselect all checkboxes
        const allCheckboxes = document.querySelectorAll('input.duplicate-checkbox');
        console.log('Total checkboxes found:', allCheckboxes.length);
        allCheckboxes.forEach(cb => cb.checked = false);
        
        // Then select only those without accounts
        const checkboxes = document.querySelectorAll('input.duplicate-checkbox[data-has-account="0"]');
        console.log('Checkboxes without accounts:', checkboxes.length);
        let count = 0;
        let memberIds = [];
        checkboxes.forEach(cb => {
            cb.checked = true;
            memberIds.push(cb.value);
            count++;
        });
        console.log('Selected member IDs without accounts:', memberIds);
        alert(`Selected ${count} member(s) without accounts.`);
    }

    // Deselect all duplicates
    function deselectAllDuplicates() {
        const checkboxes = document.querySelectorAll('input.duplicate-checkbox');
        checkboxes.forEach(cb => cb.checked = false);
    }

    // Delete all selected members across all groups
    function deleteAllSelected() {
        const checkboxes = document.querySelectorAll('input.duplicate-checkbox:checked');
        const memberIds = Array.from(checkboxes).map(cb => cb.value);
        
        if (memberIds.length === 0) {
            alert('Please select at least one member to delete.');
            return;
        }
        
        confirmAction(`Are you sure you want to delete ${memberIds.length} selected member(s)? This action cannot be undone.`, function() {
            deleteMembersById(memberIds);
        });
    }

    // Handle bulk deletion via POST request
    function deleteMembersById(memberIds) {
        console.log('Attempting to delete member IDs:', memberIds);
        
        if (!memberIds || memberIds.length === 0) {
            alert('No members selected for deletion.');
            return;
        }
        
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'delete-duplicates.php';
        
        memberIds.forEach(id => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'member_ids[]';
            input.value = id;
            form.appendChild(input);
        });
        
        document.body.appendChild(form);
        console.log('Submitting form with', memberIds.length, 'member(s)');
        form.submit();
    }

    // Handle group select all checkbox
    document.addEventListener('DOMContentLoaded', function() {
        // Group select all functionality
        const groupSelectAlls = document.querySelectorAll('.group-select-all');
        groupSelectAlls.forEach(selectAll => {
            selectAll.addEventListener('change', function() {
                const groupId = this.dataset.group;
                const checkboxes = document.querySelectorAll(`input.duplicate-checkbox[data-group="${groupId}"]`);
                checkboxes.forEach(cb => cb.checked = this.checked);
            });
        });

        // Update group select all when individual checkboxes change
        const duplicateCheckboxes = document.querySelectorAll('.duplicate-checkbox');
        duplicateCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const groupId = this.dataset.group;
                const groupCheckboxes = document.querySelectorAll(`input.duplicate-checkbox[data-group="${groupId}"]`);
                const selectAllCheckbox = document.querySelector(`.group-select-all[data-group="${groupId}"]`);
                
                if (selectAllCheckbox) {
                    const allChecked = Array.from(groupCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                }
            });
        });

        // Filter Assembly options based on selected District
        var districtSelect = document.getElementById('filterDistrictSelect');
        var assemblySelect = document.getElementById('filterAssemblySelect');
        if (!districtSelect || !assemblySelect) return;

        function filterAssemblyOptions() {
            var selectedDistrict = districtSelect.value;
            var options = assemblySelect.querySelectorAll('option');
            options.forEach(function(opt) {
                if (!opt.dataset.districtId) {
                    opt.style.display = '';
                    return;
                }
                if (selectedDistrict === '' || opt.dataset.districtId === selectedDistrict) {
                    opt.style.display = '';
                } else {
                    opt.style.display = 'none';
                }
            });
        }

        filterAssemblyOptions();
        districtSelect.addEventListener('change', function() {
            assemblySelect.value = '';
            filterAssemblyOptions();
        });
    });
</script>

</main>

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

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists