<?php
include 'inc/header.php';

if (isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'user') {
    echo "<script>window.location.href='index.php'</script>";
    exit;
}
?>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-secondary">Users List</h6>
    </div>

    <div class="card-body">
        <table id="usersTable" class="display table table-bordered" width="100%">
            <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Profile Image</th>
                <th>Role</th>
                <th>Status</th>
                <th>Created</th>
                <th>Actions</th>
            </tr>
            </thead>

            <tbody>
            <?php
            $sql = "SELECT * FROM tbl_register WHERE role != 'admin' ORDER BY id DESC";
            $res = mysqli_query($conn, $sql);

            while ($row = mysqli_fetch_assoc($res)) {
            ?>
                <tr data-id="<?= $row['id'] ?>">
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= htmlspecialchars($row['email']) ?></td>
                    <td><?= htmlspecialchars($row['phone']) ?></td>
                     <td><img src="" alt=""></td>
                    <td><?= ucfirst($row['role']) ?></td>

                    <td>
                        <span class="badge badge-<?=
                            $row['status']=='active' ? 'success' :
                            ($row['status']=='pending' ? 'warning' : 'danger')
                        ?>">
                            <?= ucfirst($row['status']) ?>
                        </span>
                    </td>

                    <td><?= date('d M Y h: i a', strtotime($row['created_date'])) ?></td>

                    <td>
                        <select class="form-control form-control-sm status-change">
                            <option value="active" <?= $row['status']=='active'?'selected':'' ?>>Active</option>
                            <option value="inactive" <?= $row['status']=='inactive'?'selected':'' ?>>Inactive</option>
                        </select>

                        <button class="btn btn-sm btn-danger mt-1 delete-btn">
                            Delete
                        </button>
                    </td>
                </tr>
            <?php } ?>
            </tbody>
        </table>
    </div>
</div>

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

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(function () {

    const table = $('#usersTable').DataTable();

    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000"
    };

    /* STATUS UPDATE */
    $('#usersTable').on('change', '.status-change', function () {
        let row = $(this).closest('tr');
        let user_id = row.data('id');
        let status = $(this).val();

        $.post('update_user.php', {
            user_id: user_id,
            status: status
        }, function (res) {
            if (res == 1) {
                toastr.success('User status updated');

                let badge = row.find('.badge');
                badge.removeClass('badge-success badge-warning badge-danger');

                if(status === 'active') badge.addClass('badge-success');
                if(status === 'inactive') badge.addClass('badge-danger');

                badge.text(status.charAt(0).toUpperCase()+status.slice(1));
            } else {
                toastr.error('Failed to update user');
            }
        });
    });

    /* DELETE USER */
    $('#usersTable').on('click', '.delete-btn', function () {
        let row = $(this).closest('tr');
        let user_id = row.data('id');

        Swal.fire({
            title: 'Are you sure?',
            text: "This user will be permanently deleted!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('delete_user.php', { id: user_id }, function (res) {
                    if (res == 1) {
                        toastr.success('User deleted');
                        table.row(row).remove().draw();
                    } else {
                        toastr.error('Unable to delete user');
                    }
                });
            }
        });
    });

});
</script>
