@php
    $entityCrudView = 'administracion.crud.entities.' . $entity;
@endphp
@extends('layouts.app')

@section('title', ($mode === 'create' ? 'Crear ' : 'Editar ') . $entitySingularLabel)

@section('content')
    <div class="mb-3">
        <a href="{{ url()->previous() }}" class="btn  btn-outline-secondary">
            Volver
        </a>
    </div>
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-3">
        <h1 class="h3 mb-0">{{ $mode === 'create' ? 'Crear' : 'Editar' }} {{ $entitySingularLabel }}</h1>
        <a class="btn btn-outline-secondary" href="{{ route('administracion.crud.index', ['entity' => $entity]) }}">Volver al listado</a>
    </div>

    <form class="card card-soft" method="POST" enctype="multipart/form-data" action="{{ $mode === 'create' ? route('administracion.crud.store', ['entity' => $entity]) : route('administracion.crud.update', ['entity' => $entity, 'id' => data_get($record, $primaryKey)]) }}" autocomplete="off">
        <div class="card-body p-4">
            @csrf
            @if ($mode === 'edit')
                @method('PUT')
            @endif
            <input type="hidden" name="__form_mode" value="{{ $mode }}">

            @php
                $currentFormMode = $mode;
                $editableColumns = $columns;
                $resourceCandidates = [
                    resource_path('views/' . str_replace('.', '/', $entityCrudView) . '/recursos-formulario.php'),
                    resource_path('views/administracion/crud/entities/' . $entity . '/recursos-formulario.php'),
                    resource_path('views/administracion/crud/partials/comun/formulario/recursos.php'),
                ];
                $formResources = null;

                foreach (array_unique($resourceCandidates) as $resourceFile) {
                    if (! is_file($resourceFile)) {
                        continue;
                    }

                    $resolvedResources = require $resourceFile;

                    if (is_array($resolvedResources)) {
                        $formResources = $resolvedResources;
                        break;
                    }
                }

                if (! is_array($formResources)) {
                    throw new RuntimeException('Unable to resolve CRUD form resources for entity [' . $entity . '].');
                }

                extract($formResources, EXTR_SKIP);

                $usuarioPhotoUrl = null;
                $bienPhotoUrl = null;
                $requiredColumnsByEntity = [
                    'users' => ['cedula', 'password', 'nombre', 'cargo', 'fechaIngreso'],
                    'sitios' => ['nombre', 'responsable', 'cantidad_personas', 'activo'],
                    'embarcaciones' => ['imo', 'nombre', 'responsable', 'cantidad_personas', 'tipo_buque', 'bandera', 'ubicacion', 'activo'],
                    'bienes' => ['descripcion', 'relacionUnidades'],
                    'dependencias' => ['nombre'],
                    'transportes' => ['tipo', 'identificacion', 'conductor', 'estado'],
                    'tipos-insumos' => ['nombre'],
                    'tallas-uniformes' => ['cedula_usuario', 'tallaCamisa', 'tallaChaqueta', 'tallaPantalon', 'tallaBotas', 'tallaZapatos'],
                    'registros-stock' => ['codigo', 'cantidad', 'objetivo'],
                    'num-operaciones' => ['numero', 'tipo'],
                ];
                $requiredColumns = $requiredColumnsByEntity[$entity] ?? [];
                $isImportantField = static fn (string $column): bool => in_array($column, $requiredColumns, true);
                $fieldLabel = static fn (string $column): string => $columnLabels[$column] ?? ucfirst(str_replace('_', ' ', $column));
                if ($isPersonalEntity) {
                    $cedulaFoto = trim((string) data_get($record, 'cedula', ''));
                    if ($cedulaFoto !== '') {
                        foreach (['jpg', 'png', 'webp'] as $ext) {
                            $relativePath = 'foto_usuarios/' . $cedulaFoto . '.' . $ext;
                            if (is_file(public_path($relativePath))) {
                                $usuarioPhotoUrl = asset($relativePath);
                                break;
                            }
                        }
                    }
                }

                if ($entity === 'bienes') {
                    $codigoFoto = trim((string) data_get($record, 'codigo', ''));
                    if ($codigoFoto !== '') {
                        foreach (['jpg', 'png', 'webp'] as $ext) {
                            $relativePath = 'foto_bienes/' . $codigoFoto . '.' . $ext;
                            if (is_file(public_path($relativePath))) {
                                $bienPhotoUrl = asset($relativePath);
                                break;
                            }
                        }
                    }
                }
            @endphp

            <div class="row g-3">
                <div class="col-12">
                    <div class="form-text mt-0">Los campos marcados con <span class="text-danger">*</span> son obligatorios.</div>
                </div>
                @includeFirst([
                    $entityCrudView . '.campos-formulario-pagina',
                    'administracion.crud.partials.campos-formulario-pagina',
                ])
            </div>

            <div class="d-flex gap-2 mt-4">
                <button class="btn btn-brand" type="submit">{{ $mode === 'create' ? 'Guardar' : 'Actualizar' }}</button>
                <a class="btn btn-outline-secondary" href="{{ route('administracion.crud.index', ['entity' => $entity]) }}">Cancelar</a>
            </div>
        </div>
    </form>
@endsection

@push('scripts')
    @include('administracion.crud.partials.comun.scripts.base-formulario-pagina')
    @includeFirst([
        $entityCrudView . '.scripts-formulario-pagina',
        'administracion.crud.partials.scripts-formulario-pagina',
    ])
@endpush
