<?php
session_start();
include '../includes/connection.php';

if (!isset($_SESSION['authenticated_user']) || $_SESSION['authenticated_user'] !== true) {
    header("Location: /LoanApprovalPredction/login.php");
    exit;
}
$mid = $_SESSION['authenticated_user'];
$email = $_SESSION['email'];
$name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);

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

// Session messages
$deleteMessage = $_SESSION['delete'] ?? '';
$updateMessage = $_SESSION['upm'] ?? '';
unset($_SESSION['delete'], $_SESSION['upm']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($name); ?> | Members</title>
    <link rel="icon" href="../images/Icon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <header class="sticky top-0 z-10">
        <?php include '../includes/navbar.php'; ?>
    </header>

    <div class="max-w-7xl mx-auto mt-4 px-4">
        <?php if ($deleteMessage): ?>
            <p class="text-red-500 font-semibold"><?php echo $deleteMessage; ?></p>
        <?php endif; ?>
        <?php if ($updateMessage): ?>
            <p class="text-green-500 font-semibold"><?php echo $updateMessage; ?></p>
        <?php endif; ?>

        <!-- Search -->
        <div class="flex justify-end gap-2 mb-4">
            <a href="members.php" class="bg-black text-white px-4 py-2 rounded-lg">Clear Search</a>
            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                <input type="search" name="search" placeholder="Search"
                    onchange="this.form.submit()"
                    class="p-2 rounded-xl bg-gray-200 text-black focus:ring focus:ring-blue-400 outline-none">
            </form>
        </div>

        <?php
        // Fetch members
        $sql = "SELECT Mid, MembersName, Email, PhoneNo, Address, MPid, status, image
                FROM members
                WHERE Email <> 'agyat@gmail.com' AND MembersName <> 'Agyat Manchhe'
                LIMIT $offset, $Limit";
        $result = mysqli_query($conn, $sql);
        $data = mysqli_fetch_all($result, MYSQLI_ASSOC);

        function linearSearch($data, $term) {
            $results = [];
            foreach ($data as $row) {
                foreach (['MembersName', 'Email', 'Address', 'PhoneNo', 'status'] as $field) {
                    if (stripos($row[$field], $term) !== false) {
                        $results[] = $row;
                        break;
                    }
                }
            }
            return $results;
        }

        if (isset($_POST['search']) && !empty($_POST['search'])) {
            $data = linearSearch($data, $_POST['search']);
        }

        if (count($data) > 0): ?>
            <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php foreach ($data as $member): 
                    $isCurrentUser = ($member['Email'] === $email && $member['Mid'] == $mid);
                    $borderClass = $isCurrentUser ? "shadow-lg border-2 border-green-600" : "";
                    $textClass = $isCurrentUser ? "font-semibold text-green-700" : "";
                    $bgStatus = ($member['status'] === 'leave') ? "bg-red-200" : "bg-white";
                ?>
                <div class="relative bg-white rounded-xl shadow p-4 <?php echo $borderClass; ?>">
                    <?php if ($isCurrentUser): ?>
                        <a href="leave.php?id=<?php echo $member['Mid']; ?>&mpid=<?php echo $member['MPid']; ?>" title="Leave" onclick="return confirm('Are you sure you want to leave?')"
                           class="absolute top-2 left-2"><img src="../images/delete.png" width="30" alt="Leave"></a>
                        <a href="editmember.php?id=<?php echo $member['Mid']; ?>" title="Edit"
                           class="absolute top-2 right-2"><img src="../images/edit.png" width="30" alt="Edit"></a>
                    <?php endif; ?>

                    <img src="../images/<?php echo $member['image']; ?>" alt="Member Image" class="w-40 h-40 mx-auto rounded-full mb-4 object-cover border-2">
                    <figcaption class="text-center text-lg font-bold <?php echo $textClass; ?>"><?php echo $member['MembersName']; ?></figcaption>
                    <p class="text-center <?php echo $textClass . ' ' . $bgStatus; ?>"><?php echo $member['Email']; ?></p>
                    <p class="text-center <?php echo $textClass . ' ' . $bgStatus; ?>"><?php echo $member['PhoneNo']; ?></p>
                    <p class="text-center <?php echo $textClass . ' ' . $bgStatus; ?>"><?php echo $member['Address']; ?></p>
                    <div class="flex justify-center mt-2">
                        <a href="#" class="px-3 py-1 bg-gray-800 text-white rounded hover:bg-gray-700 transition">View Details</a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <p class="text-center text-gray-500 mt-10 text-lg">No results found.</p>
        <?php endif; ?>

        <!-- Pagination -->
        <div class="mt-8 flex justify-center">
            <ul class="flex gap-2">
                <?php
                $countQuery = "SELECT COUNT(*) as total FROM members WHERE Email <> 'agyat@gmail.com' AND MembersName <> 'Agyat Manchhe'";
                $countResult = mysqli_query($conn, $countQuery);
                $totalRecords = mysqli_fetch_assoc($countResult)['total'];
                $totalPages = ceil($totalRecords / $Limit);

                if ($page > 1):
                    echo '<li><a class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-black" href="?page=' . ($page - 1) . '">Prev</a></li>';
                endif;

                for ($i = 1; $i <= $totalPages; $i++):
                    $active = ($i == $page) ? "bg-blue-800" : "bg-blue-600";
                    echo '<li><a class="px-3 py-1 text-white rounded hover:bg-black ' . $active . '" href="?page=' . $i . '">' . $i . '</a></li>';
                endfor;

                if ($page < $totalPages):
                    echo '<li><a class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-black" href="?page=' . ($page + 1) . '">Next</a></li>';
                endif;
                ?>
            </ul>
        </div>
    </div>
</body>
</html>
