@extends('layout.main')

@section('content')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />

<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">
        <div class="card-header border-bottom mb-4">
            <h5 class="card-title mb-0">Tambah Map Tanaman</h5>
        </div>
        
        <div class="card-body">
            <form id="addTanamanForm" action="{{ route('tanaman.store') }}" method="POST">
                @csrf
                
                <div class="row">
                    <div class="col-lg-5 mb-4">
                        <h6 class="mb-3 text-primary"><i class="ti tabler-seeding me-1"></i> Data Tanaman</h6>
                        
                        <div class="mb-3 form-control-validation">
                            <label class="form-label">Nama Tanaman (Cth: Pohon Mangga 01)<span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="nama" />
                        </div>

                        <div class="mb-3 form-control-validation">
                            <label class="form-label">Pemilik/Pengelola<span class="text-danger">*</span></label>
                            <select name="profile_id" class="select2 form-select" data-placeholder="Pilih Pemilik">
                                <option value="">Pilih Pemilik</option>
                                @foreach($profiles as $p)
                                    <option value="{{ $p->id }}">{{ $p->nama }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3 form-control-validation">
                                <label class="form-label">Komoditas<span class="text-danger">*</span></label>
                                <select name="komoditas_id" class="select2 form-select" data-placeholder="Pilih Komoditas">
                                    <option value="">Pilih Komoditas</option>
                                    @foreach($komoditas as $k)
                                        <option value="{{ $k->id }}">{{ $k->nama }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6 mb-3 form-control-validation">
                                <label class="form-label">Kondisi<span class="text-danger">*</span></label>
                                <select name="kondisi_tanaman" class="select2 form-select" data-placeholder="Kondisi">
                                    <option value="">Pilih Kondisi</option>
                                    <option value="sehat">Sehat</option>
                                    <option value="sakit">Sakit</option>
                                    <option value="mati">Mati</option>
                                </select>
                            </div>
                        </div>

                        <hr class="my-4">
                        <h6 class="mb-3 text-primary"><i class="ti tabler-map-pin me-1"></i> Tentukan Titik Koordinat</h6>

                        <div class="mb-3 form-control-validation">
                            <label class="form-label text-success fw-bold">1. Pilih Lahan (Lokasi Tanam)<span class="text-danger">*</span></label>
                            <select id="lahan-select" name="lahan_id" class="select2 form-select" data-placeholder="Pilih Lahan">
                                <option value="">Pilih Lahan</option>
                                @foreach($lahan as $l)
                                    <option value="{{ $l->id }}">{{ $l->nama }}</option>
                                @endforeach
                            </select>
                            <small class="text-muted d-block mt-1">Pilih lahan untuk memunculkan poligon di peta.</small>
                        </div>

                        <div class="row">
                            <div class="col-12 mb-2">
                                <label class="form-label text-success fw-bold">2. Klik Area pada Peta di samping untuk mengisi koordinat otomatis <i class="ti tabler-arrow-right d-none d-lg-inline"></i></label>
                            </div>
                            <div class="col-6 mb-3 form-control-validation">
                                <label class="form-label">Latitude<span class="text-danger">*</span></label>
                                <input type="text" class="form-control bg-lighter" id="lat-input" name="latitude" readonly placeholder="Otomatis" />
                            </div>
                            <div class="col-6 mb-3 form-control-validation">
                                <label class="form-label">Longitude<span class="text-danger">*</span></label>
                                <input type="text" class="form-control bg-lighter" id="lng-input" name="longitude" readonly placeholder="Otomatis" />
                            </div>
                        </div>

                        <div class="mt-4 text-end">
                            <a href="{{ route('tanaman.index') }}" class="btn btn-label-secondary me-2">Batal</a>
                            <button type="submit" class="btn btn-primary data-submit">Simpan Tanaman</button>
                        </div>
                    </div>

                    <div class="col-lg-7">
                        <div class="border rounded h-100 min-vh-50" style="min-height: 500px; position: relative;">
                            <div id="map" style="height: 100%; width: 100%; z-index: 1; border-radius: 0.375rem;"></div>
                            <div id="map-overlay" class="position-absolute top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center bg-dark bg-opacity-50 rounded" style="z-index: 2;">
                                <h5 class="text-white text-center px-4"><i class="ti tabler-map-search mb-2" style="font-size: 3rem;"></i><br>Silakan pilih Lahan terlebih dahulu</h5>
                            </div>
                        </div>
                    </div>

                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
@endsection

@push('scripts')
<script>
    'use strict';
    $(document).ready(function () {
        $('.select2').select2();

        let map = L.map('map').setView([-2.5489, 118.0149], 5);
        L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
            attribution: '&copy; Google Maps Satellite'
        }).addTo(map);

        let currentPolygon = null;
        let currentMarker = null;

        $('#lahan-select').on('change', function() {
            let lahanId = $(this).val();
            
            if (currentPolygon) map.removeLayer(currentPolygon);
            if (currentMarker) map.removeLayer(currentMarker);
            $('#lat-input').val('');
            $('#lng-input').val('');
            fvAdd.revalidateField('latitude');

            if (lahanId) {
                $('#map-overlay').addClass('d-none');

                $.get(`/tanaman/get-lahan/${lahanId}`, function(res) {
                    if (res.status === 'success' && res.path) {
                        try {
                            let rawData = JSON.parse(res.path);
                            let latLngs = rawData.map(coord => [coord[1], coord[0]]);
                            
                            currentPolygon = L.polygon(latLngs, {
                                color: '#28c76f',
                                fillColor: '#28c76f',
                                fillOpacity: 0.4,
                                weight: 2
                            }).addTo(map);

                            map.fitBounds(currentPolygon.getBounds(), { padding: [30, 30] });

                        } catch (e) {
                            console.error("Format JSON Lahan tidak valid.");
                            Swal.fire('Oops!', 'Format koordinat lahan ini rusak/tidak valid.', 'warning');
                        }
                    } else {
                        Swal.fire('Oops!', 'Lahan ini belum memiliki data pemetaan (Polygon kosong).', 'warning');
                    }
                });
            } else {
                $('#map-overlay').removeClass('d-none');
                map.setView([-2.5489, 118.0149], 5);
            }
        });

        map.on('click', function(e) {
            let lahanId = $('#lahan-select').val();
            if (!lahanId) {
                Swal.fire('Perhatian', 'Silakan pilih Lahan terlebih dahulu sebelum menentukan titik tanam.', 'warning');
                return;
            }

            let lat = e.latlng.lat.toFixed(8);
            let lng = e.latlng.lng.toFixed(8);

            $('#lat-input').val(lat);
            $('#lng-input').val(lng);

            fvAdd.revalidateField('latitude');
            fvAdd.revalidateField('longitude');

            if (currentMarker) {
                map.removeLayer(currentMarker);
            }
            currentMarker = L.marker([lat, lng]).addTo(map)
                .bindPopup("<b>Titik Tanam Dipilih!</b><br>Lat: " + lat + "<br>Lng: " + lng).openPopup();
        });

        const addForm = document.getElementById('addTanamanForm');
        let fvAdd = FormValidation.formValidation(addForm, {
            fields: {
                nama: { validators: { notEmpty: { message: 'Nama tanaman wajib diisi' } } },
                profile_id: { validators: { notEmpty: { message: 'Pemilik wajib dipilih' } } },
                lahan_id: { validators: { notEmpty: { message: 'Lahan wajib dipilih' } } },
                komoditas_id: { validators: { notEmpty: { message: 'Komoditas wajib dipilih' } } },
                kondisi_tanaman: { validators: { notEmpty: { message: 'Kondisi wajib dipilih' } } },
                latitude: { validators: { notEmpty: { message: 'Klik pada peta untuk menentukan titik koordinat' } } },
                longitude: { validators: { notEmpty: { message: 'Longitude tidak boleh kosong' } } },
            },
            plugins: {
                trigger: new FormValidation.plugins.Trigger(),
                bootstrap5: new FormValidation.plugins.Bootstrap5({ eleValidClass: '', rowSelector: '.form-control-validation' }),
                submitButton: new FormValidation.plugins.SubmitButton(),
            }
        }).on('core.form.valid', function () {
            let formData = $(addForm).serialize();

            $.ajax({
                url: addForm.action,
                type: 'POST',
                data: formData,
                success: function (res) {
                    Swal.fire({ icon: 'success', title: 'Berhasil!', text: res.message, timer: 1500, showConfirmButton: false })
                        .then(() => window.location.href = "{{ route('tanaman.index') }}");
                },
                error: function (xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors || {}; 
                        Object.keys(errors).forEach(key => {
                            fvAdd.updateFieldStatus(key, 'Invalid', 'notEmpty');
                            const fieldRow = addForm.querySelector(`[name="${key}"]`).closest('.form-control-validation');
                            const messageContainer = fieldRow.querySelector('.fv-plugins-message-container');
                            if (messageContainer) messageContainer.innerHTML = `<div class="fv-help-block text-danger">${errors[key][0]}</div>`;
                        });
                    } else {
                        Swal.fire({ icon: 'error', title: 'Gagal!', text: xhr.responseJSON?.message || 'Error' });
                    }
                }
            });
        });

        $('.select2').on('change', function() {
            const name = $(this).attr('name');
            if (name && addForm.querySelector(`[name="${name}"]`)) fvAdd.revalidateField(name);
        });
    });
</script>
@endpush