<?php
include '../db.php';
include 'binary_search.php';

session_start();

// Admin authentication check
if (!isset($_SESSION['mpid']) || $_SESSION['mpid'] !== 1) {
    header("Location: http://localhost/LoanApprovalPredction/admin.php");
    exit();
}

$mpid = $_SESSION['mpid'];
$Limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 8;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $Limit;
$isSearch = isset($_GET['search']) && !empty(trim($_GET['search']));
$isAjax = isset($_GET['ajax']);

// Handle Edit Member
if (isset($_POST['edit_member'])) {
    $edit_id = (int)$_POST['edit_id'];
    $name = mysqli_real_escape_string($conn, trim($_POST['name']));
    $position = (int)$_POST['position'];
    $email = mysqli_real_escape_string($conn, trim($_POST['email']));
    $phone = mysqli_real_escape_string($conn, trim($_POST['phone']));
    $address = mysqli_real_escape_string($conn, trim($_POST['address']));

    $update_sql = "UPDATE members SET MembersName='$name', MPid=$position, Email='$email', PhoneNo='$phone', Address='$address' 
                   WHERE Mid=$edit_id AND Email <> 'agyat@gmail.com'";
    if (mysqli_query($conn, $update_sql)) {
        $_SESSION['upm'] = "<div class='fixed top-4 right-4 z-50 flex items-center p-4 mb-4 text-sm text-green-800 rounded-lg bg-green-50 animate-fade-in-down' role='alert'>
                              <i class='fas fa-check-circle mr-2'></i>
                              <div>Member updated successfully!</div>
                            </div>";
    } else {
        $_SESSION['upm'] = "<div class='fixed top-4 right-4 z-50 flex items-center p-4 mb-4 text-sm text-red-800 rounded-lg bg-red-50 animate-fade-in-down' role='alert'>
                              <i class='fas fa-exclamation-circle mr-2'></i>
                              <div>Error updating member: " . mysqli_error($conn) . "</div>
                            </div>";
    }

    header("Location: members.php?" . http_build_query([
        'page' => $_GET['page'] ?? 1,
        'search' => $_GET['search'] ?? '',
        'search_field' => $_GET['search_field'] ?? 'MembersName',
        'limit' => $_GET['limit'] ?? 8
    ]));
    exit();
}

// Handle Delete Member
if (isset($_GET['delete'])) {
    $del_id = (int)$_GET['delete'];
    $del_sql = "DELETE FROM members WHERE Mid = $del_id AND Email <> 'agyat@gmail.com'";
    if (mysqli_query($conn, $del_sql)) {
        $_SESSION['delete'] = "<div class='fixed top-4 right-4 z-50 flex items-center p-4 mb-4 text-sm text-green-800 rounded-lg bg-green-50 animate-fade-in-down' role='alert'>
                              <i class='fas fa-check-circle mr-2'></i>
                              <div>Member deleted successfully!</div>
                            </div>";
    } else {
        $_SESSION['delete'] = "<div class='fixed top-4 right-4 z-50 flex items-center p-4 mb-4 text-sm text-red-800 rounded-lg bg-red-50 animate-fade-in-down' role='alert'>
                              <i class='fas fa-exclamation-circle mr-2'></i>
                              <div>Error deleting member: " . mysqli_error($conn) . "</div>
                            </div>";
    }

    header("Location: members.php?" . http_build_query([
        'page' => $_GET['page'] ?? 1,
        'search' => $_GET['search'] ?? '',
        'search_field' => $_GET['search_field'] ?? 'MembersName',
        'limit' => $_GET['limit'] ?? 8
    ]));
    exit();
}

// --- Search Handling Logic ---
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$search_field = isset($_GET['search_field']) ? trim($_GET['search_field']) : 'MembersName';
$valid_fields = ['MembersName', 'PhoneNo', 'Address', 'MPid'];

if (!in_array($search_field, $valid_fields)) {
    $search_field = 'MembersName';
}

$resultArray = [];
$totalRecords = 0;

if (!empty($search)) {
    $isSearch = true;
    $search_value = $search;

    if ($search_field === 'MPid') {
        if (strtolower($search) === 'admin') {
            $search_value = 1;
        } elseif (strtolower($search) === 'member') {
            $search_value = 2;
        } else {
            $search_value = (int)$search;
        }
    }

    $allMembersSql = "SELECT members.*, position.Position FROM members 
                      JOIN position ON members.MPid = position.Pid 
                      WHERE Email <> 'ritik.rauniyar22@gmai.com' AND MembersName <> 'Ritik Rauniyar'";
    $allMembersResult = mysqli_query($conn, $allMembersSql);
    $membersArray = [];
    while ($row = mysqli_fetch_assoc($allMembersResult)) {
        $membersArray[] = $row;
    }

    usort($membersArray, function($a, $b) use ($search_field) {
        if ($search_field === 'MPid') {
            return $a[$search_field] <=> $b[$search_field];
        }
        return strcmp($a[$search_field], $b[$search_field]);
    });

    $resultArray = binarySearch($membersArray, $search_value, $search_field);

    if (empty($resultArray) && $search_field !== 'MPid') {
        $escaped = mysqli_real_escape_string($conn, $search);
        $searchQuery = "AND (members.$search_field LIKE '%$escaped%')";
        $sql = "SELECT members.*, position.Position FROM members 
                JOIN position ON members.MPid = position.Pid 
                WHERE Email <> 'ritik.rauniyar22@gmai.com' AND MembersName <> 'Ritik Rauniyar' $searchQuery 
                LIMIT $offset, $Limit";
        $result = mysqli_query($conn, $sql);
        while ($row = mysqli_fetch_assoc($result)) {
            $resultArray[] = $row;
        }
    }

    // Get total records count
    if ($search_field === 'MPid') {
        $totalQuery = "SELECT COUNT(*) AS total FROM members 
                       JOIN position ON members.MPid = position.Pid 
                       WHERE Email <> 'ritik.rauniyar22@gmai.com' AND MembersName <> 'Ritik Rauniyar' 
                       AND members.MPid = " . (int)$search_value;
    } else {
        $escaped = mysqli_real_escape_string($conn, $search);
        $totalQuery = "SELECT COUNT(*) AS total FROM members 
                       JOIN position ON members.MPid = position.Pid 
                       WHERE Email <> 'ritik.rauniyar22@gmai.com' AND MembersName <> 'Ritik Rauniyar' 
                       AND (members.$search_field LIKE '%$escaped%')";
    }
    $totalResult = mysqli_query($conn, $totalQuery);
    $totalRow = mysqli_fetch_assoc($totalResult);
    $totalRecords = $totalRow['total'];
} else {
    // Default query when no search is performed
    $sql = "SELECT members.*, position.Position FROM members 
            JOIN position ON members.MPid = position.Pid 
            WHERE Email <> 'ritik.rauniyar22@gmai.com' AND MembersName <> 'Ritik Rauniyar' 
            LIMIT $offset, $Limit";
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        $resultArray[] = $row;
    }

    $totalQuery = "SELECT COUNT(*) AS total FROM members 
                   WHERE Email <> 'ritik.rauniyar22@gmai.com' AND MembersName <> 'Ritik Rauniyar'";
    $totalResult = mysqli_query($conn, $totalQuery);
    $totalRow = mysqli_fetch_assoc($totalResult);
    $totalRecords = $totalRow['total'];
}

$Total_page = ceil($totalRecords / $Limit);

// Fetch positions for dropdown
$position_sql = "SELECT * FROM position";
$position_result = mysqli_query($conn, $position_sql);

// If AJAX request, return only the member list HTML
if ($isAjax) {
    ob_start();
    if (!empty($resultArray)): ?>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            <?php foreach ($resultArray as $row): 
                $position = $row['Position'];
                $statusClass = ($row['status'] === 'leave') ? 'border-red-200 bg-red-50' : 'border-gray-200 bg-white';
                $badgeClass = ($row['MPid'] == 1) ? 'badge-admin' : 'badge-member';
                $statusBadge = ($row['status'] === 'leave') ? '<span class="badge badge-inactive ml-2">Inactive</span>' : '';
            ?>
            <div class="rounded-xl overflow-hidden shadow-sm border <?= $statusClass ?> card-hover transition-all">
                <div class="relative">
                    <img src="../<?= htmlspecialchars($row['image'] ?? 'images/default-avatar.jpg') ?>" 
                         class="w-full h-48 object-cover" 
                         alt="<?= htmlspecialchars($row['MembersName']) ?>">
                    <div class="absolute top-3 right-3">
                        <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($position) ?></span>
                        <?= $statusBadge ?>
                    </div>
                </div>
                
                <div class="p-5">
                    <h3 class="text-lg font-semibold text-gray-800 mb-1"><?= htmlspecialchars($row['MembersName']) ?></h3>
                    
                    <div class="flex items-center text-sm text-gray-600 mb-2">
                        <i class="fas fa-envelope mr-2 text-blue-500"></i>
                        <span class="truncate"><?= htmlspecialchars($row['Email']) ?></span>
                    </div>
                    
                    <div class="flex items-center text-sm text-gray-600 mb-2">
                        <i class="fas fa-phone-alt mr-2 text-green-500"></i>
                        <span><?= htmlspecialchars($row['PhoneNo']) ?></span>
                    </div>
                    
                    <div class="flex items-start text-sm text-gray-600 mb-4">
                        <i class="fas fa-map-marker-alt mr-2 text-red-500 mt-0.5"></i>
                        <span class="flex-1"><?= htmlspecialchars($row['Address']) ?></span>
                    </div>
                    
                    <div class="flex justify-between border-t pt-3">
                        <button onclick="openEditModal(<?= $row['Mid'] ?>, '<?= addslashes(htmlspecialchars($row['MembersName'])) ?>', <?= $row['MPid'] ?>, '<?= addslashes(htmlspecialchars($row['Email'])) ?>', '<?= addslashes(htmlspecialchars($row['PhoneNo'])) ?>', '<?= addslashes(htmlspecialchars($row['Address'])) ?>')" 
                                class="text-blue-600 hover:text-blue-800 font-medium text-sm flex items-center transition-all">
                            <i class="fas fa-edit mr-1"></i> Edit
                        </button>
                        <a href="members.php?delete=<?= $row['Mid'] ?>&search=<?= urlencode($search) ?>&search_field=<?= urlencode($search_field) ?>&page=<?= $page ?>&limit=<?= $Limit ?>" 
                           onclick="return confirm('Are you sure you want to delete this member?')" 
                           class="text-red-600 hover:text-red-800 font-medium text-sm flex items-center transition-all">
                            <i class="fas fa-trash-alt mr-1"></i> Delete
                        </a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="bg-white rounded-xl shadow-sm p-12 text-center">
            <div class="mx-auto w-24 h-24 mb-4 text-gray-400">
                <i class="fas fa-search text-6xl"></i>
            </div>
            <h3 class="text-lg font-medium text-gray-900 mb-2">No members found</h3>
            <p class="text-gray-600">Try adjusting your search query</p>
        </div>
    <?php endif;
    echo ob_get_clean();
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Member Management | Loan Approval Prediction</title>
    <link rel="icon" href="../images/Icon.png">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .animate-fade-in-down {
            animation: fadeInDown 0.3s ease-out;
        }
        .card-hover:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }
        .transition-all {
            transition: all 0.3s ease;
        }
        .badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            border-radius: 0.5rem;
        }
        .badge-admin {
            background-color: #3B82F6;
            color: white;
        }
        .badge-member {
            background-color: #10B981;
            color: white;
        }
        .badge-inactive {
            background-color: #EF4444;
            color: white;
        }
        .search-active .non-search-content {
            display: none;
        }
        .search-active .search-content {
            display: block;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen <?= $isSearch ? 'search-active' : '' ?>">
    <!-- Single Navigation Bar -->
     <?php include '../includes/newnavbar.php'; ?>
    <nav class="bg-white shadow-lg sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16 items-center">
                <div class="flex items-center">
                    
                    <span class="text-xl font-semibold text-gray-800">Member Management</span>
                </div>
                
                <div class="flex items-center space-x-4">
                    <div class="relative flex items-center bg-gray-100 rounded-lg">
                        <select id="searchField" class="appearance-none bg-transparent border-0 pl-3 pr-8 py-2 focus:outline-none focus:ring-0">
                            <option value="MembersName" <?= $search_field == 'MembersName' ? 'selected' : '' ?>>Name</option>
                            <option value="PhoneNo" <?= $search_field == 'PhoneNo' ? 'selected' : '' ?>>Phone</option>
                            <option value="Address" <?= $search_field == 'Address' ? 'selected' : '' ?>>Address</option>
                            <option value="MPid" <?= $search_field == 'MPid' ? 'selected' : '' ?>>Position</option>
                        </select>
                        <div class="absolute right-0 flex items-center pr-2 pointer-events-none">
                            <i class="fas fa-chevron-down text-gray-500"></i>
                        </div>
                    </div>
                    
                    <div class="relative flex-grow w-64">
                        <input type="text" id="searchInput" value="<?= htmlspecialchars($search) ?>" placeholder="Search..." 
                               class="w-full px-4 py-2 border-0 bg-gray-100 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <button id="clearSearch" class="absolute right-3 top-2 text-gray-500 hover:text-gray-700 <?= empty($search) ? 'hidden' : '' ?>">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <a href="add_member.php" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-all flex items-center">
                        <i class="fas fa-user-plus mr-2"></i> Add Member
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <!-- Flash Messages -->
        <div class="flash-messages space-y-2">
            <?php
            foreach (['adduser', 'upm', 'unadduser', 'delete'] as $msg) {
                if (isset($_SESSION[$msg])) {
                    echo $_SESSION[$msg];
                    unset($_SESSION[$msg]);
                }
            }
            ?>
        </div>

        <!-- Non-search content -->
        <div class="non-search-content <?= $isSearch ? 'hidden' : '' ?>">
            <div class="bg-white rounded-xl shadow-sm p-6 mb-8">
                <h2 class="text-2xl font-bold text-gray-800 mb-2">Member Directory</h2>
                <p class="text-gray-600">Browse through all committee members or use the search bar to find specific members.</p>
            </div>

            <!-- Member Grid -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                <?php foreach ($resultArray as $row): 
                    $position = $row['Position'];
                    $statusClass = ($row['status'] === 'leave') ? 'border-red-200 bg-red-50' : 'border-gray-200 bg-white';
                    $badgeClass = ($row['MPid'] == 1) ? 'badge-admin' : 'badge-member';
                    $statusBadge = ($row['status'] === 'leave') ? '<span class="badge badge-inactive ml-2">Inactive</span>' : '';
                ?>
                <div class="rounded-xl overflow-hidden shadow-sm border <?= $statusClass ?> card-hover transition-all">
                    <div class="relative">
                        <img src="../<?= htmlspecialchars($row['image'] ?? 'images/default-avatar.jpg') ?>" 
                             class="w-full h-48 object-cover" 
                             alt="<?= htmlspecialchars($row['MembersName']) ?>">
                        <div class="absolute top-3 right-3">
                            <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($position) ?></span>
                            <?= $statusBadge ?>
                        </div>
                    </div>
                    
                    <div class="p-5">
                        <h3 class="text-lg font-semibold text-gray-800 mb-1"><?= htmlspecialchars($row['MembersName']) ?></h3>
                        
                        <div class="flex items-center text-sm text-gray-600 mb-2">
                            <i class="fas fa-envelope mr-2 text-blue-500"></i>
                            <span class="truncate"><?= htmlspecialchars($row['Email']) ?></span>
                        </div>
                        
                        <div class="flex items-center text-sm text-gray-600 mb-2">
                            <i class="fas fa-phone-alt mr-2 text-green-500"></i>
                            <span><?= htmlspecialchars($row['PhoneNo']) ?></span>
                        </div>
                        
                        <div class="flex items-start text-sm text-gray-600 mb-4">
                            <i class="fas fa-map-marker-alt mr-2 text-red-500 mt-0.5"></i>
                            <span class="flex-1"><?= htmlspecialchars($row['Address']) ?></span>
                        </div>
                        
                        <div class="flex justify-between border-t pt-3">
                            <button onclick="openEditModal(<?= $row['Mid'] ?>, '<?= addslashes(htmlspecialchars($row['MembersName'])) ?>', <?= $row['MPid'] ?>, '<?= addslashes(htmlspecialchars($row['Email'])) ?>', '<?= addslashes(htmlspecialchars($row['PhoneNo'])) ?>', '<?= addslashes(htmlspecialchars($row['Address'])) ?>')" 
                                    class="text-blue-600 hover:text-blue-800 font-medium text-sm flex items-center transition-all">
                                <i class="fas fa-edit mr-1"></i> Edit
                            </button>
                            <a href="members.php?delete=<?= $row['Mid'] ?>&page=<?= $page ?>&limit=<?= $Limit ?>" 
                               onclick="return confirm('Are you sure you want to delete this member?')" 
                               class="text-red-600 hover:text-red-800 font-medium text-sm flex items-center transition-all">
                                <i class="fas fa-trash-alt mr-1"></i> Delete
                            </a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Pagination -->
            <div class="mt-8 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div class="text-sm text-gray-600">
                    Showing <span class="font-medium"><?= $offset + 1 ?></span> to <span class="font-medium"><?= min($offset + $Limit, $totalRecords) ?></span> of <span class="font-medium"><?= $totalRecords ?></span> members
                </div>
                
                <div class="flex items-center gap-1">
                    <?php if ($page > 1): ?>
                        <a href="members.php?page=<?= $page - 1 ?>&limit=<?= $Limit ?>" 
                           class="px-3 py-1 border rounded-lg text-gray-700 hover:bg-gray-100 transition-all">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    <?php endif; ?>
                    
                    <?php 
                    // Show first page
                    if ($page > 3): ?>
                        <a href="members.php?page=1&limit=<?= $Limit ?>" 
                           class="px-3 py-1 border rounded-lg text-gray-700 hover:bg-gray-100 transition-all">
                            1
                        </a>
                        <?php if ($page > 4): ?>
                            <span class="px-2">...</span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php 
                    // Show pages around current page
                    for ($i = max(1, $page - 2); $i <= min($Total_page, $page + 2); $i++): ?>
                        <a href="members.php?page=<?= $i ?>&limit=<?= $Limit ?>" 
                           class="px-3 py-1 border rounded-lg <?= ($i == $page ? 'bg-blue-600 text-white border-blue-600' : 'text-gray-700 hover:bg-gray-100') ?> transition-all">
                            <?= $i ?>
                        </a>
                    <?php endfor; ?>
                    
                    <?php 
                    // Show last page
                    if ($page < $Total_page - 2): ?>
                        <?php if ($page < $Total_page - 3): ?>
                            <span class="px-2">...</span>
                        <?php endif; ?>
                        <a href="members.php?page=<?= $Total_page ?>&limit=<?= $Limit ?>" 
                           class="px-3 py-1 border rounded-lg text-gray-700 hover:bg-gray-100 transition-all">
                            <?= $Total_page ?>
                        </a>
                    <?php endif; ?>
                    
                    <?php if ($page < $Total_page): ?>
                        <a href="members.php?page=<?= $page + 1 ?>&limit=<?= $Limit ?>" 
                           class="px-3 py-1 border rounded-lg text-gray-700 hover:bg-gray-100 transition-all">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Search content -->
        <div class="search-content <?= !$isSearch ? 'hidden' : '' ?>">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-semibold text-gray-800">
                  
                </h2>
                <a href="members.php" class="text-blue-600 hover:text-blue-800 flex items-center">
                    <i class="fas fa-times mr-1"></i> Clear Search
                </a>
            </div>

            <div id="searchResultsContainer">
                <?php if (!empty($resultArray)): ?>
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                        <?php foreach ($resultArray as $row): 
                            $position = $row['Position'];
                            $statusClass = ($row['status'] === 'leave') ? 'border-red-200 bg-red-50' : 'border-gray-200 bg-white';
                            $badgeClass = ($row['MPid'] == 1) ? 'badge-admin' : 'badge-member';
                            $statusBadge = ($row['status'] === 'leave') ? '<span class="badge badge-inactive ml-2">Inactive</span>' : '';
                        ?>
                        <div class="rounded-xl overflow-hidden shadow-sm border <?= $statusClass ?> card-hover transition-all">
                            <div class="relative">
                                <img src="../<?= htmlspecialchars($row['image'] ?? 'images/default-avatar.jpg') ?>" 
                                     class="w-full h-48 object-cover" 
                                     alt="<?= htmlspecialchars($row['MembersName']) ?>">
                                <div class="absolute top-3 right-3">
                                    <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($position) ?></span>
                                    <?= $statusBadge ?>
                                </div>
                            </div>
                            
                            <div class="p-5">
                                <h3 class="text-lg font-semibold text-gray-800 mb-1"><?= htmlspecialchars($row['MembersName']) ?></h3>
                                
                                <div class="flex items-center text-sm text-gray-600 mb-2">
                                    <i class="fas fa-envelope mr-2 text-blue-500"></i>
                                    <span class="truncate"><?= htmlspecialchars($row['Email']) ?></span>
                                </div>
                                
                                <div class="flex items-center text-sm text-gray-600 mb-2">
                                    <i class="fas fa-phone-alt mr-2 text-green-500"></i>
                                    <span><?= htmlspecialchars($row['PhoneNo']) ?></span>
                                </div>
                                
                                <div class="flex items-start text-sm text-gray-600 mb-4">
                                    <i class="fas fa-map-marker-alt mr-2 text-red-500 mt-0.5"></i>
                                    <span class="flex-1"><?= htmlspecialchars($row['Address']) ?></span>
                                </div>
                                
                                <div class="flex justify-between border-t pt-3">
                                    <button onclick="openEditModal(<?= $row['Mid'] ?>, '<?= addslashes(htmlspecialchars($row['MembersName'])) ?>', <?= $row['MPid'] ?>, '<?= addslashes(htmlspecialchars($row['Email'])) ?>', '<?= addslashes(htmlspecialchars($row['PhoneNo'])) ?>', '<?= addslashes(htmlspecialchars($row['Address'])) ?>')" 
                                            class="text-blue-600 hover:text-blue-800 font-medium text-sm flex items-center transition-all">
                                        <i class="fas fa-edit mr-1"></i> Edit
                                    </button>
                                    <a href="members.php?delete=<?= $row['Mid'] ?>&search=<?= urlencode($search) ?>&search_field=<?= urlencode($search_field) ?>&page=<?= $page ?>&limit=<?= $Limit ?>" 
                                       onclick="return confirm('Are you sure you want to delete this member?')" 
                                       class="text-red-600 hover:text-red-800 font-medium text-sm flex items-center transition-all">
                                        <i class="fas fa-trash-alt mr-1"></i> Delete
                                    </a>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="bg-white rounded-xl shadow-sm p-12 text-center">
                        <div class="mx-auto w-24 h-24 mb-4 text-gray-400">
                            <i class="fas fa-search text-6xl"></i>
                        </div>
                        <h3 class="text-lg font-medium text-gray-900 mb-2">No members found</h3>
                        <p class="text-gray-600">Try adjusting your search query</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <!-- Edit Modal -->
    <div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md transform transition-all duration-300 scale-95 opacity-0" id="modalContent">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-bold text-gray-900">Edit Member</h3>
                    <button onclick="closeEditModal()" class="text-gray-400 hover:text-gray-500">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <form action="members.php" method="POST">
                    <input type="hidden" name="edit_id" id="edit_id">
                    <input type="hidden" name="page" value="<?= $page ?>">
                    <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
                    <input type="hidden" name="search_field" value="<?= htmlspecialchars($search_field) ?>">
                    <input type="hidden" name="limit" value="<?= $Limit ?>">
                    
                    <div class="space-y-4">
                        <div>
                            <label for="edit_name" class="block text-sm font-medium text-gray-700 mb-1">Full Name</label>
                            <input type="text" name="name" id="edit_name" required 
                                   class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 py-2 px-3 border">
                        </div>
                        
                        <div>
                            <label for="edit_position" class="block text-sm font-medium text-gray-700 mb-1">Position</label>
                            <select name="position" id="edit_position" required 
                                    class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 py-2 px-3 border">
                                <?php while ($pos = mysqli_fetch_assoc($position_result)): ?>
                                    <option value="<?= $pos['Pid'] ?>"><?= htmlspecialchars($pos['Position']) ?></option>
                                <?php endwhile; mysqli_data_seek($position_result, 0); ?>
                            </select>
                        </div>
                        
                        <div>
                            <label for="edit_email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                            <input type="email" name="email" id="edit_email" required 
                                   class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 py-2 px-3 border">
                        </div>
                        
                        <div>
                            <label for="edit_phone" class="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                            <input type="text" name="phone" id="edit_phone" required 
                                   class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 py-2 px-3 border">
                        </div>
                        
                        <div>
                            <label for="edit_address" class="block text-sm font-medium text-gray-700 mb-1">Address</label>
                            <textarea name="address" id="edit_address" rows="3" required 
                                      class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 py-2 px-3 border"></textarea>
                        </div>
                    </div>
                    
                    <div class="mt-6 flex justify-end gap-3">
                        <button type="button" onclick="closeEditModal()" 
                                class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-all">
                            Cancel
                        </button>
                        <button type="submit" name="edit_member" 
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-all">
                            Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Toggle search mode
        function toggleSearchMode() {
            const searchValue = document.getElementById('searchInput').value.trim();
            if (searchValue.length > 0) {
                document.body.classList.add('search-active');
                document.getElementById('clearSearch').classList.remove('hidden');
            } else {
                document.body.classList.remove('search-active');
                document.getElementById('clearSearch').classList.add('hidden');
            }
        }

        // Initialize search mode on page load
        toggleSearchMode();

        // Debounce function for search
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }

        // Perform search
        const performSearch = debounce(function() {
            const searchValue = document.getElementById('searchInput').value.trim();
            const searchField = document.getElementById('searchField').value;
            
            if (searchValue.length > 0) {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', `members.php?search=${encodeURIComponent(searchValue)}&search_field=${encodeURIComponent(searchField)}&ajax=1`, true);
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        document.getElementById('searchResultsContainer').innerHTML = xhr.responseText;
                        // Update URL without reloading
                        const newUrl = `members.php?search=${encodeURIComponent(searchValue)}&search_field=${encodeURIComponent(searchField)}`;
                        window.history.pushState({ path: newUrl }, '', newUrl);
                    }
                };
                xhr.send();
            }
        }, 300);

        // Event listeners
        document.getElementById('searchInput').addEventListener('input', function() {
            toggleSearchMode();
            performSearch();
        });

        document.getElementById('clearSearch').addEventListener('click', function(e) {
            e.preventDefault();
            document.getElementById('searchInput').value = '';
            toggleSearchMode();
            window.location.href = 'members.php';
        });

        document.getElementById('searchField').addEventListener('change', function() {
            const searchValue = document.getElementById('searchInput').value.trim();
            if (searchValue.length > 0) {
                performSearch();
            }
        });

        // Handle back/forward navigation
        window.addEventListener('popstate', function() {
            window.location.reload();
        });

        // Modal functions
        function openEditModal(id, name, position, email, phone, address) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_position').value = position;
            document.getElementById('edit_email').value = email;
            document.getElementById('edit_phone').value = phone;
            document.getElementById('edit_address').value = address;
            
            const modal = document.getElementById('editModal');
            const modalContent = document.getElementById('modalContent');
            
            modal.classList.remove('hidden');
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }

        function closeEditModal() {
            const modal = document.getElementById('editModal');
            const modalContent = document.getElementById('modalContent');
            
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            
            setTimeout(() => {
                modal.classList.add('hidden');
            }, 300);
        }

        // Close modal when clicking outside
        document.getElementById('editModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeEditModal();
            }
        });

        // Auto-hide flash messages after 5 seconds
        setTimeout(() => {
            const flashMessages = document.querySelectorAll('.flash-messages > div');
            flashMessages.forEach(msg => {
                msg.style.transition = 'opacity 0.5s ease';
                msg.style.opacity = '0';
                setTimeout(() => msg.remove(), 500);
            });
        }, 5000);
    </script>
</body>
</html>