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

@section('title', 'Tambah Peninjauan Baru')

@section('styles')
<style>

</style>
<style>
.nav-tabs .nav-link {
    color: #495057 !important;  /* default text abu-abu gelap */
}

.nav-tabs .nav-link.active {
    color: #000 !important;     /* hitam biar kontras */
    background-color: #fff !important;  /* putih, sama dengan card */
    border: 1px solid #dee2e6;
    border-bottom-color: transparent;   /* hilangkan border bawah agar nyambung */
    font-weight: 600;
}


.was-validated .form-control:invalid {
    border-color: #dc3545;
}

.was-validated .form-control:valid {
    border-color: #28a745;
}

.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.loading-spinner {
    background: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
}
</style>
@endsection

@section('content')
<div class="form-container">
    <div class="container">
        @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

        @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

        @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-times-circle mr-2"></i>
            {{ session('error') }}
            <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.store') }}" method="POST" enctype="multipart/form-data" novalidate>
            @csrf
            <input type="hidden" name="type_permohonan" id="type_permohonan" value="SKPT">
            <input type="hidden" name="coordinates_data" id="coordinates_input" value="">

            <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">
                                BA Kesaksian - Hal 1
                            </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">
                                BA Kesaksian - Hal 2
                            </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">
                                BA Kesepakatan batas dan Pernyataan tidak sengketa
                            </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">
                                BA Penelitian Penguasaan tanah
                            </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.tab-ba-kesaksian')
                        @include('admin.peninjauan.partials.tab-data-pemohon')
                        @include('admin.peninjauan.partials.tab-batas-tanah')
                        @include('admin.peninjauan.partials.tab-pendaftaran')
                        @include('admin.peninjauan.partials.tab-pengukuran')
                        @include('admin.peninjauan.partials.tab-kesimpulan')
                    </div>
                </div>

                <!-- Form Actions -->
                <div class="card-footer bg-light">
                    <div class="row">
                        <div class="col-6">
                            <button type="button" class="btn btn-secondary" id="prevTabBtn" onclick="previousTab()">
                                <i class="fas fa-chevron-left"></i> Sebelumnya
                            </button>
                            <button type="button" class="btn btn-secondary" id="nextTabBtn" 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" id="draftBtn" onclick="saveDraft()">
                                <i class="fas fa-save"></i> Simpan Draft
                            </button>
                            <button type="submit" class="btn btn-primary" id="submitBtn">
                                <i class="fas fa-check"></i> Submit Final
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Loading Overlay -->
<div id="loadingOverlay" class="loading-overlay" style="display: none;">
    <div class="loading-spinner">
        <div class="spinner-border text-primary" role="status">
            <span class="sr-only">Loading...</span>
        </div>
        <p class="mt-2 mb-0">Sedang memproses...</p>
    </div>
</div>
@endsection

@push('scripts')
<script>
    // Global variables
    let formChanged = false;
    let currentTabIndex = 0;
    const totalTabs = 6;

    // Initialize when document ready
    $(document).ready(function() {
        initializeForm();
        setupEventListeners();
        updateNavigationButtons();

        // Handle validation errors on load
        @if ($errors->any())
            showTabWithErrors();
        @endif
    });

    function initializeForm() {
        // Initialize tooltips
        $('[data-toggle="tooltip"]').tooltip();

        // Initialize form validation classes
        $('#peninjauanForm').removeClass('was-validated');

        // Set initial tab state
        updateNavigationButtons();

        console.log('Form initialized successfully');
    }

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

            // Update navigation buttons
            updateNavigationButtons();

            // Handle specific tabs
            handleTabSpecificActions(tabId);

            // Scroll to top
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });

        // Form change detection
        $('#peninjauanForm').on('change input', 'input, select, textarea', function() {
            formChanged = true;
            $(this).removeClass('is-invalid is-valid');
        });

        // Form submission
        $('#peninjauanForm').on('submit', function(e) {
            e.preventDefault();
            validateAndSubmit();
        });

        // Prevent accidental page leave
        window.addEventListener('beforeunload', function(e) {
            if (formChanged) {
                e.preventDefault();
                e.returnValue = 'Ada perubahan yang belum disimpan. Yakin ingin keluar?';
            }
        });

        // Auto-save every 3 minutes
        setInterval(function() {
            if (formChanged) {
                saveDraft(true); // Silent save
            }
        }, 180000);
    }

    function handleTabSpecificActions(tabId) {
        switch(tabId) {
            case 'pengukuran':
                setTimeout(() => {
                    if (typeof initPengukuranMap === 'function') {
                        initPengukuranMap();
                    }
                }, 150);
                break;

            case 'kesimpulan':
                if (typeof updateSummary === 'function') {
                    updateSummary();
                }
                break;
        }
    }

    function updateNavigationButtons() {
        const prevBtn = $('#prevTabBtn');
        const nextBtn = $('#nextTabBtn');

        // Update previous button
        if (currentTabIndex === 0) {
            prevBtn.prop('disabled', true);
        } else {
            prevBtn.prop('disabled', false);
        }

        // Update next button
        if (currentTabIndex === totalTabs - 1) {
            nextBtn.text('Submit Final').removeClass('btn-secondary').addClass('btn-success');
        } else {
            nextBtn.html('Selanjutnya <i class="fas fa-chevron-right"></i>').removeClass('btn-success').addClass('btn-secondary');
        }
    }

    function nextTab() {
        if (currentTabIndex < totalTabs - 1) {
            const nextTabIndex = currentTabIndex + 1;
            const nextTab = $('#peninjauanTabs .nav-item:eq(' + nextTabIndex + ') .nav-link');
            nextTab.tab('show');
        } else {
            // Last tab, submit form
            validateAndSubmit();
        }
    }

    function previousTab() {
        if (currentTabIndex > 0) {
            const prevTabIndex = currentTabIndex - 1;
            const prevTab = $('#peninjauanTabs .nav-item:eq(' + prevTabIndex + ') .nav-link');
            prevTab.tab('show');
        }
    }

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

        // Add coordinates if available
        if (typeof coordinates !== 'undefined' && coordinates.length > 0) {
            formData.set('coordinates_data', JSON.stringify(coordinates));
        }

        // Show loading for non-silent saves
        if (!silent) {
            showLoading('Menyimpan draft...');
        }

        const draftBtn = $('#draftBtn');
        const originalText = draftBtn.html();

        if (!silent) {
            draftBtn.html('<i class="fas fa-spinner fa-spin"></i> Menyimpan...').prop('disabled', true);
        }

        $.ajax({
            url: '{{ route("peninjauan.store") }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            success: function(response) {
                if (!silent) {
                    showSuccess('Draft berhasil disimpan!');
                }
                formChanged = false;

                // Update form with any returned data
                if (response.data && response.data.id) {
                    // Update form action for future updates
                    // $('#peninjauanForm').attr('action', '/peninjauan/' + response.data.id);
                }
            },
            error: function(xhr) {
                console.error('Save draft error:', xhr);

                if (!silent) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        showValidationErrors(errors);
                    } else if (xhr.status === 419) {
                        showError('Session expired. Silakan refresh halaman.');
                    } else {
                        showError('Gagal menyimpan draft: ' + (xhr.responseJSON?.message || 'Unknown error'));
                    }
                }
            },
            complete: function() {
                hideLoading();
                if (!silent) {
                    draftBtn.html(originalText).prop('disabled', false);
                }
            }
        });
    }

    function validateAndSubmit() {
        // Clear previous validation
        $('.form-control').removeClass('is-invalid is-valid');
        $('.invalid-feedback').remove();

        // Basic client-side validation
        const validationResult = performClientValidation();

        if (!validationResult.isValid) {
            showValidationErrors(validationResult.errors);
            return;
        }

        // Add coordinates to form
        updateCoordinatesInput();

        // Show confirmation
        if (!confirm('Apakah Anda yakin ingin submit data peninjauan ini?')) {
            return;
        }

        // Show loading
        showLoading('Memproses data...');

        const submitBtn = $('#submitBtn');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Processing...').prop('disabled', true);

        // Submit form via AJAX for better error handling
        const formData = new FormData(document.getElementById('peninjauanForm'));

        $.ajax({
            url: $('#peninjauanForm').attr('action'),
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            success: function(response) {
                hideLoading();
                formChanged = false;

                if (response.redirect) {
                    showSuccess('Data berhasil disimpan! Mengalihkan...');
                    setTimeout(() => {
                        window.location.href = response.redirect;
                    }, 1500);
                } else {
                    showSuccess('Data berhasil disimpan!');
                }
            },
            error: function(xhr) {
                console.error('Submit error:', xhr);

                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    showValidationErrors(errors);
                } else if (xhr.status === 419) {
                    showError('Session expired. Silakan refresh halaman.');
                } else {
                    showError('Gagal menyimpan data: ' + (xhr.responseJSON?.message || 'Unknown error'));
                }
            },
            complete: function() {
                hideLoading();
                submitBtn.html(originalText).prop('disabled', false);
            }
        });
    }

    function performClientValidation() {
        const errors = {};
        let isValid = true;

        // Required fields validation
        const requiredFields = [
            { name: 'ba_tanggal', label: 'Tanggal BA', tabIndex: 0 },
            { name: 'saksi1_nama', label: 'Nama Saksi 1', tabIndex: 0 },
            { name: 'saksi2_nama', label: 'Nama Saksi 2', tabIndex: 0 }
        ];

        requiredFields.forEach(field => {
            const element = $(`[name="${field.name}"]`);
            if (element.length && !element.val().trim()) {
                errors[field.name] = [field.label + ' harus diisi'];
                isValid = false;
            }
        });

        // Coordinate validation (if map tab is used)
        if (typeof coordinates !== 'undefined' && coordinates.length < 3) {
            errors.coordinates = ['Minimal 3 koordinat harus diisi'];
            isValid = false;
        }

        return { isValid, errors };
    }

    function updateCoordinatesInput() {
        if (typeof coordinates !== 'undefined' && coordinates.length > 0) {
            $('#coordinates_input').val(JSON.stringify(coordinates));
        }
    }

    function showValidationErrors(errors) {
        let firstErrorTab = null;
        let firstErrorField = null;

        Object.keys(errors).forEach(fieldName => {
            const element = $(`[name="${fieldName}"]`);
            if (element.length) {
                element.addClass('is-invalid');

                // Add error message
                const errorDiv = $('<div class="invalid-feedback d-block"></div>');
                errorDiv.text(errors[fieldName][0]);
                element.parent().append(errorDiv);

                if (!firstErrorField) {
                    firstErrorField = element;
                    // Determine which tab contains this field
                    firstErrorTab = element.closest('.tab-pane').attr('id');
                }
            }
        });

        if (firstErrorTab) {
            // Switch to tab containing first error
            $(`a[href="#${firstErrorTab}"]`).tab('show');

            setTimeout(() => {
                if (firstErrorField) {
                    $('html, body').animate({
                        scrollTop: firstErrorField.offset().top - 100
                    }, 500);
                    firstErrorField.focus();
                }
            }, 300);
        }

        showError('Harap perbaiki kesalahan pada form');
    }

    function showTabWithErrors() {
        // Switch to first tab with errors
        setTimeout(() => {
            const firstError = $('.is-invalid, .text-danger').first();
            if (firstError.length > 0) {
                const tabPane = firstError.closest('.tab-pane');
                if (tabPane.length > 0) {
                    const tabId = tabPane.attr('id');
                    $(`a[href="#${tabId}"]`).tab('show');

                    // Scroll to error after tab switch
                    setTimeout(() => {
                        $('html, body').animate({
                            scrollTop: firstError.offset().top - 100
                        }, 500);
                    }, 300);
                }
            } else {
                // Default to first tab if no specific error found
                $('#ba-kesaksian-tab').tab('show');
            }
        }, 100);
    }

    // Utility functions for notifications
    function showLoading(message = 'Loading...') {
        $('#loadingOverlay').show();
        $('#loadingOverlay .loading-spinner p').text(message);
    }

    function hideLoading() {
        $('#loadingOverlay').hide();
    }

    function showSuccess(message) {
        if (typeof toastr !== 'undefined') {
            toastr.success(message);
        } else {
            alert('Success: ' + message);
        }
    }

    function showError(message) {
        if (typeof toastr !== 'undefined') {
            toastr.error(message);
        } else {
            alert('Error: ' + message);
        }
    }

    function showInfo(message) {
        if (typeof toastr !== 'undefined') {
            toastr.info(message);
        } else {
            alert('Info: ' + message);
        }
    }

    function showWarning(message) {
        if (typeof toastr !== 'undefined') {
            toastr.warning(message);
        } else {
            alert('Warning: ' + message);
        }
    }

    // Expose functions globally for external access
    window.nextTab = nextTab;
    window.previousTab = previousTab;
    window.saveDraft = saveDraft;
    window.validateAndSubmit = validateAndSubmit;
    window.showSuccess = showSuccess;
    window.showError = showError;
    window.showInfo = showInfo;
    window.showWarning = showWarning;

    // Type selector function (if needed)
    function selectType(type) {
        $('.type-selector .btn-group .btn').removeClass('active');
        $(event.target).addClass('active');
        $('#type_permohonan').val(type);
        formChanged = true;
    }

    // Additional helper functions
    function resetFormValidation() {
        $('#peninjauanForm').removeClass('was-validated');
        $('.form-control').removeClass('is-invalid is-valid');
        $('.invalid-feedback').remove();
    }

    function validateCurrentTab() {
        const activeTab = $('.tab-pane.active');
        let isValid = true;

        activeTab.find('input[required], select[required], textarea[required]').each(function() {
            if (!$(this).val().trim()) {
                $(this).addClass('is-invalid');
                isValid = false;
            } else {
                $(this).removeClass('is-invalid').addClass('is-valid');
            }
        });

        return isValid;
    }

    function formatCurrency(value) {
        if (!value) return '';
        return new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            minimumFractionDigits: 0
        }).format(value);
    }

    function formatNumber(value) {
        if (!value) return '';
        return new Intl.NumberFormat('id-ID').format(value);
    }

    // Auto-resize textareas
    function autoResizeTextarea() {
        $('textarea').each(function() {
            $(this).on('input', function() {
                this.style.height = 'auto';
                this.style.height = (this.scrollHeight) + 'px';
            });
        });
    }

    // Call auto-resize on document ready
    $(document).ready(function() {
        autoResizeTextarea();
    });

    // Handle form reset
    function resetForm() {
        if (confirm('Yakin ingin reset form? Semua data akan hilang.')) {
            document.getElementById('peninjauanForm').reset();
            resetFormValidation();
            formChanged = false;

            // Reset to first tab
            $('#ba-kesaksian-tab').tab('show');
            currentTabIndex = 0;
            updateNavigationButtons();

            showInfo('Form berhasil direset');
        }
    }

    // Export additional functions
    window.selectType = selectType;
    window.resetForm = resetForm;
    window.validateCurrentTab = validateCurrentTab;
    window.formatCurrency = formatCurrency;
    window.formatNumber = formatNumber;

    // Console log for debugging
    console.log('Create form scripts loaded successfully');
</script>

<!-- Include additional scripts if needed -->
@if(config('app.env') === 'local')
<script>
    // Development mode debugging
    console.log('Development mode active');

    // Add debug info
    window.debugInfo = {
        formChanged: () => formChanged,
        currentTabIndex: () => currentTabIndex,
        coordinates: () => typeof coordinates !== 'undefined' ? coordinates : 'Not available'
    };
</script>
@endif
@endpush
