{{--
# ────────────── lee_gwena ──────────────
# Code by: ashley_gwena
# Created: 2026-03-12
# Notes: Trust account edit form
# ───────────────────────────────────────
--}}
@extends('layouts.master')

@section('title', 'Edit Trust Account')

@section('content')
@include('chart_of_accounts.partials.form-styles')
<div class="container py-4 coa-form">
    <div class="coa-header">
        <div>
            <h1 class="h3 mb-1">Edit Trust Account</h1>
            <p>Update trust ledger details.</p>
        </div>
        <div class="coa-actions">
            <a href="{{ route('trust-accounts.index') }}" class="btn btn-outline-secondary">Back</a>
        </div>
    </div>

    <form method="POST" action="{{ route('trust-accounts.update', $trustAccount) }}" class="card p-4 coa-card">
        @csrf
        @method('PUT')
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label">Client</label>
                <div style="position:relative;">
                    <input class="form-control" id="client_search" name="client_id" value="{{ old('client_id', $trustAccount->client_id) }}" placeholder="Search client by name" autocomplete="off" required>
                    <div id="client_results" style="position:absolute;left:0;right:0;top:100%;z-index:20;background:#fff;border:1px solid #e3e8ee;border-radius:10px;box-shadow:0 10px 20px rgba(13,31,45,0.08);display:none;max-height:220px;overflow:auto;"></div>
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label">Matter</label>
                @php
                    $selectedMatterIds = collect(old('matter_ids', $trustAccount->matters->pluck('id')->all()));
                @endphp
                <input type="text" class="form-control mb-2" id="matter_filter" placeholder="Search matter number">
                <select name="matter_ids[]" id="matter_ids" class="form-select" multiple size="6">
                    @foreach($matters as $matter)
                        <option value="{{ $matter->id }}" {{ $selectedMatterIds->contains($matter->id) ? 'selected' : '' }}>
                            {{ $matter->matter_number }} - {{ $matter->matter_title }}
                        </option>
                    @endforeach
                </select>
                <div class="text-muted mt-1" style="font-size:12px;">Select one or more matters.</div>
            </div>
            <div class="col-md-6">
                <label class="form-label">Account Number</label>
                <input type="text" name="account_number" value="{{ old('account_number', $trustAccount->account_number) }}" class="form-control" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">Currency</label>
                <select name="currency" class="form-select" required>
                    @foreach($currencies as $currency)
                        <option value="{{ $currency->currency_code }}" {{ old('currency', $trustAccount->currency) == $currency->currency_code ? 'selected' : '' }}>
                            {{ $currency->currency_code }} - {{ $currency->currency_name }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Status</label>
                <select name="status" class="form-select" required>
                    <option value="active" {{ old('status', $trustAccount->status) === 'active' ? 'selected' : '' }}>Active</option>
                    <option value="suspended" {{ old('status', $trustAccount->status) === 'suspended' ? 'selected' : '' }}>Suspended</option>
                    <option value="closed" {{ old('status', $trustAccount->status) === 'closed' ? 'selected' : '' }}>Closed</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Opened At</label>
                <input type="date" name="opened_at" value="{{ old('opened_at', optional($trustAccount->opened_at)->toDateString()) }}" class="form-control" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">Closed At</label>
                <input type="date" name="closed_at" value="{{ old('closed_at', optional($trustAccount->closed_at)->toDateString()) }}" class="form-control">
            </div>
        </div>
        <div class="mt-4">
            <button class="btn btn-primary" type="submit">Update Trust Account</button>
        </div>
    </form>

    @if($trustAccount->status !== 'closed')
        <div class="mt-3">
            <form method="POST" action="{{ route('trust-accounts.terminate', $trustAccount) }}" onsubmit="return confirm('Terminate this trust account? This cannot be undone.');">
                @csrf
                <button class="btn btn-outline-danger" type="submit">Terminate Trust Account</button>
            </form>
            <div class="text-muted" style="margin-top:8px;">Termination closes the account but keeps records for audit.</div>
        </div>
    @endif
</div>

<script>
    (function () {
        const filter = document.getElementById('matter_filter');
        const select = document.getElementById('matter_ids');
        if (!filter || !select) return;

        filter.addEventListener('input', () => {
            const term = filter.value.toLowerCase().trim();
            Array.from(select.options).forEach(option => {
                const text = option.textContent.toLowerCase();
                option.style.display = text.includes(term) ? '' : 'none';
            });
        });
    })();

    (function () {
        const input = document.getElementById('client_search');
        const results = document.getElementById('client_results');
        const clients = @json($clients->map(fn($c) => ['id' => $c->id, 'name' => $c->full_name])->values());
        if (!input || !results) return;

        const render = (items) => {
            results.innerHTML = '';
            if (!items.length) {
                results.style.display = 'none';
                return;
            }
            items.forEach(item => {
                const row = document.createElement('div');
                row.textContent = item.name;
                row.style.padding = '8px 12px';
                row.style.cursor = 'pointer';
                row.addEventListener('mouseenter', () => row.style.background = '#f5f8fb');
                row.addEventListener('mouseleave', () => row.style.background = '#fff');
                row.addEventListener('click', () => {
                    input.value = item.id;
                    input.setAttribute('data-label', item.name);
                    results.style.display = 'none';
                });
                results.appendChild(row);
            });
            results.style.display = 'block';
        };

        input.addEventListener('input', () => {
            const term = input.value.trim().toLowerCase();
            if (!term) {
                results.style.display = 'none';
                return;
            }
            const filtered = clients.filter(c => c.name.toLowerCase().includes(term)).slice(0, 20);
            render(filtered);
        });

        document.addEventListener('click', (e) => {
            if (!results.contains(e.target) && e.target !== input) {
                results.style.display = 'none';
            }
        });
    })();
</script>
@endsection
