@extends('layouts.app')
@section('title', $branch->exists ? 'Edit Branch' : 'New Branch')
@section('content')
@php
    $selectedBusinessId = (int) old('business_id', $branch->business_id ?: $businesses->first()?->id);
    $selectedLoanProductIds = collect(
        old('loan_product_selection_present')
            ? old('loan_product_ids', [])
            : ($branch->exists ? $branch->loanProducts->pluck('id')->all() : [])
    )->map(fn ($id) => (int) $id);
@endphp
<x-ui.form-shell
    :title="$branch->exists ? 'Edit Branch' : 'Create Branch'"
    description="Configure branch identity, management, location, loan products and contact information."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Branches','url'=>route('admin.branches.index')],['label'=>$branch->exists?'Edit Branch':'Create Branch']]"
>
    <form method="POST" action="{{ $branch->exists ? route('admin.branches.update',$branch) : route('admin.branches.store') }}" class="mf-form">
        @csrf
        @if($branch->exists)@method('PUT')@endif

        <x-ui.form-section title="Branch identity & governance" description="The branch name, system-generated code, manager and operating status.">
            <x-ui.form-grid>
                <div class="mf-col-3"><label class="mf-field-label">Business</label><select id="branch-business" name="business_id" class="mf-input" required>@foreach($businesses as $business)<option value="{{ $business->id }}" @selected($selectedBusinessId===$business->id)>{{ $business->name }}</option>@endforeach</select>@error('business_id')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
                <div class="mf-col-4"><label class="mf-field-label">Branch name</label><input name="name" value="{{ old('name',$branch->name) }}" class="mf-input" required>@error('name')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
                <div class="mf-col-2">
                    <label class="mf-field-label">Branch code</label>
                    <input value="{{ $branch->exists ? $branch->code : 'Generated automatically' }}" class="mf-input" readonly aria-readonly="true">
                    <p class="mf-field-help">Assigned by the system when the branch is created and cannot be changed.</p>
                </div>
                <div class="mf-col-3"><label class="mf-field-label">Status</label><select name="status" class="mf-input"><option value="active" @selected(old('status',$branch->status ?: 'active')==='active')>Active</option><option value="inactive" @selected(old('status',$branch->status)==='inactive')>Inactive</option></select></div>
                <div class="mf-col-4"><label class="mf-field-label">Branch manager</label><select name="manager_user_id" class="mf-input"><option value="">Not assigned</option>@foreach($managers as $manager)<option value="{{ $manager->id }}" @selected(old('manager_user_id',$branch->manager_user_id)==$manager->id)>{{ $manager->name }}</option>@endforeach</select></div>
                <div class="mf-col-3"><label class="mf-field-label">Opening date</label><input type="date" name="opening_date" value="{{ old('opening_date',optional($branch->opening_date)->format('Y-m-d')) }}" class="mf-input"></div>
            </x-ui.form-grid>
        </x-ui.form-section>

        <x-ui.form-section title="Loan products" description="By default this branch can use every loan product for its business. Select products only when you want to restrict this branch.">
            <input type="hidden" name="loan_product_selection_present" value="1">
            <p class="mf-field-help mb-3">Leave every product unchecked to allow all current and future loan products. If you select one or more, only those selected products will be available at this branch.</p>
            <div class="mf-option-grid" id="branch-loan-products">
                @forelse($loanProducts as $product)
                    <label class="mf-option" data-loan-product-business="{{ $product->business_id }}">
                        <input type="checkbox" name="loan_product_ids[]" value="{{ $product->id }}" @checked($selectedLoanProductIds->contains($product->id))>
                        <span>
                            <strong>{{ $product->name }}</strong>
                            <small class="block text-muted-foreground">{{ str($product->status)->title() }} · {{ number_format((float)$product->minimum_amount, 2) }}–{{ number_format((float)$product->maximum_amount, 2) }}</small>
                        </span>
                    </label>
                @empty
                    <p class="text-sm text-muted-foreground">No loan products have been created yet.</p>
                @endforelse
            </div>
            @error('loan_product_ids')<p class="mf-field-error">{{ $message }}</p>@enderror
            @error('loan_product_ids.*')<p class="mf-field-error">{{ $message }}</p>@enderror
        </x-ui.form-section>

        <x-ui.form-section title="Location" description="Administrative and physical location details used in reports, customer records and official documents.">
            <x-ui.form-grid>
                <div class="mf-col-4"><label class="mf-field-label">Location</label><input name="location" value="{{ old('location',$branch->location) }}" class="mf-input">@error('location')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
                <div class="mf-col-4"><label class="mf-field-label">Address</label><input name="address" value="{{ old('address',$branch->address) }}" class="mf-input">@error('address')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
                <div class="mf-col-2"><label class="mf-field-label">Region</label><input name="region" value="{{ old('region',$branch->region) }}" class="mf-input">@error('region')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
                <div class="mf-col-2"><label class="mf-field-label">District</label><input name="district" value="{{ old('district',$branch->district) }}" class="mf-input">@error('district')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
            </x-ui.form-grid>
        </x-ui.form-section>

        <x-ui.form-section title="Contact information" description="Official communication channels for this branch.">
            <x-ui.form-grid>
                <div class="mf-col-3"><label class="mf-field-label">Phone</label><input name="phone" value="{{ old('phone',$branch->phone) }}" class="mf-input">@error('phone')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
                <div class="mf-col-5"><label class="mf-field-label">Email</label><input type="email" name="email" value="{{ old('email',$branch->email) }}" class="mf-input">@error('email')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
            </x-ui.form-grid>
        </x-ui.form-section>

        <x-ui.form-actions>
            <a class="mf-btn" href="{{ route('admin.branches.index') }}">Cancel</a>
            <button class="mf-btn mf-btn-primary">Save branch</button>
        </x-ui.form-actions>
    </form>
</x-ui.form-shell>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', () => {
    const business = document.getElementById('branch-business');
    const products = [...document.querySelectorAll('[data-loan-product-business]')];

    function filterLoanProducts(clearMismatched = false) {
        const businessId = business?.value || '';
        products.forEach((item) => {
            const mismatched = !!businessId && item.dataset.loanProductBusiness !== businessId;
            item.hidden = mismatched;
            if (clearMismatched && mismatched) item.querySelector('input').checked = false;
        });
    }

    business?.addEventListener('change', () => filterLoanProducts(true));
    filterLoanProducts(true);
});
</script>
@endpush
