{{-- resources/views/peninjauan/edit.blade.php --}}
@extends('admin-layouts.master')

@section('title', 'Edit Peninjauan')

<style>
.nav-tabs .nav-link {
    color: #495057 !important;
}

.nav-tabs .nav-link.active {
    color: #000 !important;
    background-color: #fff !important;
    border: 1px solid #dee2e6;
    border-bottom-color: transparent;
    font-weight: 600;
}
</style>

@section('content')
<div class="">
    <div class="">

        @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            <strong>Terdapat kesalahan pada form:</strong>
            <ul class="mb-0 mt-2">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
        @endif

        <!-- Success Message -->
        @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>
            {{ session('success') }}
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
        @endif

        <!-- Main Form Container -->
        <form id="peninjauanForm" class="mt-3" action="{{ route('peninjauan.update', $peninjauan->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')
            <input type="hidden" name="type_permohonan" id="type_permohonan" value="{{ $peninjauan->type_permohonan }}">
            <input type="hidden" name="coordinates" id="coordinates_input" value="{{ $peninjauan->coordinates }}">

            <div class="card">
                <!-- Navigation Tabs -->
                <div class="card-header p-0">
                    <ul class="nav nav-tabs" id="peninjauanTabs" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="ba-kesaksian-tab" data-toggle="tab" href="#ba-kesaksian" role="tab" aria-controls="ba-kesaksian" aria-selected="true">
                            A. DATA IDENTITAS & WAKTU
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="data-pemohon-tab" data-toggle="tab" href="#data-pemohon" role="tab" aria-controls="data-pemohon" aria-selected="false">
                            B. DATA FISIK TANAH (OBJEK TANAH)
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="batas-tanah-tab" data-toggle="tab" href="#batas-tanah" role="tab" aria-controls="batas-tanah" aria-selected="false">
                                Batas Tanah
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="pendaftaran-tab" data-toggle="tab" href="#pendaftaran" role="tab" aria-controls="pendaftaran" aria-selected="false">
                                Pendaftaran
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="pengukuran-tab" data-toggle="tab" href="#pengukuran" role="tab" aria-controls="pengukuran" aria-selected="false">
                                Pengukuran
                            </a>
                        </li>
                        {{-- <li class="nav-item">
                            <a class="nav-link" id="kesimpulan-tab" data-toggle="tab" href="#kesimpulan" role="tab" aria-controls="kesimpulan" aria-selected="false">
                                Kesimpulan
                            </a>
                        </li> --}}
                    </ul>
                </div>

                <!-- Tab Content -->
                <div class="card-body">
                   <div class="tab-content" id="peninjauanTabContent">
                        @include('admin.peninjauan.partials.edit-tab-ba-kesaksian')
                        @include('admin.peninjauan.partials.edit-tab-data-pemohon')
                        @include('admin.peninjauan.partials.edit-tab-batas-tanah')
                        @include('admin.peninjauan.partials.edit-tab-pendaftaran')
                        @include('admin.peninjauan.partials.edit-tab-pengukuran')
                        {{-- @include('admin.peninjauan.partials.edit-tab-kesimpulan') --}}
                    </div>
                </div>

                <!-- Form Actions -->
                <div class="card-footer">
                    <div class="row">
                        <div class="col-6">
                            <button type="button" class="btn btn-secondary" onclick="previousTab()">
                                <i class="fas fa-chevron-left"></i> Sebelumnya
                            </button>
                            <button type="button" class="btn btn-secondary" onclick="nextTab()">
                                Selanjutnya <i class="fas fa-chevron-right"></i>
                            </button>
                        </div>
                        <div class="col-6 text-right">
                            <button type="button" class="btn btn-info" onclick="saveDraft()">
                                <i class="fas fa-save"></i> Simpan Draft
                            </button>
                            <button type="submit" class="btn btn-primary" onclick="return validateAndSubmit(event)">
                                <i class="fas fa-check"></i> Update Data
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
    // Initialize coordinates from existing data
    // let coordinates = {!! $peninjauan->coordinates ?? '[]' !!};
    let coordinates = @json($peninjauan->coordinates ?? []);
    let coordinateCount = coordinates.length || 4;

    // Tab navigation
    $('#peninjauanTabs a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        const tabId = $(e.target).attr('href').substring(1);

        if (tabId === 'pengukuran') {
            setTimeout(() => {
                if (typeof initPengukuranMap === 'function') {
                    initPengukuranMap();
                }
            }, 100);
        }

        if (tabId === 'kesimpulan') {
            if (typeof updateSummary === 'function') {
                updateSummary();
            }
        }
    });

    function nextTab() {
        const activeTab = $('.nav-tabs .nav-link.active');
        const nextTab = activeTab.parent().next().find('.nav-link');
        if (nextTab.length > 0) {
            nextTab.tab('show');
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }

    function previousTab() {
        const activeTab = $('.nav-tabs .nav-link.active');
        const prevTab = activeTab.parent().prev().find('.nav-link');
        if (prevTab.length > 0) {
            prevTab.tab('show');
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }

    function saveDraft() {
        const formData = new FormData(document.getElementById('peninjauanForm'));
        formData.append('save_as_draft', '1');

        if (coordinates.length > 0) {
            formData.set('coordinates', JSON.stringify(coordinates));
        }

        const btn = $('button:contains("Simpan Draft")');
        const originalText = btn.html();
        btn.html('<i class="fas fa-spinner fa-spin"></i> Menyimpan...').prop('disabled', true);

        $.ajax({
            url: '{{ route("peninjauan.update", $peninjauan->id) }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'X-HTTP-Method-Override': 'PUT'
            },
            success: function(response) {
                toastr.success('Draft berhasil disimpan!');
                $('#peninjauanForm').data('changed', false);
            },
            error: function(xhr) {
                console.error('Save draft error:', xhr);
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    let errorMsg = 'Validation errors:\n';
                    Object.keys(errors).forEach(key => {
                        errorMsg += errors[key].join('\n') + '\n';
                    });
                    toastr.error(errorMsg);
                } else {
                    toastr.error('Gagal menyimpan draft');
                }
            },
            complete: function() {
                btn.html(originalText).prop('disabled', false);
            }
        });
    }

    function validateAndSubmit(event) {
        event.preventDefault();

        $('.form-control').removeClass('is-invalid');
        $('.invalid-feedback').hide();

        const requiredFields = [
            // { name: 'nomor_ba_kesaksian', label: 'Nomor BA Kesaksian' },
            { name: 'ba_tanggal', label: 'Tanggal BA' },
            { name: 'saksi1_nama', label: 'Nama Saksi 1' },
            { name: 'saksi2_nama', label: 'Nama Saksi 2' }
        ];

        let isValid = true;
        let firstErrorField = null;

        requiredFields.forEach(field => {
            const element = document.querySelector(`[name="${field.name}"]`);
            if (!element || !element.value.trim()) {
                isValid = false;
                $(element).addClass('is-invalid');

                let errorDiv = $(element).siblings('.invalid-feedback');
                if (errorDiv.length === 0) {
                    errorDiv = $('<div class="invalid-feedback"></div>');
                    $(element).after(errorDiv);
                }
                errorDiv.text(`${field.label} harus diisi`).show();

                if (!firstErrorField) {
                    firstErrorField = element;
                }
            }
        });

        if (!isValid) {
            toastr.error('Harap lengkapi field yang wajib diisi');
            $('#ba-kesaksian-tab').tab('show');

            if (firstErrorField) {
                setTimeout(() => {
                    firstErrorField.focus();
                }, 300);
            }

            return false;
        }

        if (coordinates.length > 0) {
            $('#coordinates_input').val(JSON.stringify(coordinates));
        }

        if (confirm('Apakah Anda yakin ingin update data peninjauan ini?')) {
            const btn = $('button[type="submit"]');
            const originalText = btn.html();
            btn.html('<i class="fas fa-spinner fa-spin"></i> Processing...').prop('disabled', true);

            document.getElementById('peninjauanForm').submit();
            return true;
        }

        return false;
    }

    $(document).ready(function() {
        $('[data-toggle="tooltip"]').tooltip();

        setInterval(function() {
            if ($('#peninjauanForm').data('changed')) {
                saveDraft();
            }
        }, 120000);

        $('#peninjauanForm').on('change', 'input, select, textarea', function() {
            $('#peninjauanForm').data('changed', true);
        });

        @if ($errors->any())
            $('#ba-kesaksian-tab').tab('show');
            const firstError = $('.is-invalid').first();
            if (firstError.length > 0) {
                setTimeout(() => {
                    $('html, body').animate({
                        scrollTop: firstError.offset().top - 100
                    }, 500);
                }, 300);
            }
        @endif
    });
</script>
@endpush
