<?php

require_once __DIR__.'/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__.'/../includes/csrf.php';

if($_SESSION['role']!='admin')
{
    die("Access Denied");
}

$result =
mysqli_query(
$conn,
"SELECT *
 FROM users
 ORDER BY id ASC"
);

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

<?php if(isset($_GET['msg']) && $_GET['msg']=='deleted'){ ?>

<div class="alert alert-success">
    User deleted successfully.
</div>

<?php } ?>


<div class="container mt-4">

    <div class="card shadow">

        <div class="card-header bg-primary text-white">

            Users

            <a href="add_user.php"
                class="btn btn-light btn-sm float-end">

                Add User

            </a>

        </div>

        <div class="card-body">

            <table class="table table-bordered">

                <tr>

                    <th>ID</th>
                    <th>Full Name</th>
                    <th>Phone Number</th>
                    <th>Role</th>
                    <th>Status</th>
                    <th>Action</th>

                </tr>

                <?php while($row=mysqli_fetch_assoc($result)){ ?>

                <tr>

                    <td><?= $row['id'] ?></td>

                    <td><?= htmlspecialchars($row['fullname']) ?></td>

                    <td><?= htmlspecialchars($row['phone']) ?></td>

                    <td><?= $row['role'] ?></td>

                    <td><?= $row['status'] ?></td>

                    <?php
                    $isSystemAdmin = ($row['id'] == 1 && $row['role'] == 'admin');
                    $isCurrentUser = ($_SESSION['user_id'] == $row['id']);
                    ?>

                    <td>

                        <?php if (!$isSystemAdmin || $isCurrentUser) { ?>

                            <a href="edit_user.php?id=<?= $row['id'] ?>"
                            class="btn btn-warning btn-sm">
                                <i class="fa-solid fa-pen-to-square"></i> Edit
                            </a>

                        <?php } ?>

                        <?php if (!$isSystemAdmin) { ?>

                            <form method="POST" action="delete_user.php" class="d-inline" onsubmit="return confirm('Delete this user?');">
                                <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                                <button class="btn btn-danger btn-sm"><i class="fa-solid fa-trash"></i> Delete</button>
                            </form>

                        <?php } ?>

                    </td>

                </tr>

                <?php } ?>

            </table>

        </div>

    </div>

</div>

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