@extends('layouts.master')

<link rel="stylesheet" href="{{ asset('assets/styles/vendor/datatables.min.css') }}">
<style>
    .dot {
        height: 10px;
        width: 10px;
        background-color: #ef8e8e;
        border-radius: 50%;
        display: inline-block;
    }

    .dot2 {
        height: 10px;
        width: 10px;
        background-color: #b69595;
        border-radius: 50%;
        display: inline-block;
    }

    .switch {
        position: relative;
        display: inline-block;
        width: 34px;
        height: 20px;
    }

    .switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    .switch .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        transition: .4s;
        border-radius: 34px;
    }

    .switch .slider:before {
        position: absolute;
        content: "";
        height: 14px;
        width: 14px;
        left: 3px;
        bottom: 3px;
        background-color: white;
        transition: .4s;
        border-radius: 50%;
    }

    .switch input:checked+.slider.module-slider {
        background-color: #3bafda;
    }

    .switch input:checked+.slider.submodule-slider {
        background-color: #4caf50;
    }

    .switch input:checked+.slider.subpermissions-slider {
        background-color: #ffc107;
    }

    .switch input:checked+.slider:before {
        transform: translateX(14px);
    }

    .switch label {
        margin: 0;
    }

    .description-container {
        margin-bottom: 1rem;
    }

    .description-container h5 {
        font-weight: bold;
        color: #333;
    }

    .description-text {
        font-size: 0.9rem;
        margin-left: 10px;
    }

    .btn {
        border-radius: 4px;
    }

    .btn-primary {
        background-color: #3bafda;
        border-color: #3bafda;
    }

    .btn-danger {
        background-color: #dc3545;
        border-color: #dc3545;
    }

    .btn-sm {
        padding: 0.375rem 0.75rem;
        font-size: 0.875rem;
    }

    .table thead th {
        background-color: #f8f9fa;
        font-weight: bold;
    }

    .table tbody tr:nth-child(odd) {
        background-color: #f9f9f9;
    }

    .table tbody tr:hover {
        background-color: #e9ecef;
    }

    .card {
        border-radius: 6px;
        border: 1px solid #ddd;
    }

    .card-body {
        padding: 1.25rem;
    }

    .alert-card {
        border-radius: 6px;
        padding: 0.75rem 1.25rem;
    }

    .alert-card .close {
        margin-top: -0.75rem;
        margin-right: -0.75rem;
    }

    .search-box {
        position: relative;
        margin-bottom: 0.5rem;
    }

    .search-box input {
        width: 100%;
        padding: 0.45rem 0.75rem 0.45rem 2.1rem;
        border: 1px solid #ced4da;
        border-radius: 4px;
        font-size: 0.875rem;
        color: #495057;
        background-color: #fff;
        transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;
    }

    .search-box input:focus {
        outline: none;
        border-color: #3bafda;
        box-shadow: 0 0 0 2px rgba(59, 175, 218, .2);
    }

    .search-box .search-icon {
        position: absolute;
        left: 0.6rem;
        top: 50%;
        transform: translateY(-50%);
        color: #aaa;
        pointer-events: none;
        font-size: 13px;
    }

    .search-count {
        font-size: 0.78rem;
        color: #6c757d;
        margin-bottom: 0.5rem;
        min-height: 1.1rem;
    }
</style>

@section('content')
    <div class="az-content-breadcrumb">
        <span>Roles Permission Management</span>
    </div>
    <h2 class="az-content-title d-flex justify-content-between align-items-center">
        Permissions List
        <a href="{{ url('roles') }}" class="btn btn-outline-secondary">
            <i class="fa-solid fa-bars-staggered"></i> Back to Roles
        </a>
    </h2>

    <div class="row">
        <div class="col-md-12">
            @if (Session('alert'))
                <div class="alert alert-card alert-{{ Session('alert-class') }}" role="alert">
                    {{ Session('alert') }}
                    <button class="close" type="button" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            @endif
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-4">
            <label for="role">Role</label>
            <select onchange="location.href='{{ url('roles/permission') }}/' + this.value;" class="form-control">
                <option value="0">--Select--</option>
                @foreach ($roles as $role)
                    <option value="{{ $role->id }}" {{ $role_id == $role->id ? 'selected' : '' }}>
                        {{ $role->name }}
                    </option>
                @endforeach
            </select>
        </div>
        <div class="col-md-6"></div>
        <div class="col-md-2">
            <button style="float: right" type="submit" class="btn btn-az-primary submit">Update Permissions</button>
        </div>
    </div>

    <div class="separator-breadcrumb border-top"></div>

    <form id="permission" action="{{ url('roles/permission', [$role_id]) }}" method="post">
        @csrf
        <div class="row">

            {{-- ===================== Modules Permissions ===================== --}}
            <div class="col-md-6">
                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card text-left shadow p-3 mb-5 bg-white rounded">
                            <div class="card-body">

                                <div class="description-container">
                                    <h5>Access Control Information:</h5>
                                    <div class="d-flex flex-column">
                                        <div class="d-flex align-items-center mb-2">
                                            <label class="switch mr-2">
                                                <input type="checkbox" checked value="1" />
                                                <span class="slider module-slider"></span>
                                            </label>
                                            <span class="description-text">
                                                <b style="color:#3bafda;">Primary Modules Permission:</b> switch for core accessibility
                                            </span>
                                        </div>
                                        <div class="d-flex align-items-center mb-2">
                                            <label class="switch mr-2">
                                                <input type="checkbox" checked value="1" />
                                                <span class="slider submodule-slider"></span>
                                            </label>
                                            <span class="description-text">
                                                <b style="color:#4caf50;">Sub Modules Permission:</b> switch for primary core accessibility
                                            </span>
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <label class="switch mr-2">
                                                <input type="checkbox" checked value="1" />
                                                <span class="slider subpermissions-slider"></span>
                                            </label>
                                            <span class="description-text">
                                                <b style="color:#ffc107;">Access Controls Permission:</b> switch for sub controls accessibility
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <hr>
                                <h2>Modules Permissions</h2>

                                <h6 class="card-title mb-3 d-flex align-items-center">
                                    <span class="mr-2">Check All</span>
                                    <label class="switch mb-0">
                                        <input type="checkbox" id="check-all">
                                        <span class="slider module-slider"></span>
                                    </label>
                                </h6>

                                {{-- Module Search --}}
                                <div class="search-box">
                                    <span class="search-icon">
                                        <i class="fa fa-search"></i>
                                    </span>
                                    <input type="text" id="moduleSearch" placeholder="Search modules...">
                                </div>
                                <div class="search-count" id="moduleCount"></div>

                                <div class="table-responsive">
                                    <table id="permissionsTable" class="table table-striped table-bordered">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Pages</th>
                                                <th>Permission</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @php $count = 1; @endphp
                                            @foreach ($permissions->groupBy('parent_id') as $parent_id => $group)
                                                @if ($parent_id == 0)
                                                    @foreach ($group as $permission)
                                                        <tr class="module-row"
                                                            data-name="{{ strtolower($permission->name) }}"
                                                            data-module-id="{{ $permission->id }}">
                                                            <td>{{ $count++ }}</td>
                                                            <td><strong>{{ $permission->name }}</strong></td>
                                                            <td>
                                                                <label class="switch">
                                                                    <input type="checkbox"
                                                                        class="check-module"
                                                                        name="permissions[]"
                                                                        value="{{ $permission->id }}"
                                                                        {{ in_array($permission->id, $assigned_permissions) ? 'checked' : '' }}>
                                                                    <span class="slider module-slider"></span>
                                                                </label>
                                                            </td>
                                                        </tr>

                                                        @foreach ($permissions->where('parent_id', $permission->id) as $subPermission)
                                                            <tr class="sub-module module-child-{{ $permission->id }}"
                                                                data-name="{{ strtolower($subPermission->name) }}"
                                                                data-parent="{{ $permission->id }}"
                                                                data-submodule-id="{{ $subPermission->id }}">
                                                                <td>{{ $count++ }}</td>
                                                                <td style="padding-left: 3rem;">
                                                                    <span class="dot"></span> {{ $subPermission->name }}
                                                                </td>
                                                                <td>
                                                                    <label class="switch">
                                                                        <input type="checkbox"
                                                                            class="check-module"
                                                                            name="permissions[]"
                                                                            value="{{ $subPermission->id }}"
                                                                            {{ in_array($subPermission->id, $assigned_permissions) ? 'checked' : '' }}>
                                                                        <span class="slider submodule-slider"></span>
                                                                    </label>
                                                                </td>
                                                            </tr>

                                                            @foreach ($permissions->where('parent_id', $subPermission->id) as $subSubPermission)
                                                                <tr class="sub-permissions module-child-{{ $permission->id }} submodule-child-{{ $subPermission->id }}"
                                                                    data-name="{{ strtolower($subSubPermission->name) }}"
                                                                    data-parent="{{ $subPermission->id }}">
                                                                    <td>{{ $count++ }}</td>
                                                                    <td style="padding-left: 5rem;">
                                                                        <span class="dot2"></span> {{ $subSubPermission->name }}
                                                                    </td>
                                                                    <td>
                                                                        <label class="switch">
                                                                            <input type="checkbox"
                                                                                class="check-module"
                                                                                name="permissions[]"
                                                                                value="{{ $subSubPermission->id }}"
                                                                                {{ in_array($subSubPermission->id, $assigned_permissions) ? 'checked' : '' }}>
                                                                            <span class="slider subpermissions-slider"></span>
                                                                        </label>
                                                                    </td>
                                                                </tr>
                                                            @endforeach
                                                        @endforeach
                                                    @endforeach
                                                @endif
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {{-- ===================== Accounts Permissions ===================== --}}
            <div class="col-md-6">
                <div class="card text-left shadow p-3 mb-5 bg-white rounded">
                    <div class="card-body">

                        <h2>Accounts Permissions</h2>

                        <h6 class="card-title mb-3 d-flex align-items-center">
                            <span class="mr-2">Check All Accounts</span>
                            <label class="switch mb-0">
                                <input type="checkbox" id="checkAllAccounts">
                                <span class="slider module-slider"></span>
                            </label>
                        </h6>

                        {{-- Account Search --}}
                        <div class="search-box">
                            <span class="search-icon">
                                <i class="fa fa-search"></i>
                            </span>
                            <input type="text" id="accountSearch" placeholder="Search accounts...">
                        </div>
                        <div class="search-count" id="accountCount"></div>

                        <div class="table-responsive">
                            <table id="accountsTable" class="table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Account Type</th>
                                        <th>Account Name</th>
                                        <th>Enable/Disable</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @php $count = 1; @endphp

                                    @foreach ($mainAccounts as $mainAccount)

                                        <tr class="account-main-row"
                                            data-name="{{ strtolower($mainAccount->main_account_name) }}"
                                            data-main-id="{{ $mainAccount->id_main_account }}">
                                            <td>{{ $count++ }}</td>
                                            <td><strong>Main Account</strong></td>
                                            <td>{{ $mainAccount->main_account_name }}</td>
                                            <td>
                                                <label class="switch">
                                                    <input type="checkbox"
                                                        name="accounts[{{ $mainAccount->id_main_account }}][mainaccount_id]"
                                                        value="{{ $mainAccount->id_main_account }}"
                                                        class="account-checkbox"
                                                        {{ $accountPermissions->contains(fn($perm) => $perm->account_type === 'MainAccount' && $perm->main_account_id == $mainAccount->id_main_account) ? 'checked' : '' }}>
                                                    <span class="slider module-slider"></span>
                                                </label>
                                            </td>
                                        </tr>

                                        @foreach ($mainAccount->controlAccounts as $controlAccount)

                                            <tr class="account-child-row account-main-{{ $mainAccount->id_main_account }}"
                                                data-name="{{ strtolower($controlAccount->control_account_name) }}"
                                                data-control-id="{{ $controlAccount->id_control_account }}">
                                                <td>{{ $count++ }}</td>
                                                <td style="padding-left: 3rem;">
                                                    <span class="dot"></span> <strong>Control Account</strong>
                                                </td>
                                                <td>{{ $controlAccount->control_account_name }}</td>
                                                <td>
                                                    <label class="switch">
                                                        <input type="checkbox"
                                                            name="accounts[{{ $controlAccount->id_control_account }}][conaccount_id]"
                                                            value="{{ $controlAccount->id_control_account }}"
                                                            class="account-checkbox"
                                                            {{ $accountPermissions->contains(fn($perm) => $perm->account_type === 'ControlAccount' && $perm->control_account_id == $controlAccount->id_control_account) ? 'checked' : '' }}>
                                                        <span class="slider submodule-slider"></span>
                                                    </label>
                                                </td>
                                            </tr>

                                            @foreach ($controlAccount->subControlAccounts as $subControlAccount)

                                                <tr class="account-child-row account-main-{{ $mainAccount->id_main_account }} account-control-{{ $controlAccount->id_control_account }}"
                                                    data-name="{{ strtolower($subControlAccount->sub_control_account_name) }}">
                                                    <td>{{ $count++ }}</td>
                                                    <td style="padding-left: 5rem;">
                                                        <span class="dot2"></span> <strong>Sub-Control Account</strong>
                                                    </td>
                                                    <td>{{ $subControlAccount->sub_control_account_name }}</td>
                                                    <td>
                                                        <label class="switch">
                                                            <input type="checkbox"
                                                                name="accounts[{{ $subControlAccount->id_sub_control_account }}][subaccount_id]"
                                                                value="{{ $subControlAccount->id_sub_control_account }}"
                                                                class="account-checkbox"
                                                                {{ $accountPermissions->contains(fn($perm) => $perm->account_type === 'SubControlAccount' && $perm->sub_control_account_id == $subControlAccount->id_sub_control_account) ? 'checked' : '' }}>
                                                            <span class="slider subpermissions-slider"></span>
                                                        </label>
                                                    </td>
                                                </tr>

                                                @foreach ($subControlAccount->transactionAccounts as $transactionAccount)

                                                    <tr class="account-child-row account-main-{{ $mainAccount->id_main_account }} account-control-{{ $controlAccount->id_control_account }}"
                                                        data-name="{{ strtolower($transactionAccount->transaction_account_name) }}">
                                                        <td>{{ $count++ }}</td>
                                                        <td style="padding-left: 7rem;">
                                                            <span class="dot2"></span> <strong>Transaction Account</strong>
                                                        </td>
                                                        <td>{{ $transactionAccount->transaction_account_name }}</td>
                                                        <td>
                                                            <label class="switch">
                                                                <input type="checkbox"
                                                                    name="accounts[{{ $transactionAccount->id_transaction_account }}][transaccount_id]"
                                                                    value="{{ $transactionAccount->id_transaction_account }}"
                                                                    class="account-checkbox"
                                                                    {{ $accountPermissions->contains(fn($perm) => $perm->account_type === 'TransactionAccount' && $perm->transaction_account_id == $transactionAccount->id_transaction_account) ? 'checked' : '' }}>
                                                                <span class="slider subpermissions-slider"></span>
                                                            </label>
                                                        </td>
                                                    </tr>

                                                @endforeach
                                            @endforeach
                                        @endforeach
                                    @endforeach
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>
            </div>

        </div>
    </form>
@endsection

@push('scripts')
    <script src="{{ asset('assets/js/vendor/datatables.min.js') }}"></script>
    <script>
        // Submit on button click
        document.querySelector('.submit').addEventListener('click', function() {
            document.getElementById('permission').submit();
        });

        // Submit on Ctrl+S
        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 's') {
                e.preventDefault();
                document.getElementById('permission').submit();
            }
        });

        $(document).ready(function() {

            // Init DataTables
            $('#permissionsTable').DataTable({
                paging: false,
                info: false,
                searching: false,
                destroy: true
            });

            $('#accountsTable').DataTable({
                paging: false,
                info: false,
                searching: false,
                destroy: true
            });

            // ── Check All Modules (visible rows only) ──
            $('#check-all').change(function() {
                $('#permissionsTable tbody tr:visible .check-module').prop('checked', $(this).is(':checked'));
            });

            // ── Check All Accounts (visible rows only) ──
            $('#checkAllAccounts').change(function() {
                $('#accountsTable tbody tr:visible .account-checkbox').prop('checked', $(this).is(':checked'));
            });

            // ── Module Search ──
            function updateModuleCount() {
                var visible = $('#permissionsTable tbody tr:visible').length;
                var total = $('#permissionsTable tbody tr').length;
                $('#moduleCount').text(visible < total ? 'Showing ' + visible + ' of ' + total + ' rows' : '');
            }

            $('#moduleSearch').on('input', function() {
                var q = $(this).val().toLowerCase().trim();

                if (q === '') {
                    $('#permissionsTable tbody tr').show();
                    updateModuleCount();
                    return;
                }

                // Hide all rows first
                $('#permissionsTable tbody tr').hide();

                // Loop each top-level module
                $('#permissionsTable tbody tr.module-row').each(function() {
                    var $parentRow = $(this);
                    var parentId = $parentRow.data('module-id');
                    var parentName = $parentRow.data('name');
                    var $children = $('#permissionsTable tbody tr[class*="module-child-' + parentId + '"]');

                    var parentMatch = parentName.includes(q);
                    var childrenMatch = false;

                    $children.each(function() {
                        if ($(this).data('name').includes(q)) childrenMatch = true;
                    });

                    if (parentMatch) {
                        $parentRow.show();
                        $children.show();
                    } else if (childrenMatch) {
                        $parentRow.show();
                        $children.each(function() {
                            if ($(this).data('name').includes(q)) $(this).show();
                        });
                    }
                });

                updateModuleCount();
            });

            // ── Account Search ──
            function updateAccountCount() {
                var visible = $('#accountsTable tbody tr:visible').length;
                var total = $('#accountsTable tbody tr').length;
                $('#accountCount').text(visible < total ? 'Showing ' + visible + ' of ' + total + ' rows' : '');
            }

            $('#accountSearch').on('input', function() {
                var q = $(this).val().toLowerCase().trim();

                if (q === '') {
                    $('#accountsTable tbody tr').show();
                    updateAccountCount();
                    return;
                }

                // Hide all rows first
                $('#accountsTable tbody tr').hide();

                // Loop each main account row
                $('#accountsTable tbody tr.account-main-row').each(function() {
                    var $mainRow = $(this);
                    var mainId = $mainRow.data('main-id');
                    var $children = $('#accountsTable tbody tr.account-main-' + mainId);

                    var mainMatch = $mainRow.data('name').includes(q);
                    var childrenMatch = false;

                    $children.each(function() {
                        if ($(this).data('name').includes(q)) childrenMatch = true;
                    });

                    if (mainMatch) {
                        $mainRow.show();
                        $children.show();
                    } else if (childrenMatch) {
                        $mainRow.show();
                        $children.each(function() {
                            if ($(this).data('name').includes(q)) $(this).show();
                        });
                    }
                });

                updateAccountCount();
            });

        });
    </script>
@endpush
