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

$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',
    'products' => 'Sản phẩm', 'customers' => 'Khách hàng', 'suppliers' => 'Nhà cung cấp',
    '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 FROM cms_users_group g ORDER BY g.id ASC";
$user_groups = $conn->query($sql_groups)->fetch_all(MYSQLI_ASSOC);
?>

<style>
    .nav-tabs .nav-link { margin-bottom: -1px; }
    .nav-tabs .nav-link.active { font-weight: bold; color: #4e73df; }
    .filter-card { border-left: 4px solid #4e73df; }
    .form-check-label { cursor: pointer; }
    .table thead th { vertical-align: middle; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý người dùng</h1>
    
    <ul class="nav nav-tabs mb-4">
        <li class="nav-item"><a class="nav-link" href="/quanlybanhang/modules/users/list.php"><i class="fas fa-user fa-sm me-2"></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 me-2"></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 me-2"></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-warehouse fa-sm me-2"></i>Quản lý kho</a></li>
    </ul>

    <div class="card shadow mb-4 filter-card">
        <div class="card-body">
            <h6 class="mb-3 font-weight-bold text-primary">Chọn nhóm người dùng</h6>
            <?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 justify-content-between align-items-center">
            <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 me-2"></i> Lưu quyền</button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Chức năng</th>
                            <th style="width: 150px;" class="text-center">
                                <div class="form-check"><input type="checkbox" class="form-check-input" id="checkAll"><label class="form-check-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="form-check d-inline-block"><input type="checkbox" class="form-check-input permission-check" value="<?php echo $key; ?>" id="check-<?php echo $key; ?>"><label class="form-check-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>
// BỔ SUNG LẠI ĐẦY ĐỦ 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 me-2"></i> Lưu quyền');
            }
        });
    }

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

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

    $('#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 me-2"></i> Lưu quyền'); }
        });
    });

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