<?php
// admin/roles_permissions.php
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth_stub.php';

// Faqat roles.manage ruxsati bor user kira oladi
require_permission('roles.manage');

// Faqat aktiv rollar ro'yxati
$rolesStmt = $pdo->query("
    SELECT id, name, description, is_active
    FROM roles
    WHERE is_active = 1
    ORDER BY id
");
$roles = $rolesStmt->fetchAll(PDO::FETCH_ASSOC);

// Permissionlar
$permStmt = $pdo->query("
    SELECT id, code, name, description
    FROM permissions
    ORDER BY code
");
$perms = $permStmt->fetchAll(PDO::FETCH_ASSOC);

// Modul nomlari (code: module.action) uchun chiroyli label
$moduleLabels = [
    'index'     => 'Dashboard (index.php)',
    'agg'       => 'Aggregation (agg.php)',
    'blocks'    => 'Bloklar (blocks.php)',
    'categories'=> 'Kategoriyalar (categories.php)',
    'clients'   => 'Mijozlar (clients.php)',
    'km'        => 'KM kodlar (km.php)',
    'km_check'  => 'KM tekshirish (km_check.php)',
    'marking'   => 'Markirovka (marking.php)',
    'oms_api'   => 'OMS API diagnostika (oms_api.php)',
    'products'  => 'Mahsulotlar (products.php)',
    'reports'   => 'Hisobotlar (reports.php)',
    'sales'     => 'Sotuvlar (sales.php)',
    'transport' => 'Transport (transport.php)',
    'users'     => 'Foydalanuvchilar (users.php)',
    'roles'     => 'Role & ruxsatlar (roles_permissions.php)',
];

// Permissionlarni modul + action strukturasiga ajratamiz
$modules = []; // [moduleKey => ['label'=>..., 'actions'=>[action => permRow]]]

foreach ($perms as $p) {
    $code = trim($p['code']);
    if ($code === '') continue;

    $parts = explode('.', $code, 2);
    $moduleKey = $parts[0] ?? 'other';
    $actionKey = $parts[1] ?? 'other';

    if (!isset($modules[$moduleKey])) {
        $modules[$moduleKey] = [
            'key'     => $moduleKey,
            'label'   => $moduleLabels[$moduleKey] ?? ucfirst($moduleKey),
            'actions' => []
        ];
    }
    $modules[$moduleKey]['actions'][$actionKey] = $p;
}

// modulalar bo'yicha sort
usort($modules, function ($a, $b) {
    return strcmp($a['label'], $b['label']);
});

$firstRoleId      = $roles[0]['id'] ?? 0;
$currentUserName  = current_user_name() ?: '';
$currentUserRole  = current_user_role_name() ?: '';
?>
<!DOCTYPE html>
<html lang="uz">
<head>
    <meta charset="UTF-8">
    <title>Role va ruxsatlar boshqaruvi</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 5 (oxirgi versiya) -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Toastr -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

    <style>
        body {
            background: #f3f4f6;
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        }
        .page-wrapper {
            max-width: 1400px;
            margin: 20px auto;
            padding: 0 15px;
        }
        .card-main {
            border-radius: 1rem;
            overflow: hidden;
            border: 1px solid #e5e7eb;
        }
        .card-header {
            background: linear-gradient(90deg, #0d6efd, #38bdf8);
            color: #fff;
            padding: 16px 24px;
        }
        .card-header h5 {
            margin: 0;
            font-weight: 600;
        }
        .user-info {
            font-size: 0.85rem;
            text-align: right;
        }
        .layout {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
        }
        .roles-panel {
            flex: 0 0 260px;
            max-width: 260px;
        }
        .perms-panel {
            flex: 1 1 0;
            min-width: 0;
        }
        .roles-list {
            max-height: 560px;
            overflow-y: auto;
        }
        .role-item {
            cursor: pointer;
            border-radius: 0.75rem !important;
            margin-bottom: 6px;
            border: 1px solid #e5e7eb;
            background: #ffffff;
            transition: all 0.15s ease;
        }
        .role-item:hover {
            background: #eff6ff;
        }
        .role-item.active {
            background: #0d6efd;
            color: #fff;
            border-color: #0d6efd;
        }
        .role-item .role-name {
            font-weight: 600;
            font-size: 0.96rem;
        }
        .role-item .role-desc {
            font-size: 0.8rem;
        }
        .role-badge {
            font-size: 0.7rem;
        }

        .perms-toolbar {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .perms-toolbar .left-tools {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
        }
        .perms-toolbar .right-tools {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
        }

        .perm-container {
            border-radius: 0.75rem;
            border: 1px solid #e5e7eb;
            background: #ffffff;
            max-height: 540px;
            overflow-y: auto;
            padding: 10px 12px;
        }

        .perm-group {
            border-radius: 0.75rem;
            border: 1px solid #e5e7eb;
            margin-bottom: 10px;
            background: #f9fafb;
        }
        .perm-group-header {
            padding: 8px 10px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .perm-group-header-left {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .perm-group-title-text {
            font-weight: 600;
            font-size: 0.95rem;
        }
        .perm-group-file {
            font-size: 0.78rem;
            color: #6b7280;
        }
        .perm-group-badge {
            font-size: 0.75rem;
        }
        .perm-group-actions {
            font-size: 0.78rem;
            display: flex;
            gap: 6px;
            align-items: center;
        }
        .perm-group-body {
            padding: 8px 12px 10px 12px;
        }

        .perm-item {
            font-size: 0.88rem;
            padding: 6px 0;
            border-bottom: 1px dashed #e5e7eb;
        }
        .perm-item:last-child {
            border-bottom: none;
        }
        .perm-item-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
        }
        .perm-item-text-main {
            font-weight: 500;
            font-size: 0.9rem;
        }
        .perm-item-text-sub {
            font-size: 0.78rem;
            color: #6b7280;
        }

        .perm-search-input {
            max-width: 260px;
        }

        .perm-footer-help {
            font-size: 0.8rem;
            color: #6b7280;
            margin-top: 6px;
        }

        /* iPhone-style toggle */
        .switch {
            position: relative;
            display: inline-block;
            width: 44px;
            height: 24px;
        }
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .slider {
            position: absolute;
            cursor: pointer;
            inset: 0;
            background-color: #e5e7eb;
            transition: .2s;
            border-radius: 999px;
            box-shadow: inset 0 0 0 1px #d1d5db;
        }
        .slider:before {
            position: absolute;
            content: "";
            height: 20px;
            width: 20px;
            left: 2px;
            top: 2px;
            background-color: #ffffff;
            transition: .2s;
            border-radius: 50%;
            box-shadow: 0 1px 2px rgba(0,0,0,0.15);
        }
        input:checked + .slider {
            background-color: #22c55e;
            box-shadow: inset 0 0 0 1px #16a34a;
        }
        input:checked + .slider:before {
            transform: translateX(20px);
        }

        @media (max-width: 992px) {
            .layout {
                flex-direction: column;
            }
            .roles-panel {
                max-width: 100%;
                flex: 1 1 auto;
            }
        }
    </style>
</head>
<body>
<div class="page-wrapper">
    <div class="card card-main shadow-sm">
        <div class="card-header d-flex justify-content-between align-items-center">
            <div>
                <h5>Role va ruxsatlar boshqaruvi</h5>
                <div class="small opacity-75">
                    Rollar bo‘yicha sahifalar va <strong>view / create / edit / delete</strong> ruxsatlarini sozlang.
                </div>
            </div>
            <div class="user-info">
                <div><?= htmlspecialchars($currentUserName); ?></div>
                <div class="opacity-75">Rol: <?= htmlspecialchars($currentUserRole); ?></div>
            </div>
        </div>

        <div class="card-body">
            <div class="layout">
                <!-- Rollar paneli -->
                <div class="roles-panel">
                    <h6 class="mb-2">Rollar</h6>
                    <div class="mb-2 small text-muted">
                        Chap tomondan rolni tanlang, o‘ng tomonda modul va ruxsatlar ochiladi.
                    </div>
                    <div class="roles-list list-group" id="rolesList">
                        <?php foreach ($roles as $r): ?>
                            <?php
                            $rid   = (int)$r['id'];
                            $isAct = (int)$r['is_active'] === 1;
                            ?>
                            <button
                                type="button"
                                class="list-group-item list-group-item-action role-item <?= $rid === (int)$firstRoleId ? 'active' : '' ?>"
                                data-role-id="<?= $rid; ?>"
                                data-role-name="<?= htmlspecialchars($r['name']); ?>"
                                data-role-desc="<?= htmlspecialchars($r['description'] ?? ''); ?>"
                            >
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="role-name"><?= htmlspecialchars($r['name']); ?></div>
                                        <?php if (!empty($r['description'])): ?>
                                            <div class="role-desc text-muted">
                                                <?= htmlspecialchars($r['description']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <span class="badge bg-<?= $isAct ? 'success' : 'secondary'; ?> role-badge">
                                        <?= $isAct ? 'aktiv' : 'o‘chirilgan'; ?>
                                    </span>
                                </div>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Permissionlar paneli -->
                <div class="perms-panel">
                    <div class="perms-toolbar">
                        <div class="left-tools">
                            <h6 class="mb-0">Ruxsatlar</h6>
                            <span class="badge bg-light text-dark border">
                                Tanlangan: <span id="permCountSelected">0</span> /
                                <span id="permCountTotal"><?= count($perms); ?></span>
                            </span>
                        </div>
                        <div class="right-tools">
                            <input
                                type="text"
                                class="form-control form-control-sm perm-search-input"
                                id="permSearch"
                                placeholder="Sahifa yoki action bo‘yicha qidirish..."
                            >
                            <button id="btnSave" class="btn btn-success btn-sm">
                                <i class="bi bi-save"></i> Saqlash
                            </button>
                        </div>
                    </div>

                    <input type="hidden" id="currentRoleId" value="<?= (int)$firstRoleId; ?>">

                    <div class="perm-container">
                        <?php foreach ($modules as $mod): ?>
                            <?php
                            $mKey   = $mod['key'];
                            $mLabel = $mod['label'];
                            $actions = $mod['actions'];

                            // tartib: view, create, edit, delete, keyin qolganlari
                            $order = ['view','create','edit','delete'];
                            $orderedActions = [];
                            foreach ($order as $o) {
                                if (isset($actions[$o])) {
                                    $orderedActions[$o] = $actions[$o];
                                    unset($actions[$o]);
                                }
                            }
                            // qolganlar
                            foreach ($actions as $ak => $row) {
                                $orderedActions[$ak] = $row;
                            }

                            // fayl nomini taxmin qilish
                            $fileName = '';
                            if ($mKey === 'index') {
                                $fileName = 'index.php';
                            } elseif ($mKey === 'roles') {
                                $fileName = 'admin/roles_permissions.php';
                            } else {
                                $fileName = $mKey . '.php';
                            }
                            ?>
                            <div class="perm-group mb-2" data-group="<?= htmlspecialchars($mKey); ?>">
                                <div class="perm-group-header">
                                    <div class="perm-group-header-left">
                                        <button
                                            class="btn btn-sm btn-outline-secondary toggle-collapse"
                                            type="button"
                                            data-bs-toggle="collapse"
                                            data-bs-target="#group-<?= htmlspecialchars($mKey); ?>"
                                            aria-expanded="true"
                                        >
                                            <i class="bi bi-chevron-down"></i>
                                        </button>
                                        <div>
                                            <div class="perm-group-title-text"><?= htmlspecialchars($mLabel); ?></div>
                                            <div class="perm-group-file"><?= htmlspecialchars($fileName); ?></div>
                                        </div>
                                    </div>
                                    <div class="perm-group-actions">
                                        <span class="badge bg-secondary bg-opacity-50 text-dark perm-group-badge"
                                              data-group-count="<?= htmlspecialchars($mKey); ?>">
                                            0 ta belgilangan
                                        </span>
                                        <button type="button"
                                                class="btn btn-link btn-sm text-decoration-none btn-check-all"
                                                data-group="<?= htmlspecialchars($mKey); ?>">
                                            Hammasi ON
                                        </button>
                                        <button type="button"
                                                class="btn btn-link btn-sm text-decoration-none btn-uncheck-all"
                                                data-group="<?= htmlspecialchars($mKey); ?>">
                                            Hammasi OFF
                                        </button>
                                    </div>
                                </div>
                                <div class="perm-group-body collapse show" id="group-<?= htmlspecialchars($mKey); ?>">
                                    <?php foreach ($orderedActions as $actionKey => $p): ?>
                                        <?php
                                        $actionLabelUz = match($actionKey) {
                                            'view'   => 'Ko‘rish',
                                            'create' => 'Yaratish (create)',
                                            'edit'   => 'Tahrirlash (edit)',
                                            'delete' => 'O‘chirish (delete)',
                                            default  => ucfirst($actionKey),
                                        };
                                        $actionDescUz = match($actionKey) {
                                            'view'   => 'Sahifani ochish va ko‘rish huquqi',
                                            'create' => 'Yangi yozuv qo‘shish huquqi',
                                            'edit'   => 'Mavjud yozuvni o‘zgartirish huquqi',
                                            'delete' => 'Yozuvni o‘chirish huquqi',
                                            default  => 'Qo‘shimcha amal (' . $actionKey . ')',
                                        };
                                        $dataText = mb_strtolower(
                                            $p['code'] . ' ' .
                                            ($p['name'] ?? '') . ' ' .
                                            ($p['description'] ?? '') . ' ' .
                                            $mLabel . ' ' . $actionLabelUz
                                        );
                                        ?>
                                        <div class="perm-item"
                                             data-perm-text="<?= htmlspecialchars($dataText); ?>">
                                            <div class="perm-item-row">
                                                <div>
                                                    <div class="perm-item-text-main">
                                                        <?= htmlspecialchars($actionLabelUz); ?>
                                                        <span class="text-muted small">
                                                            (<?= htmlspecialchars($p['code']); ?>)
                                                        </span>
                                                    </div>
                                                    <div class="perm-item-text-sub">
                                                        <?= htmlspecialchars($actionDescUz); ?>
                                                    </div>
                                                </div>
                                                <label class="switch mb-0">
                                                    <input
                                                        type="checkbox"
                                                        class="perm-checkbox"
                                                        data-group="<?= htmlspecialchars($mKey); ?>"
                                                        value="<?= (int)$p['id']; ?>"
                                                    >
                                                    <span class="slider"></span>
                                                </label>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="perm-footer-help">
                        Rolni almashtirsangiz – modul va actionlardagi toggle’lar avtomatik yangilanadi.  
                        <strong>Saqlash</strong> tugmasini bosmasangiz, o‘zgarishlar bazaga yozilmaydi.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// API URL – admin papkadan chiqib api/acl.php ga
const API_URL = '../api/acl.php';

// umumiy counterlarni yangilash
function updatePermCounters() {
    const total = $('.perm-checkbox').length;
    const selected = $('.perm-checkbox:checked').length;
    $('#permCountTotal').text(total);
    $('#permCountSelected').text(selected);

    // har bir modul bo'yicha
    $('.perm-group-badge').each(function () {
        const group = $(this).data('group-count');
        const groupSelected = $('.perm-checkbox[data-group="' + group + '"]:checked').length;
        $(this).text(groupSelected + ' ta belgilangan');
    });
}

// tanlangan rol uchun permissionlarni yuklab checkboxlarni sozlash
function loadRolePermissions(roleId) {
    if (!roleId) return;

    $('.perm-checkbox').prop('checked', false);
    updatePermCounters();

    $.getJSON(API_URL, { action: 'get_role_permissions', role_id: roleId })
        .done(function (resp) {
            if (resp.status !== 'ok') {
                toastr.error(resp.message || 'Xatolik');
                return;
            }
            const ids = resp.permission_ids || [];
            ids.forEach(function (id) {
                $('.perm-checkbox[value="' + id + '"]').prop('checked', true);
            });
            updatePermCounters();
        })
        .fail(function () {
            toastr.error('Role permissionlarini yuklashda xato');
        });
}

$(function () {
    toastr.options = {
        positionClass: 'toast-bottom-right',
        timeOut: 2500
    };

    const firstRoleId = $('#currentRoleId').val();
    if (firstRoleId) {
        loadRolePermissions(firstRoleId);
    }

    // Rol tanlash
    $('#rolesList').on('click', '.role-item', function () {
        $('#rolesList .role-item').removeClass('active');
        $(this).addClass('active');

        const rid = $(this).data('role-id');
        $('#currentRoleId').val(rid);
        loadRolePermissions(rid);
    });

    // Har bir modul: hammasini ON/OFF
    $('.perm-container').on('click', '.btn-check-all', function () {
        const g = $(this).data('group');
        $('.perm-checkbox[data-group="' + g + '"]').prop('checked', true).trigger('change');
    });

    $('.perm-container').on('click', '.btn-uncheck-all', function () {
        const g = $(this).data('group');
        $('.perm-checkbox[data-group="' + g + '"]').prop('checked', false).trigger('change');
    });

    // Checkbox o‘zgarganda umumiy counter
    $('.perm-container').on('change', '.perm-checkbox', function () {
        updatePermCounters();
    });

    // Collapse tugmasida iconni aylantirish
    $('.perm-container').on('click', '.toggle-collapse', function () {
        const icon = $(this).find('i');
        setTimeout(() => {
            if ($(this).attr('aria-expanded') === 'true') {
                icon.removeClass('bi-chevron-right').addClass('bi-chevron-down');
            } else {
                icon.removeClass('bi-chevron-down').addClass('bi-chevron-right');
            }
        }, 150);
    });

    // Qidirish
    $('#permSearch').on('input', function () {
        const q = $(this).val().toLowerCase().trim();

        if (q === '') {
            $('.perm-item').show();
            $('.perm-group').show();
            return;
        }

        $('.perm-item').each(function () {
            const txt = ($(this).data('perm-text') || '').toLowerCase();
            if (txt.indexOf(q) !== -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });

        // agar gruppada birorta item ko‘rinmay qolsa, gruppani yashiramiz
        $('.perm-group').each(function () {
            const visibleItems = $(this).find('.perm-item:visible').length;
            if (visibleItems === 0) {
                $(this).hide();
            } else {
                $(this).show();
            }
        });
    });

    // Saqlash
    $('#btnSave').on('click', function () {
        const roleId = $('#currentRoleId').val();
        if (!roleId) {
            toastr.error('Rol tanlanmagan');
            return;
        }

        const ids = [];
        $('.perm-checkbox:checked').each(function () {
            ids.push($(this).val());
        });

        $.ajax({
            url: API_URL + '?action=save_role_permissions',
            method: 'POST',
            dataType: 'json',
            data: {
                role_id: roleId,
                'permission_ids[]': ids
            }
        }).done(function (resp) {
            if (resp.status === 'ok') {
                toastr.success(resp.message || 'Saqlandi');
            } else {
                toastr.error(resp.message || 'Xatolik');
            }
        }).fail(function () {
            toastr.error('Saqlashda xato');
        });
    });
});
</script>
</body>
</html>
