
<?php $__env->startSection('title', 'User Management'); ?>

<?php $__env->startSection('backend_content'); ?>
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">

    <style>
        .badge-modern {
            background-color: #e0e7ff;
            color: #4f46e5;
            padding: 6px 12px;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 500;
            display: inline-block;
            margin: 2px;
            border: 1px solid #c7d2fe;
        }

        .btn-action {
            width: 35px;
            height: 35px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        table.dataTable tbody td {
            padding: 12px 15px !important;
            vertical-align: middle;
        }

        .image-preview-container {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            border: 2px dashed #cbd5e1;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            background: #f8fafc;
        }

        .image-preview-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>

    <div class="container-fluid">
        <div class="row page-title clearfix">
            <div class="page-title-left">
                <h6 class="page-title-heading mr-0 mr-r-5">User Management</h6>
                <p class="page-title-description mr-0 d-none d-md-inline-block">Manage system users and assign roles.</p>
            </div>
            <div class="page-title-right d-none d-sm-inline-flex">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="<?php echo e(route('dashboard')); ?>">Dashboard</a></li>
                    <li class="breadcrumb-item active">Users</li>
                </ol>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <div class="widget-list">
            <div class="row">
                <div class="col-md-12">
                    <div class="widget-bg border-0 shadow-sm" style="border-radius: 10px;">
                        <div
                            class="widget-heading widget-heading-border d-flex justify-content-between align-items-center py-3">
                            <h5 class="widget-title m-0">Users List</h5>
                            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('create User')): ?>
                                <button type="button" class="btn btn-primary" style="border-radius: 6px;"
                                    onclick="showAddModal()">
                                    <i class="fa fa-plus-circle mr-1"></i> Add New User
                                </button>
                            <?php endif; ?>
                        </div>

                        <div class="widget-body table-responsive py-3">
                            <table id="usersTable" class="table table-hover text-center w-100">
                                <thead>
                                    <tr>
                                        <th width="5%">#</th>
                                        <th width="8%">Photo</th>
                                        <th width="18%">Name</th>
                                        <th width="14%">Username</th>
                                        <th width="20%">Email</th>
                                        <th width="15%">Role</th>
                                        <th width="10%">Status</th>
                                        <th width="10%">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- DataTables will load this -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit User Modal -->
    <div class="modal fade" id="userModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content" style="border-radius: 12px; border: none;">
                <div class="modal-header bg-light border-bottom-0 pb-3 pt-4 px-4">
                    <h5 class="modal-title font-weight-bold text-dark" id="modalTitle">Add New User</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="userForm" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>
                    <div class="modal-body px-4">
                        <input type="hidden" id="user_id" name="user_id">

                        <!-- Image Upload & Preview Section -->
                        <div class="d-flex align-items-center mb-4 p-3 bg-light rounded" style="border: 1px solid #e2e8f0;">
                            <div class="image-preview-container mr-3">
                                <img id="preview-img"
                                    src="https://ui-avatars.com/api/?name=User&background=6366f1&color=ffffff"
                                    alt="User Image">
                            </div>
                            <div>
                                <label class="font-weight-bold text-dark mb-1">Profile Photo <small
                                        class="text-muted">(Optional)</small></label>
                                <input type="file" class="form-control-file" id="user_image" name="user_image"
                                    accept="image/*" onchange="previewImage(this)">
                                <small class="form-text text-muted">Allowed types: png, jpg, jpeg, webp (Max: 2MB)</small>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 form-group mb-3">
                                <label class="font-weight-bold text-dark">First Name <span
                                        class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="first_name" name="first_name" required>
                            </div>
                            <div class="col-md-6 form-group mb-3">
                                <label class="font-weight-bold text-dark">Last Name <span
                                        class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="last_name" name="last_name" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 form-group mb-3">
                                <label class="font-weight-bold text-dark">Username <span
                                        class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="username" name="username" required>
                            </div>
                            <div class="col-md-6 form-group mb-3">
                                <label class="font-weight-bold text-dark">Email Address <span
                                        class="text-danger">*</span></label>
                                <input type="email" class="form-control" id="email" name="email" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 form-group mb-3">
                                <label class="font-weight-bold text-dark">Password <small id="passHelp"
                                        class="text-muted">(Leave blank if unchanged)</small></label>
                                <input type="password" class="form-control" id="password" name="password">
                            </div>
                            <div class="col-md-6 form-group mb-3">
                                <label class="font-weight-bold text-dark">Status</label>
                                <select class="form-control" id="status" name="status">
                                    <option value="1">Active</option>
                                    <option value="0">Inactive</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group mb-3">
                            <label class="font-weight-bold text-dark">Assign Role <span class="text-danger">*</span></label>
                            <select class="form-control" id="roles" name="roles[]" required>
                                <option value="">Select Role</option>
                                <?php $__currentLoopData = $roles; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $role): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($role->name); ?>"><?php echo e($role->name); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer border-top-0 px-4 pb-4">
                        <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="saveBtn">Save User</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

        var table = $('#usersTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: "<?php echo e(route('admin.users.fetch')); ?>",
            columns: [
                { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
                { data: 'image', name: 'image', orderable: false, searchable: false },
                { data: 'name', name: 'name' },
                { data: 'username', name: 'username' },
                { data: 'email', name: 'email' },
                { data: 'roles', name: 'roles' },
                { data: 'status', name: 'status' },
                { data: 'action', name: 'action', orderable: false, searchable: false },
            ]
        });

        function fetchTable() { table.ajax.reload(null, false); }

        // Instant Image Preview Function
        function previewImage(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#preview-img').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

        function showAddModal() {
            $('#userForm')[0].reset();
            $('#user_id').val('');
            $('#modalTitle').text('Add New User');
            $('#password').attr('required', true);
            $('#preview-img').attr('src', 'https://ui-avatars.com/api/?name=User&background=6366f1&color=ffffff');
            $('#userModal').modal('show');
        }

        function editUser(id) {
            let url = "<?php echo e(route('admin.users.edit', ':id')); ?>".replace(':id', id);

            $.get(url, function (response) {
                $('#userForm')[0].reset();
                $('#modalTitle').text('Modify User');
                $('#user_id').val(response.user.id);
                $('#first_name').val(response.user.first_name);
                $('#last_name').val(response.user.last_name);
                $('#username').val(response.user.username);
                $('#email').val(response.user.email);
                $('#status').val(response.user.status);

                $('#password').removeAttr('required');

                // Set image preview
                if (response.imageUrl) {
                    $('#preview-img').attr('src', response.imageUrl);
                } else {
                    let fullName = response.user.first_name + ' ' + response.user.last_name;
                    $('#preview-img').attr('src', 'https://ui-avatars.com/api/?name=' + encodeURIComponent(fullName) + '&background=6366f1&color=ffffff');
                }

                if (response.userRoles.length > 0) {
                    $('#roles').val(response.userRoles[0]);
                }

                $('#userModal').modal('show');
            }).fail(function (xhr) {
                if (xhr.status === 403) {
                    Swal.fire({ icon: 'error', title: 'Access Denied', text: xhr.responseJSON.error });
                }
            });
        }

        $('#userForm').submit(function (e) {
            e.preventDefault();
            let formData = new FormData(this);
            let btn = $('#saveBtn');
            let originalText = btn.html();
            btn.html('<i class="fa fa-spinner fa-spin mr-1"></i> Saving...').prop('disabled', true);

            $.ajax({
                type: "POST",
                url: "<?php echo e(route('admin.users.store')); ?>",
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    $('#userModal').modal('hide');
                    btn.html(originalText).prop('disabled', false);
                    fetchTable();
                    Swal.fire({ icon: 'success', title: 'Success!', text: response.success, timer: 2000, showConfirmButton: false });
                },
                error: function (xhr) {
                    btn.html(originalText).prop('disabled', false);
                    let errorMsg = 'Something went wrong!';
                    if (xhr.status === 422 && xhr.responseJSON.errors) {
                        errorMsg = Object.values(xhr.responseJSON.errors)[0][0];
                    } else if (xhr.responseJSON && xhr.responseJSON.error) {
                        errorMsg = xhr.responseJSON.error;
                    }
                    Swal.fire({ icon: 'error', title: 'Oops...', text: errorMsg });
                }
            });
        });

        function confirmDelete(id) {
            Swal.fire({
                title: 'Are you sure?', text: "This user will be deleted permanently!", icon: 'warning',
                showCancelButton: true, confirmButtonColor: '#ef4444', cancelButtonColor: '#64748b',
                confirmButtonText: '<i class="fa fa-trash"></i> Yes, delete!'
            }).then((result) => {
                if (result.isConfirmed) {
                    let url = "<?php echo e(route('admin.users.destroy', ':id')); ?>".replace(':id', id);
                    $.ajax({
                        type: "DELETE", url: url,
                        success: function (response) {
                            fetchTable();
                            Swal.fire('Deleted!', response.success, 'success');
                        },
                        error: function (xhr) {
                            let msg = xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : 'Could not delete user.';
                            Swal.fire('Failed!', msg, 'error');
                        }
                    });
                }
            });
        }
    </script>
    <script>

    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('backend.master', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH I:\laragon\www\kyamchjournal\resources\views/backend/users/index.blade.php ENDPATH**/ ?>