@extends('layouts.app')

@section('content')
<x-app-layout>
    <x-slot name="header">
        <div class="flex justify-between items-center">
            <h2 class="font-semibold text-l text-gray-800 leading-tight">
                {{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.TreeTitle', __('Cost Centers Tree')) }}
            </h2>
            <div>
                <a href="{{ route('accounting.cost-centers.index') }}" class="inline-flex items-center p-4 py-2 bg-gray-600 border border-transparent rounded-md font-semibold text-s text-white uppercase tracking-widest hover:bg-gray-700 focus:bg-gray-700 active:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition ease-in-out duration-150">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
                    </svg>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.BackToList', __('Back to List')) }}
                </a>
            </div>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7l m-auto sm:p-6 lg:p-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <div class="mb-4 flex justify-between items-center">
                        <div>
                            <h3 class="text-lg font-medium text-gray-900">{{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.TreeTitle', __('Cost Centers Tree')) }}</h3>
                            <p class="mt-1 text-sm text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.TreeDescription', __('View hierarchical structure of cost centers')) }}</p>
                        </div>
                        <div class="flex gap-2">
                            <button id="expand-all" class="inline-flex items-center px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-150">
                                <i class="fas fa-expand-alt ml-2"></i>
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.ExpandAll', __('Expand All')) }}
                            </button>
                            <button id="collapse-all" class="inline-flex items-center px-3 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors duration-150">
                                <i class="fas fa-compress-alt ml-2"></i>
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.CollapseAll', __('Collapse All')) }}
                            </button>
                        </div>
                    </div>

                    <div class="mt-6">
                        <ul class="space-y-2" id="cost-centers-tree">
                            @forelse ($costCenters as $costCenter)
                                <li class="border-r-2 border-gray-300 pr-4 tree-item" data-center-id="{{ $costCenter->id }}">
                                    <div class="flex items-center">
                                        @if ($costCenter->children && $costCenter->children->count() > 0)
                                            <button class="toggle-btn mr-2 p-1 hover:bg-gray-100 rounded transition-colors duration-150" data-center-id="{{ $costCenter->id }}" title="{{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.ToggleExpand', __('Expand/Collapse')) }}">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-600 transition-transform duration-200 transform" viewBox="0 0 20 20" fill="currentColor" style="transform: rotate(-90deg);">
                                                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                                                </svg>
                                            </button>
                                        @else
                                            <div class="mr-2 p-1 w-8"></div>
                                        @endif
                                        
                                        <div class="flex-shrink-0">
                                            @if ($costCenter->center_type === 'parent')
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-blue-500" viewBox="0 0 20 20" fill="currentColor">
                                                    <path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" />
                                                </svg>
                                            @else
                                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-500" viewBox="0 0 20 20" fill="currentColor">
                                                    <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clip-rule="evenodd" />
                                                </svg>
                                            @endif
                                        </div>
                                        <div class="mr-3 flex-grow">
                                            <div class="text-sm font-medium text-gray-900">
                                                <a href="{{ route('accounting.cost-centers.show', $costCenter) }}" class="hover:underline">
                                                    {{ $costCenter->code }} - {{ $costCenter->name_ar }}
                                                </a>
                                                @if ($costCenter->status === 'inactive')
                                                    <span class="inline-flex items-center p-2.5 py-0.5 rounded-full text-s font-medium bg-red-100 text-red-800 mr-2">
                                                        {{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.Inactive', __('Inactive')) }}
                                                    </span>
                                                @endif
                                            </div>
                                            <div class="text-s text-gray-500">
                                                @if ($costCenter->type)
                                                    {{ $costCenter->type->name_ar }} -
                                                @endif
                                                @if ($costCenter->center_type === 'parent')
                                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.ParentCenter', __('Parent Center')) }}
                                                @else
                                                    {{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.SubCenter', __('Sub Center')) }}
                                                @endif
                                                @if ($costCenter->budget)
                                                    - {{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.Budget', __('Budget')) }}: {{ number_format($costCenter->budget, 2) }}
                                                @endif
                                            </div>
                                        </div>
                                    </div>

                                    @if ($costCenter->children && $costCenter->children->count() > 0)
                                        <ul class="children-container mt-2 space-y-2 mr-6 border-r-2 border-gray-200 pr-4" id="children-{{ $costCenter->id }}" style="display: block;">
                                            @foreach ($costCenter->children as $child)
                                                @include('cost-centers.partials.cost-center-tree-item', ['costCenter' => $child])
                                            @endforeach
                                        </ul>
                                    @endif
                                </li>
                            @empty
                                <li class="text-sm text-gray-500">{{ \App\Helpers\TranslationHelper::transFromDatabase('CostCenters.NoData', __('No cost centers added')) }}</li>
                            @endforelse
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const treeContainer = document.getElementById('cost-centers-tree');

            treeContainer.addEventListener('click', function(e) {
                const toggleBtn = e.target.closest('.toggle-btn');
                
                if (toggleBtn) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    const centerId = toggleBtn.getAttribute('data-center-id');
                    const childrenContainer = document.getElementById('children-' + centerId);
                    const icon = toggleBtn.querySelector('svg');
                    
                    if (childrenContainer) {
                        const isHidden = childrenContainer.style.display === 'none';
                        childrenContainer.style.display = isHidden ? 'block' : 'none';
                        
                        if (isHidden) {
                            icon.style.transform = 'rotate(-90deg)';
                        } else {
                            icon.style.transform = 'rotate(0deg)';
                        }
                        
                        const expanded = JSON.parse(localStorage.getItem('costCentersExpanded') || '{}');
                        expanded[centerId] = isHidden;
                        localStorage.setItem('costCentersExpanded', JSON.stringify(expanded));
                    }
                }
            });

            document.getElementById('expand-all')?.addEventListener('click', function() {
                const childContainers = document.querySelectorAll('.children-container');
                const toggleBtns = document.querySelectorAll('.toggle-btn');
                
                childContainers.forEach(container => {
                    container.style.display = 'block';
                });
                
                toggleBtns.forEach(btn => {
                    const icon = btn.querySelector('svg');
                    icon.style.transform = 'rotate(-90deg)';
                    const centerId = btn.getAttribute('data-center-id');
                    const expanded = JSON.parse(localStorage.getItem('costCentersExpanded') || '{}');
                    expanded[centerId] = true;
                    localStorage.setItem('costCentersExpanded', JSON.stringify(expanded));
                });
            });

            document.getElementById('collapse-all')?.addEventListener('click', function() {
                const childContainers = document.querySelectorAll('.children-container');
                const toggleBtns = document.querySelectorAll('.toggle-btn');
                
                childContainers.forEach(container => {
                    container.style.display = 'none';
                });
                
                toggleBtns.forEach(btn => {
                    const icon = btn.querySelector('svg');
                    icon.style.transform = 'rotate(0deg)';
                    const centerId = btn.getAttribute('data-center-id');
                    const expanded = JSON.parse(localStorage.getItem('costCentersExpanded') || '{}');
                    expanded[centerId] = false;
                    localStorage.setItem('costCentersExpanded', JSON.stringify(expanded));
                });
            });

            const expanded = JSON.parse(localStorage.getItem('costCentersExpanded') || '{}');
            Object.entries(expanded).forEach(([centerId, isExpanded]) => {
                const childrenContainer = document.getElementById('children-' + centerId);
                const toggleBtn = document.querySelector(`[data-center-id="${centerId}"].toggle-btn`);
                
                if (childrenContainer && toggleBtn) {
                    const icon = toggleBtn.querySelector('svg');
                    if (isExpanded) {
                        childrenContainer.style.display = 'block';
                        icon.style.transform = 'rotate(-90deg)';
                    } else {
                        childrenContainer.style.display = 'none';
                        icon.style.transform = 'rotate(0deg)';
                    }
                }
            });
        });
    </script>
    @endpush
</x-app-layout>
@endsection
