<?php
require_once __DIR__ . '/../../templates/header.php';

// 1. LẤY DỮ LIỆU TỪ DATABASE
$sql_users = "SELECT u.id, u.username AS ma_nhan_vien, u.display_name AS ten_nhan_vien, u.email, u.commission AS he_so_thuong, u.user_status, g.group_name FROM cms_users AS u LEFT JOIN cms_users_group AS g ON u.group_id = g.id ORDER BY u.id ASC";
$staff_list = $conn->query($sql_users)->fetch_all(MYSQLI_ASSOC);

$sql_groups = "SELECT id, group_name FROM cms_users_group ORDER BY group_name ASC";
$user_groups_list = $conn->query($sql_groups)->fetch_all(MYSQLI_ASSOC);

// Lấy danh sách kho từ CSDL
$sql_stores = "SELECT ID, store_name FROM cms_stores ORDER BY store_name ASC";
$stores_list = $conn->query($sql_stores)->fetch_all(MYSQLI_ASSOC);
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Quản lý người dùng</h1>
    <ul class="nav nav-tabs mb-3">
    <li class="nav-item">
        <a class="nav-link active" href="/quanlybanhang/modules/users/list.php">
            <i class="fas fa-user fa-sm mr-1"></i> Nhân viên
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="/quanlybanhang/modules/users/permissions.php">
            <i class="fas fa-user-shield fa-sm mr-1"></i> Phân quyền
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="/quanlybanhang/modules/settings/print_config.php">
            <i class="fas fa-print fa-sm mr-1"></i> Cài đặt trang in
        </a>
    </li>
</ul>

    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addUserModal">
                <i class="fas fa-plus mr-1"></i> Tạo nhân viên
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTableNhanVien" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Mã nhân viên</th>
                            <th>Tên nhân viên</th>
                            <th>Email</th>
                            <th>Hệ số thưởng</th>
                            <th>Nhóm người sử dụng</th>
                            <th>Trạng thái</th>
                            <th>Hành động</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($staff_list)): foreach ($staff_list as $index => $staff): ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td><?php echo htmlspecialchars($staff['ma_nhan_vien']); ?></td>
                                <td><?php echo htmlspecialchars($staff['ten_nhan_vien']); ?></td>
                                <td><?php echo htmlspecialchars($staff['email']); ?></td>
                                <td><?php echo htmlspecialchars($staff['he_so_thuong']); ?></td>
                                <td><?php echo htmlspecialchars($staff['group_name'] ?? 'Chưa phân nhóm'); ?></td>
                                <td><?php echo ($staff['user_status'] == 1) ? '<span class="badge badge-success">Hoạt động</span>' : '<span class="badge badge-secondary">Tạm khóa</span>'; ?></td>
                                <td class="text-center">
                                    <a href="#" class="btn btn-info btn-sm btn-edit" data-id="<?php echo $staff['id']; ?>" title="Sửa"><i class="fas fa-edit"></i></a>
                                    <a href="#" class="btn btn-danger btn-sm btn-delete" data-id="<?php echo $staff['id']; ?>" title="Xóa"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="8" class="text-center">Không tìm thấy nhân viên nào.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addUserModalLabel"><i class="fas fa-user-plus mr-2"></i>THÊM TÀI KHOẢN ĐĂNG NHẬP</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="form-group row"><label for="display_name" class="col-sm-3 col-form-label">Tên nhân viên</label><div class="col-sm-9"><input type="text" class="form-control" id="display_name" name="display_name" placeholder="Nhập tên nhân viên" required></div></div>
                    <div class="form-group row"><label for="username" class="col-sm-3 col-form-label">Mã nhân viên</label><div class="col-sm-9"><input type="text" class="form-control" id="username" name="username" placeholder="Nhập mã nhân viên (dùng để đăng nhập)" required></div></div>
                    <div class="form-group row"><label for="email" class="col-sm-3 col-form-label">Email</label><div class="col-sm-9"><input type="email" class="form-control" id="email" name="email" placeholder="Nhập email của bạn" required></div></div>
                    <div class="form-group row"><label for="commission" class="col-sm-3 col-form-label">Hệ số thưởng</label><div class="col-sm-9"><input type="number" step="0.1" class="form-control" id="commission" name="commission" value="0" placeholder="Nhập % hoa hồng (hệ số thưởng)"></div></div>
                    <div class="form-group row"><label for="password" class="col-sm-3 col-form-label">Mật khẩu</label><div class="col-sm-9"><input type="password" class="form-control" id="password" name="password" placeholder="Nhập mật khẩu" required></div></div>
                    <div class="form-group row"><label for="group_id" class="col-sm-3 col-form-label">Nhóm người dùng</label><div class="col-sm-9"><select class="form-control" id="group_id" name="group_id" required><option value="">-- Chọn nhóm --</option><?php foreach ($user_groups_list as $group): ?><option value="<?php echo $group['id']; ?>"><?php echo htmlspecialchars($group['group_name']); ?></option><?php endforeach; ?></select></div></div>
                    <div class="form-group row"><label for="store_id" class="col-sm-3 col-form-label">Kho làm việc</label><div class="col-sm-9"><select class="form-control" id="store_id" name="store_id" required><option value="">-- Chọn kho --</option><?php foreach ($stores_list as $store): ?><option value="<?php echo $store['ID']; ?>"><?php echo htmlspecialchars($store['store_name']); ?></option><?php endforeach; ?></select></div></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Bỏ qua</button>
                <button type="submit" class="btn btn-primary" form="addUserForm">Lưu</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editUserModalLabel"><i class="fas fa-edit mr-2"></i>CHỈNH SỬA TÀI KHOẢN</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="edit_user_id" name="user_id">
                    <div class="form-group row"><label for="edit_display_name" class="col-sm-3 col-form-label">Tên nhân viên</label><div class="col-sm-9"><input type="text" class="form-control" id="edit_display_name" name="display_name" required></div></div>
                    <div class="form-group row"><label for="edit_username" class="col-sm-3 col-form-label">Mã nhân viên</label><div class="col-sm-9"><input type="text" class="form-control" id="edit_username" name="username" required></div></div>
                    <div class="form-group row"><label for="edit_email" class="col-sm-3 col-form-label">Email</label><div class="col-sm-9"><input type="email" class="form-control" id="edit_email" name="email" required></div></div>
                    <div class="form-group row"><label for="edit_password" class="col-sm-3 col-form-label">Mật khẩu mới</label><div class="col-sm-9"><input type="password" class="form-control" id="edit_password" name="password" placeholder="Để trống nếu không muốn đổi"></div></div>
                    <div class="form-group row"><label for="edit_group_id" class="col-sm-3 col-form-label">Nhóm người dùng</label><div class="col-sm-9"><select class="form-control" id="edit_group_id" name="group_id" required><?php foreach ($user_groups_list as $group): ?><option value="<?php echo $group['id']; ?>"><?php echo htmlspecialchars($group['group_name']); ?></option><?php endforeach; ?></select></div></div>
                    <div class="form-group row"><label for="edit_store_id" class="col-sm-3 col-form-label">Kho làm việc</label><div class="col-sm-9"><select class="form-control" id="edit_store_id" name="store_id" required><?php foreach ($stores_list as $store): ?><option value="<?php echo $store['ID']; ?>"><?php echo htmlspecialchars($store['store_name']); ?></option><?php endforeach; ?></select></div></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Bỏ qua</button>
                <button type="submit" class="btn btn-primary" form="editUserForm">Lưu thay đổi</button>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script>
$(document).ready(function() {
    $('#dataTableNhanVien').DataTable({
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" }
    });
    
    $('#addUserForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: '/quanlybanhang/ajax/users_ajax.php', type: 'POST', dataType: 'json', data: $(this).serialize() + '&action=add_user',
            success: function(response) {
                alert(response.message);
                if (response.status === 'success') location.reload();
            },
            error: function() { alert('Lỗi kết nối đến máy chủ.'); }
        });
    });

    $('#dataTableNhanVien tbody').on('click', 'a.btn-delete', function(e) {
        e.preventDefault();
        var userId = $(this).data('id');
        if (confirm('Bạn có chắc chắn muốn xóa nhân viên này không?')) {
            $.ajax({
                url: '/quanlybanhang/ajax/users_ajax.php', type: 'POST', dataType: 'json', data: { action: 'delete_user', user_id: userId },
                success: function(response) {
                    alert(response.message);
                    if (response.status === 'success') location.reload();
                }
            });
        }
    });

    $('#dataTableNhanVien tbody').on('click', 'a.btn-edit', function(e) {
        e.preventDefault();
        var userId = $(this).data('id');
        $.ajax({
            url: '/quanlybanhang/ajax/users_ajax.php', type: 'GET', dataType: 'json', data: { action: 'get_user_details', user_id: userId },
            success: function(response) {
                if (response.status === 'success') {
                    $('#edit_user_id').val(response.data.id);
                    $('#edit_username').val(response.data.username);
                    $('#edit_display_name').val(response.data.display_name);
                    $('#edit_email').val(response.data.email);
                    $('#edit_group_id').val(response.data.group_id);
                    $('#edit_store_id').val(response.data.store_id);
                    $('#editUserModal').modal('show');
                } else {
                    alert(response.message);
                }
            }
        });
    });

    $('#editUserForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: '/quanlybanhang/ajax/users_ajax.php', type: 'POST', dataType: 'json', data: $(this).serialize() + '&action=edit_user',
            success: function(response) {
                alert(response.message);
                if (response.status === 'success') {
                    $('#editUserModal').modal('hide');
                    location.reload();
                }
            }
        });
    });
});
</script>