@extends('layouts.app')
@section('title', 'Asset Register')
@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="#">Fixed Assets</a></li>
    <li class="breadcrumb-item active">Asset Register</li>
@endsection

@push('styles')
<style>
    .fa-asset-form-modal {
        width: min(1140px, calc(100vw - 1.5rem));
        max-width: none;
        height: calc(100vh - 1.5rem);
        margin: 0.75rem auto;
    }
    .fa-asset-form-modal .modal-content {
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }
    .fa-asset-form-modal .fa-asset-form-shell {
        display: flex;
        flex-direction: column;
        flex: 1 1 auto;
        min-height: 0;
        overflow: hidden;
    }
    .fa-asset-form-modal .modal-body {
        flex: 1 1 auto;
        min-height: 0;
        overflow-y: auto;
        overscroll-behavior: contain;
    }
    .fa-asset-form-modal .modal-header,
    .fa-asset-form-modal .modal-footer {
        flex-shrink: 0;
    }
</style>
@include('partials.report-datepicker-assets')
@endpush

@section('content')
@php
    $companyId = auth()->user()->company_id;
    $fmt = fn ($n) => \App\Helpers\NumberHelper::formatAmount((float) $n, $companyId);
@endphp

<div class="page-header">
    <div>
        <h1 class="page-title"><i class="bi bi-building me-2 text-primary"></i>Asset Register</h1>
        <p class="page-subtitle">
            {{ $stats['total'] }} assets &nbsp;·&nbsp;
            <span class="text-success">{{ $stats['active'] }} active</span> &nbsp;·&nbsp;
            Cost {{ $fmt($stats['total_cost']) }} &nbsp;·&nbsp;
            Book value {{ $fmt($stats['total_book']) }}
        </p>
    </div>
    @if(auth()->user()->hasPermission('fixed_assets', 'edit'))
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#assetAddModal">
        <i class="bi bi-plus-lg me-1"></i>New Asset
    </button>
    @endif
</div>

@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-3">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif
@if($errors->any())
<div class="alert alert-danger alert-dismissible mb-3">
    @foreach($errors->all() as $e)<div>{{ $e }}</div>@endforeach
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

<div class="card mb-3">
    <div class="card-body py-2 px-3">
        <form method="GET">
            <div class="row g-2 align-items-center">
                <div class="col-12 col-md-4">
                    <input type="text" name="search" class="form-control form-control-sm" placeholder="Search code, name, serial, location…" value="{{ request('search') }}">
                </div>
                <div class="col-6 col-md-2">
                    <select name="category_id" class="form-select form-select-sm">
                        <option value="">All Categories</option>
                        @foreach($categories as $id => $name)
                        <option value="{{ $id }}" {{ (string) request('category_id') === (string) $id ? 'selected' : '' }}>{{ $name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-md-2">
                    <select name="status" class="form-select form-select-sm">
                        <option value="">All Status</option>
                        @foreach($statuses as $value => $label)
                        <option value="{{ $value }}" {{ request('status') === $value ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-3 col-md-1">
                    <button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-search"></i></button>
                </div>
                <div class="col-3 col-md-1">
                    <a href="{{ route('fixed-assets.register.index') }}" class="btn btn-outline-secondary btn-sm w-100"><i class="bi bi-x-lg"></i></a>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0" style="min-width:1100px">
                <thead class="table-light">
                    <tr>
                        <th class="ps-4">Code</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Purchase Date</th>
                        <th class="text-end">Cost</th>
                        <th class="text-end">Accum. Dep.</th>
                        <th class="text-end">Book Value</th>
                        <th>Status</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($assets as $asset)
                    <tr class="{{ !$asset->is_active ? 'table-secondary' : '' }}">
                        <td class="ps-4 text-muted" style="font-size:13px">{{ $asset->code }}</td>
                        <td>
                            <div class="fw-semibold" style="font-size:13.5px">{{ $asset->name }}</div>
                            @if($asset->location)
                            <div class="text-muted" style="font-size:12px">{{ $asset->location }}</div>
                            @endif
                        </td>
                        <td style="font-size:13px">{{ $asset->category?->name ?? '—' }}</td>
                        <td style="font-size:13px">{{ $asset->purchase_date?->format('d-m-Y') ?? '—' }}</td>
                        <td class="text-end" style="font-size:13px">{{ $fmt($asset->purchase_cost) }}</td>
                        <td class="text-end" style="font-size:13px">{{ $fmt($asset->accumulated_depreciation) }}</td>
                        <td class="text-end fw-semibold" style="font-size:13px">{{ $fmt($asset->bookValue()) }}</td>
                        <td><span class="badge bg-light text-dark border" style="font-size:11px">{{ $asset->statusLabel() }}</span></td>
                        <td class="text-end pe-3">
                            @if(auth()->user()->hasPermission('fixed_assets', 'edit'))
                            <div class="d-flex justify-content-end gap-1">
                                <button type="button" class="btn btn-outline-secondary btn-sm btn-edit-asset"
                                        data-url="{{ route('fixed-assets.register.update', $asset) }}"
                                        data-json="{{ e(json_encode([
                                            'category_id' => $asset->category_id,
                                            'code' => $asset->code,
                                            'name' => $asset->name,
                                            'location' => $asset->location,
                                            'serial_number' => $asset->serial_number,
                                            'purchase_date' => optional($asset->purchase_date)->format('Y-m-d'),
                                            'in_service_date' => optional($asset->in_service_date)->format('Y-m-d'),
                                            'purchase_cost' => $asset->purchase_cost,
                                            'salvage_value' => $asset->salvage_value,
                                            'useful_life_months' => $asset->useful_life_months,
                                            'depreciation_method' => $asset->depreciation_method,
                                            'asset_account_id' => $asset->asset_account_id,
                                            'accum_depreciation_account_id' => $asset->accum_depreciation_account_id,
                                            'depreciation_expense_account_id' => $asset->depreciation_expense_account_id,
                                            'notes' => $asset->notes,
                                            'is_active' => $asset->is_active ? '1' : '0',
                                        ])) }}"
                                        title="Edit"><i class="bi bi-pencil"></i></button>
                                <form method="POST" action="{{ route('fixed-assets.register.toggle', $asset) }}">
                                    @csrf @method('PATCH')
                                    <button type="submit" class="btn btn-sm {{ $asset->is_active ? 'btn-outline-warning' : 'btn-outline-success' }}"><i class="bi bi-{{ $asset->is_active ? 'eye-slash' : 'eye' }}"></i></button>
                                </form>
                                <form method="POST" action="{{ route('fixed-assets.register.destroy', $asset) }}" onsubmit="return confirm('Delete {{ addslashes($asset->name) }}?')">
                                    @csrf @method('DELETE')
                                    <button type="submit" class="btn btn-outline-danger btn-sm"><i class="bi bi-trash"></i></button>
                                </form>
                            </div>
                            @endif
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="text-center py-5 text-muted">
                            <i class="bi bi-building display-5 d-block mb-2"></i>
                            No fixed assets found.
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($assets->hasPages())
        <div class="px-4 py-3 border-top">{{ $assets->links() }}</div>
        @endif
    </div>
</div>

@include('fixed-assets.register._form-modal', ['modalId' => 'assetAddModal', 'formId' => 'assetAddForm', 'title' => 'New Asset', 'action' => route('fixed-assets.register.store')])
@include('fixed-assets.register._form-modal', ['modalId' => 'assetEditModal', 'formId' => 'assetEditForm', 'title' => 'Edit Asset', 'action' => '', 'method' => 'PUT'])

<script type="application/json" id="fixedAssetAccountTrees">@json($accountTrees)</script>
@endsection

@push('scripts')
<script>
(function () {
    function initFaAccountPickers(scope) {
        if (typeof window.axisInitSalaryComponentAccountPickers !== 'function') {
            return false;
        }
        const faTrees = (function () {
            const el = document.getElementById('fixedAssetAccountTrees');
            if (!el?.textContent?.trim()) {
                return null;
            }
            try {
                return JSON.parse(el.textContent);
            } catch (error) {
                return null;
            }
        })();
        if (faTrees) {
            window.salaryComponentAccountTrees = faTrees;
        }
        window.axisInitSalaryComponentAccountPickers(scope || document);
        return true;
    }

    function refreshFaPicker(form, pickerClass, listKey, value) {
        const picker = form.querySelector('.' + pickerClass);
        if (picker && typeof window.axisRefreshSalaryComponentAccountPicker === 'function') {
            window.axisRefreshSalaryComponentAccountPicker(picker, listKey, value || '');
        }
    }

    function refreshAllFaPickers(form, data) {
        refreshFaPicker(form, 'fa-asset-account-picker', 'asset', data.asset_account_id || '');
        refreshFaPicker(form, 'fa-accum-dep-account-picker', 'asset', data.accum_depreciation_account_id || '');
        refreshFaPicker(form, 'fa-expense-account-picker', 'expense', data.depreciation_expense_account_id || '');
    }

    function waitForPickers(scope, callback) {
        if (initFaAccountPickers(scope)) {
            callback();
            return;
        }
        let attempts = 0;
        const timer = setInterval(function () {
            attempts += 1;
            if (initFaAccountPickers(scope) || attempts > 80) {
                clearInterval(timer);
                callback();
            }
        }, 50);
    }

    function setFormFieldValue(form, key, value) {
        const el = form.querySelector('[name="' + key + '"]');
        if (!el) return;
        if (el.type === 'checkbox') {
            el.checked = value === '1' || value === true;
            return;
        }
        if (el.classList.contains('axis-report-datepicker') && el._flatpickr) {
            el._flatpickr.setDate(value || '', false);
            return;
        }
        el.value = value ?? '';
    }

    function initFaDatepickers() {
        if (typeof window.axisInitReportDatepickers === 'function') {
            window.axisInitReportDatepickers();
        }
    }

    ['assetAddModal', 'assetEditModal'].forEach(function (modalId) {
        document.getElementById(modalId)?.addEventListener('shown.bs.modal', function () {
            const form = this.querySelector('.fa-asset-form');
            initFaDatepickers();
            waitForPickers(form, function () {
                if (modalId === 'assetEditModal' && form?.dataset.pendingEdit) {
                    const data = JSON.parse(form.dataset.pendingEdit);
                    refreshAllFaPickers(form, data);
                    delete form.dataset.pendingEdit;
                }
            });
        });
    });

    document.querySelectorAll('.btn-edit-asset').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const form = document.getElementById('assetEditForm');
            const data = JSON.parse(this.dataset.json);
            form.action = this.dataset.url;
            Object.keys(data).forEach(function (key) {
                setFormFieldValue(form, key, data[key]);
            });
            form.dataset.pendingEdit = JSON.stringify(data);
            if (typeof bootstrap !== 'undefined') {
                bootstrap.Modal.getOrCreateInstance(document.getElementById('assetEditModal')).show();
            }
        });
    });
})();
</script>
@endpush
