@extends('layouts.app')
@section('title', 'Dimension Values')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{{ route('dimensions.index') }}">Dimensions</a></li>
    <li class="breadcrumb-item active">{{ $dimension->name }}</li>
@endsection

@section('content')
<div class="page-header">
    <div>
        <div class="d-flex align-items-center gap-2">
            <span class="badge rounded-pill fs-6 px-3" style="background:var(--primary);color:#fff">D{{ $dimension->slot }}</span>
            <h1 class="page-title mb-0">{{ $dimension->name }}</h1>
        </div>
        <p class="page-subtitle mt-1">Manage values for this dimension</p>
    </div>
    <a href="{{ route('dimensions.index') }}" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i>Back
    </a>
</div>

<div class="row g-4">
    {{-- Add Value --}}
    <div class="col-12 col-xl-4">
        <div class="card">
            <div class="card-header fw-semibold">
                <i class="bi bi-plus-circle me-2 text-primary"></i>Add Value
            </div>
            <div class="card-body">
                <form method="POST" action="{{ route('dimensions.values.store', $dimension) }}">
                @csrf
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label fw-semibold">Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" required autofocus
                               class="form-control @error('name') is-invalid @enderror"
                               value="{{ old('name') }}"
                               placeholder="e.g. Head Office">
                        @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Code</label>
                        <input type="text" name="code" class="form-control"
                               value="{{ old('code') }}" placeholder="e.g. HO (optional)">
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Parent</label>
                        <select name="parent_id" class="form-select select2">
                            <option value="">— Top Level —</option>
                            @foreach($values as $val)
                                <option value="{{ $val->id }}" {{ old('parent_id') == $val->id ? 'selected':'' }}>
                                    {{ str_repeat('›  ', $val->depth) }}{{ $val->code ? "[{$val->code}] " : "" }}{{ $val->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Sort Order</label>
                        <input type="number" name="sort_order" class="form-control"
                               value="{{ old('sort_order', 0) }}" min="0" placeholder="0">
                        <div class="form-text">Lower numbers appear first</div>
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-plus-circle me-1"></i>Add Value
                        </button>
                    </div>
                </div>
                </form>
            </div>
        </div>
    </div>

    {{-- Values Tree --}}
    <div class="col-12 col-xl-8">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <span class="fw-semibold">
                    <i class="bi bi-diagram-3 me-2 text-primary"></i>{{ $dimension->name }} Values
                </span>
                <div class="d-flex align-items-center gap-2">
                    <span class="badge bg-light text-dark border">{{ $values->count() }} values</span>
                    <button class="btn btn-outline-secondary btn-sm" id="dvExpandAll">
                        <i class="bi bi-arrows-expand"></i>
                    </button>
                    <button class="btn btn-outline-secondary btn-sm" id="dvCollapseAll">
                        <i class="bi bi-arrows-collapse"></i>
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                @if(count($tree) === 0)
                <div class="text-center py-5 text-muted">
                    <i class="bi bi-diagram-3 display-5 d-block mb-2"></i>
                    No values yet. Add your first value using the form.
                </div>
                @else
                <div class="table-responsive">
                    <table class="table table-hover mb-0" style="min-width:400px">
                        <thead class="table-light">
                            <tr>
                                <th>Name</th>
                                <th class="d-none d-sm-table-cell" style="width:100px">Code</th>
                                <th class="d-none d-md-table-cell text-center" style="width:60px">Sort</th>
                                <th style="width:80px">Status</th>
                                <th class="text-end pe-3" style="width:80px">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @include('accounting.dimensions._value_tree', [
                                'items'     => $tree,
                                'level'     => 0,
                                'dimension' => $dimension,
                                'allValues' => $values,
                            ])
                        </tbody>
                    </table>
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

{{-- Edit Modal --}}
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-semibold">
                    <i class="bi bi-pencil me-2 text-primary"></i>Edit Value
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body pt-2">
                <form method="POST" id="editForm">
                @csrf @method('PUT')
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label fw-semibold">Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="editName" class="form-control" required>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Code</label>
                        <input type="text" name="code" id="editCode" class="form-control" placeholder="Optional">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Sort Order</label>
                        <input type="number" name="sort_order" id="editSort" class="form-control" min="0">
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Parent</label>
                        <select name="parent_id" id="editParent" class="form-select">
                            <option value="">— Top Level —</option>
                            @foreach($values as $val)
                                <option value="{{ $val->id }}">
                                    {{ str_repeat('›  ', $val->depth) }}{{ $val->code ? "[{$val->code}] " : '' }}{{ $val->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-12">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_active" value="1" id="editActive">
                            <label class="form-check-label" for="editActive">Active</label>
                        </div>
                    </div>
                </div>
                </form>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary px-4" id="saveEditBtn">
                    <i class="bi bi-check-circle me-1"></i>Save Changes
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
// Edit modal
document.querySelectorAll('.btn-edit-val').forEach(btn => {
    btn.addEventListener('click', function() {
        const currentId = this.dataset.id || '';
        const descendants = JSON.parse(this.dataset.descendants || '[]').map(String);
        const parentSelect = document.getElementById('editParent');

        document.getElementById('editForm').action = this.dataset.url;
        document.getElementById('editCode').value  = this.dataset.code || '';
        document.getElementById('editName').value  = this.dataset.name;
        document.getElementById('editSort').value  = this.dataset.sort || 0;
        document.getElementById('editActive').checked = this.dataset.active === '1';

        parentSelect.querySelectorAll('option').forEach(option => {
            if (!option.value) {
                option.disabled = false;
                return;
            }

            const optionId = String(option.value);
            option.disabled = optionId === String(currentId) || descendants.includes(optionId);
        });

        parentSelect.value = this.dataset.parent || '';
        if (parentSelect.selectedOptions[0]?.disabled) {
            parentSelect.value = '';
        }

        new bootstrap.Modal(document.getElementById('editModal')).show();
    });
});
document.getElementById('saveEditBtn').addEventListener('click', function() {
    document.getElementById('editForm').submit();
});

// Tree expand/collapse for dimension values
const dvState = {};
function dvToggle(id) {
    const isOpen = dvState[id];
    dvState[id] = !isOpen;
    const icon = document.querySelector(`.dv-toggle[data-id="${id}"] .dv-icon`);
    document.querySelectorAll(`.dv-row[data-parent="${id}"]`).forEach(row => {
        if (isOpen) {
            row.style.display = 'none';
            dvCollapseChildren(row.dataset.id);
        } else {
            row.style.display = '';
        }
    });
    if (icon) {
        icon.classList.toggle('bi-chevron-down', !isOpen);
        icon.classList.toggle('bi-chevron-right', isOpen);
    }
}
function dvCollapseChildren(id) {
    if (!id) return;
    dvState[id] = false;
    const icon = document.querySelector(`.dv-toggle[data-id="${id}"] .dv-icon`);
    if (icon) { icon.classList.remove('bi-chevron-down'); icon.classList.add('bi-chevron-right'); }
    document.querySelectorAll(`.dv-row[data-parent="${id}"]`).forEach(r => { r.style.display = 'none'; dvCollapseChildren(r.dataset.id); });
}
document.addEventListener('click', function(e) {
    const btn = e.target.closest('.dv-toggle');
    if (btn) dvToggle(btn.dataset.id);
});
document.getElementById('dvExpandAll').addEventListener('click', () => {
    document.querySelectorAll('.dv-row').forEach(r => r.style.display = '');
    document.querySelectorAll('.dv-icon').forEach(i => { i.classList.add('bi-chevron-down'); i.classList.remove('bi-chevron-right'); });
    document.querySelectorAll('.dv-toggle').forEach(b => dvState[b.dataset.id] = true);
});
document.getElementById('dvCollapseAll').addEventListener('click', () => {
    document.querySelectorAll('.dv-row[data-level]:not([data-level="0"])').forEach(r => r.style.display = 'none');
    document.querySelectorAll('.dv-icon').forEach(i => { i.classList.remove('bi-chevron-down'); i.classList.add('bi-chevron-right'); });
    document.querySelectorAll('.dv-toggle').forEach(b => dvState[b.dataset.id] = false);
});
</script>
@endpush
