<?php
include '../db.php';
session_start();

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

$mpid = $_SESSION['mpid'];

$Limit = 5;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $Limit;

// 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='bg-green-100 p-2 text-green-800 rounded'>Member updated successfully!</div>";
    } else {
        $_SESSION['upm'] = "<div class='bg-red-100 p-2 text-red-800 rounded'>Error updating member: " . mysqli_error($conn) . "</div>";
    }
    $redirect_search = isset($_GET['search']) ? '&search=' . urlencode($_GET['search']) : '';
    $redirect_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    header("Location: members.php?page=$redirect_page$redirect_search");
    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='bg-green-100 p-2 text-green-800 rounded'>Member deleted successfully!</div>";
    } else {
        $_SESSION['delete'] = "<div class='bg-red-100 p-2 text-red-800 rounded'>Error deleting member: " . mysqli_error($conn) . "</div>";
    }
    $redirect_search = isset($_GET['search']) ? '&search=' . urlencode($_GET['search']) : '';
    $redirect_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    header("Location: members.php?page=$redirect_page$redirect_search");
    exit();
}

// Handle search
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$searchQuery = '';
if (!empty($search)) {
    $escaped = mysqli_real_escape_string($conn, $search);
    $searchQuery = "AND (members.MembersName LIKE '%$escaped%' OR members.Email LIKE '%$escaped%' OR members.PhoneNo 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);

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

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

// Handle AJAX request
if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    ob_clean(); // Clear any previous output
    if (mysqli_num_rows($result) > 0): ?>
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            <?php while ($row = mysqli_fetch_assoc($result)):
                $position = $row['Position'];
                $border = ($row['status'] === 'leave') ? 'border-red-400' : 'border-gray-400';
            ?>
            <div class="bg-white border <?= $border ?> shadow rounded-xl overflow-hidden relative">
                <img src="../<?= htmlspecialchars($row['image']) ?>" class="w-full h-48 object-cover" alt="Member Image">
                <div class="p-4">
                    <h2 class="text-lg font-bold"><?= htmlspecialchars($row['MembersName']) ?></h2>
                    <p class="text-sm text-gray-600 mb-1">Position: <?= htmlspecialchars($position) ?></p>
                    <p class="text-sm text-gray-600">Email: <?= htmlspecialchars($row['Email']) ?></p>
                    <p class="text-sm text-gray-600">Phone: <?= htmlspecialchars($row['PhoneNo']) ?></p>
                    <p class="text-sm text-gray-600">Address: <?= htmlspecialchars($row['Address']) ?></p>
                    <div class="flex gap-2 mt-3">
                        <a href="members.php?delete=<?= $row['Mid'] ?>&search=<?= urlencode($search) ?>&page=<?= $page ?>" onclick="return confirm('Are you sure?')" class="text-red-600 hover:text-red-800 font-bold">Delete</a>
                        <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-bold">Edit</button>
                    </div>
                </div>
            </div>
            <?php endwhile; ?>
        </div>

        <div class="mt-6 flex justify-center space-x-2">
            <?php if ($page > 1): ?>
                <a href="members.php?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>" class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-800">Prev</a>
            <?php endif; ?>
            <?php for ($i = 1; $i <= $Total_page; $i++): ?>
                <a href="members.php?page=<?= $i ?>&search=<?= urlencode($search) ?>" class="px-3 py-1 <?= ($i == $page ? 'bg-blue-800' : 'bg-blue-600') ?> text-white rounded hover:bg-blue-900"><?= $i ?></a>
            <?php endfor; ?>
            <?php if ($page < $Total_page): ?>
                <a href="members.php?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>" class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-800">Next</a>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="bg-red-100 text-center p-4 rounded mt-6">No data found.</div>
    <?php endif;
    exit();
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Member Management</title>
    <link rel="icon" href="../images/Icon.png">
    <script src="../CSS/tailwindcss.css"></script>
</head>
<body class="bg-green-50 min-h-screen">
    <header class="sticky top-0 z-50">
        <?php include '../includes/newnavbar.php'; ?>
    </header>
    <main class="p-6">
        <?php
        foreach (['adduser', 'upm', 'unadduser', 'delete'] as $msg) {
            if (isset($_SESSION[$msg])) {
                echo $_SESSION[$msg];
                unset($_SESSION[$msg]);
            }
        }
        ?>

        <div class="flex justify-end gap-2 mb-4">
            <input type="search" id="searchInput" value="<?= htmlspecialchars($search) ?>" placeholder="Search by Name, Email or Phone" class="p-2 border rounded-xl bg-gray-200">
            <a href="members.php" class="bg-gray-500 text-white px-4 py-2 rounded-xl hover:bg-black">Clear</a>
        </div>


        <div id="memberList">
        <?php if (mysqli_num_rows($result) > 0): ?>
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            <?php while ($row = mysqli_fetch_assoc($result)):
                $position = $row['Position'];
                $border = ($row['status'] === 'leave') ? 'border-red-400' : 'border-gray-400';
            ?>
            <div class="bg-white border <?= $border ?> shadow rounded-xl overflow-hidden relative">
                <img src="../<?= htmlspecialchars($row['image']) ?>" class="w-full h-48 object-cover" alt="Member Image">
                <div class="p-4">
                    <h2 class="text-lg font-bold"><?= htmlspecialchars($row['MembersName']) ?></h2>
                    <p class="text-sm text-gray-600 mb-1">Position: <?= htmlspecialchars($position) ?></p>
                    <p class="text-sm text-gray-600">Email: <?= htmlspecialchars($row['Email']) ?></p>
                    <p class="text-sm text-gray-600">Phone: <?= htmlspecialchars($row['PhoneNo']) ?></p>
                    <p class="text-sm text-gray-600">Address: <?= htmlspecialchars($row['Address']) ?></p>
                    <div class="flex gap-2 mt-3">
                        <a href="members.php?delete=<?= $row['Mid'] ?>&search=<?= urlencode($search) ?>&page=<?= $page ?>" onclick="return confirm('Are you sure?')" class="text-red-600 hover:text-red-800 font-bold">Delete</a>
                        <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-bold">Edit</button>
                    </div>
                </div>
            </div>
            <?php endwhile; ?>
        </div>

        <div class="mt-6 flex justify-center space-x-2">
            <?php if ($page > 1): ?>
                <a href="members.php?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>" class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-800">Prev</a>
            <?php endif; ?>
            <?php for ($i = 1; $i <= $Total_page; $i++): ?>
                <a href="members.php?page=<?= $i ?>&search=<?= urlencode($search) ?>" class="px-3 py-1 <?= ($i == $page ? 'bg-blue-800' : 'bg-blue-600') ?> text-white rounded hover:bg-blue-900"><?= $i ?></a>
            <?php endfor; ?>
            <?php if ($page < $Total_page): ?>
                <a href="members.php?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>" class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-800">Next</a>
            <?php endif; ?>
        </div>

        <?php else: ?>
        <div class="bg-red-100 text-center p-4 rounded mt-6">No data found.</div>
        <?php endif; ?>
        </div>

        <!-- Edit Modal -->
        <div id="editModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden">
            <div class="bg-white p-6 rounded-xl shadow-lg w-full max-w-md">
                <h2 class="text-xl font-bold mb-4">Edit Member</h2>
                <form action="members.php?page=<?= $page ?>&search=<?= urlencode($search) ?>" method="POST">
                    <input type="hidden" name="edit_id" id="edit_id">
                    <div class="mb-4">
                        <label for="name" class="block text-sm font-medium">Name</label>
                        <input type="text" name="name" id="edit_name" required class="w-full p-2 border rounded-xl">
                    </div>
                    <div class="mb-4">
                        <label for="position" class="block text-sm font-medium">Position</label>
                        <select name="position" id="edit_position" required class="w-full p-2 border rounded-xl">
                            <?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 class="mb-4">
                        <label for="email" class="block text-sm font-medium">Email</label>
                        <input type="email" name="email" id="edit_email" required class="w-full p-2 border rounded-xl">
                    </div>
                    <div class="mb-4">
                        <label for="phone" class="block text-sm font-medium">Phone</label>
                        <input type="text" name="phone" id="edit_phone" required class="w-full p-2 border rounded-xl">
                    </div>
                    <div class="mb-4">
                        <label for="address" class="block text-sm font-medium">Address</label>
                        <input type="text" name="address" id="edit_address" required class="w-full p-2 border rounded-xl">
                    </div>
                    <div class="flex justify-end gap-2">
                        <button type="button" onclick="closeEditModal()" class="bg-gray-500 text-white px-4 py-2 rounded-xl hover:bg-gray-600">Cancel</button>
                        <button type="submit" name="edit_member" class="bg-blue-600 text-white px-4 py-2 rounded-xl hover:bg-blue-800">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </main>
    <script>
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }

        const searchMembers = debounce(function(searchValue) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', `members.php?ajax=1&search=${encodeURIComponent(searchValue)}&page=1`, true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    document.getElementById('memberList').innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }, 300);

        document.getElementById('searchInput').addEventListener('input', function() {
            searchMembers(this.value.trim());
        });

        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;
            document.getElementById('editModal').classList.remove('hidden');
        }

        function closeEditModal() {
            document.getElementById('editModal').classList.add('hidden');
        }
    </script>
</body>
</html>