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

// --- BỔ SUNG QUYỀN MỚI TẠI ĐÂY ---
$permissions_list = [
    'pos' => 'POS Bán hàng',
    'dashboard' => 'Tổng quan',
    'orders' => 'Đơn hàng',
    'picking_slip' => 'Phiếu soạn hàng',
    'consolidate_orders' => 'Gộp đơn hàng', // <--- DÒNG MỚI ĐƯỢC THÊM
    'products' => 'Sản phẩm',
    'customers' => 'Khách hàng - NCC',
    'imports' => 'Nhập kho',
    'transfer' => 'Chuyển kho',
    'inventory' => 'Tồn kho',
    'reports' => 'Doanh số',
    'receipts' => 'Phiếu thu',
    'payments' => 'Phiếu chi',
    'cashbook' => 'Sổ quỹ',
    'profit' => 'Lợi nhuận',
    'summary' => 'Báo cáo tổng hợp',
    'settings' => 'Thiết lập',
];

$sql_groups = "SELECT g.id, g.group_name, g.group_permission FROM cms_users_group g ORDER BY g.id ASC";
$user_groups = $conn->query($sql_groups)->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" 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 active" 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>
    <li class="nav-item">
        <a class="nav-link" href="/quanlybanhang/modules/stores/list.php">
            <i class="fas fa-print fa-sm mr-1"></i> Quản lý kho
        </a>
    </li>
</ul>

    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Chọn nhóm người dùng</h6>
        </div>
        <div class="card-body">
            <?php if (!empty($user_groups)): foreach ($user_groups as $index => $group): ?>
                <div class="form-check form-check-inline">
                    <input class="form-check-input group-radio" type="radio" name="userGroup" id="group<?php echo $group['id']; ?>" value="<?php echo $group['id']; ?>" <?php echo ($index == 0) ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="group<?php echo $group['id']; ?>"><?php echo htmlspecialchars($group['group_name']); ?></label>
                </div>
            <?php endforeach; endif; ?>
        </div>
    </div>
    
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">Danh sách chức năng</h6>
            <button class="btn btn-success btn-sm" id="savePermissionsBtn"><i class="fas fa-save mr-1"></i> Lưu quyền</button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead class="thead-light">
                        <tr>
                            <th>Chức năng</th>
                            <th style="width: 150px;" class="text-center">
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="checkAll">
                                    <label class="custom-control-label" for="checkAll">Chọn tất cả</label>
                                </div>
                            </th>
                        </tr>
                    </thead>
                    <tbody id="permissions-tbody">
                        <?php foreach ($permissions_list as $key => $value): ?>
                        <tr>
                            <td>
                                <strong><?php echo $value; ?></strong>
                                <small class="d-block text-muted"><?php echo $key; ?></small>
                            </td>
                            <td class="text-center">
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input permission-check" name="permissions[]" value="<?php echo $key; ?>" id="check-<?php echo $key; ?>">
                                    <label class="custom-control-label" for="check-<?php echo $key; ?>"></label>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

<script>
$(document).ready(function() {
    function loadPermissions(groupId) {
        $('.permission-check, #checkAll').prop('checked', false);
        $('#savePermissionsBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Đang tải...');

        $.ajax({
            url: '/quanlybanhang/ajax/permissions_ajax.php',
            type: 'GET',
            dataType: 'json',
            data: { action: 'get_permissions', group_id: groupId },
            success: function(response) {
                if (response.status === 'success' && response.permissions) {
                    response.permissions.forEach(function(permissionKey) {
                        $(`.permission-check[value="${permissionKey}"]`).prop('checked', true);
                    });
                }
            },
            complete: function() {
                $('#savePermissionsBtn').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Lưu quyền');
            }
        });
    }

    var initialGroupId = $('.group-radio:checked').val();
    if (initialGroupId) {
        loadPermissions(initialGroupId);
    }

    $('.group-radio').on('change', function() {
        var selectedGroupId = $(this).val();
        loadPermissions(selectedGroupId);
    });

    $('#savePermissionsBtn').on('click', function() {
        var selectedGroupId = $('.group-radio:checked').val();
        var selectedPermissions = [];
        $('.permission-check:checked').each(function() {
            selectedPermissions.push($(this).val());
        });
        
        $(this).prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Đang lưu...');

        $.ajax({
            url: '/quanlybanhang/ajax/permissions_ajax.php',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'save_permissions',
                group_id: selectedGroupId,
                permissions: selectedPermissions
            },
            success: function(response) {
                alert(response.message);
            },
            error: function() {
                alert('Lỗi kết nối đến máy chủ.');
            },
            complete: function() {
                $('#savePermissionsBtn').prop('disabled', false).html('<i class="fas fa-save mr-1"></i> Lưu quyền');
            }
        });
    });

    $('#checkAll').on('click', function() {
        $('.permission-check').prop('checked', $(this).prop('checked'));
    });
});
</script>