@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('bank-data') }}
@endsection

@section('content')
    <div class="grid grid-cols-1 lg:grid-cols-4 gap-5 lg:gap-7.5 mb-10">
        <div class="col-span-1">
            <div class="card border border-agi-100 card-grid min-w-full">
                <div class="card-header bg-agi-50 py-5 flex-wrap">
                    <h3 class="card-title">
                        Filter
                    </h3>
                </div>
                <div class="card-body px-5">
                    <form id="filter-form">
                        <div class="grid gap-4 w-full p-5">

                            <div>
                                <label for="kategori" class="block text-sm font-medium text-gray-700">Kategori</label>
                                <select id="kategori" name="kategori" class="select tomselect w-full @error('kategori') border-danger bg-danger-light @enderror">
                                    <option value="">Semua Kategori</option>
                                    <option value="data_pembanding">Data Pembanding</option>
                                    <option value="penilaian">Penilaian</option>
                                    <option value="input_manual">Input Manual</option>
                                </select>
                            </div>
                            <div>
                                <label for="jenis_asset" class="block text-sm font-medium text-gray-700">Jenis Asset</label>
                                <select id="jenis_asset" name="jenis_asset" class="select tomselect w-full @error('jenis_asset') border-danger bg-danger-light @enderror">
                                    <option value="">Select Asset Type</option>
                                    @foreach($jenisJaminan as $jenis)
                                        <option value="{{ $jenis->name }}">{{ $jenis->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div>
                                <label for="province_code" class="block text-sm font-medium text-gray-700">Province</label>
                                <select id="province_code" name="province_code" class="select w-full @error('province_code') border-danger bg-danger-light @enderror">
                                    <option value="">Select Province</option>
                                    @foreach($provinces as $province)
                                        <option value="{{ $province->code }}">{{ $province->name }}</option>
                                    @endforeach
                                    <!-- Add province options here -->
                                </select>
                            </div>
                            <div>
                                <label for="city_code" class="block text-sm font-medium text-gray-700">City</label>
                                <select id="city_code" name="city_code" class="select w-full @error('city_code') border-danger bg-danger-light @enderror">
                                    <option value="">Select City</option>
                                    <!-- Add city options here -->
                                </select>
                            </div>
                            <div>
                                <label for="district_code" class="block text-sm font-medium text-gray-700">District</label>
                                <select id="district_code" name="district_code" class="select w-full @error('district_code') border-danger bg-danger-light @enderror">
                                    <option value="">Select District</option>
                                    <!-- Add district options here -->
                                </select>
                            </div>
                            <div>
                                <label for="village_code" class="block text-sm font-medium text-gray-700">Village</label>
                                <select id="village_code" name="village_code" class="select w-full @error('village_code') border-danger bg-danger-light @enderror">
                                    <option value="">Select Village</option>
                                    <!-- Add village options here -->
                                </select>
                            </div>
                            <div>
                                <label for="tahun" class="block text-sm font-medium text-gray-700">Tahun</label>
                                <select id="tahun" name="tahun" class="select tomselect w-full @error('tahun') border-danger bg-danger-light @enderror">
                                    <option value="">Semua Tahun</option>
                                    @for ($year = date('Y'); $year >= 2000; $year--)
                                        <option value="{{ $year }}">{{ $year }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div>
                                <label for="start_date" class="block text-sm font-medium text-gray-700">Start Date</label>
                                <input type="date" id="start_date" name="start_date" class="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                            </div>
                            <div>
                                <label for="end_date" class="block text-sm font-medium text-gray-700">End Date</label>
                                <input type="date" id="end_date" name="end_date" class="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                            </div>
                            <div>
                                <button type="submit" class="w-full inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                    Apply Filters
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

        </div>
        <div class="col-span-3">
            <div class="card border border-agi-100 card-grid min-w-full">
                <div class="card-header bg-agi-50 py-5 flex-wrap">
                    <h3 class="card-title">
                        Maps
                    </h3>
                </div>
                <div class="card-body px-5">
                    <div id="map" style="height: 700px; width: 100%;"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="w-full grid gap-5 lg:gap-7.5 mx-auto">
        <div class="card border border-agi-100 card-grid min-w-full" data-datatable="false" data-datatable-page-size="10" data-datatable-state-save="false" id="bank-data-table" data-api-url="{{ route('bank-data.datatables') }}">
            <div class="card-header bg-agi-50 py-5 flex-wrap">
                <h3 class="card-title">
                    Daftar Bank Data
                </h3>
                <div class="flex flex-wrap gap-2 lg:gap-5">
                    <div class="flex">
                        <label class="input input-sm"> <i class="ki-filled ki-magnifier"> </i>
                            <input placeholder="Search Bank Data" id="search" type="text" value="">
                        </label>
                    </div>
                    <div class="flex flex-wrap gap-2.5">
                        <div class="h-[24px] border border-r-gray-200"></div>
                        <a class="btn btn-sm btn-light" href="#"> Export to Excel </a>
                    </div>
                </div>
            </div>

            <div class="card-body">
                <div class="scrollable-x-auto">
                    <table class="table table-auto table-border align-middle text-gray-700 font-medium text-sm" data-datatable-table="true">
                        <thead>
                        <tr>
                            <th class="w-14">
                                <input class="checkbox checkbox-sm" data-datatable-check="true" type="checkbox"/>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="sumber">
                                <span class="sort"> <span class="sort-label"> Sumber </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="jenis_aset">
                                <span class="sort"> <span class="sort-label"> Jenis Aset </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="tanggal">
                                <span class="sort"> <span class="sort-label"> Tanggal </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="tahun">
                                <span class="sort"> <span class="sort-label"> Tahun </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="luas_tanah">
                                <span class="sort"> <span class="sort-label"> Luas Tanah </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="luas_bangunan">
                                <span class="sort"> <span class="sort-label"> Luas Bangunan </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="harga">
                                <span class="sort"> <span class="sort-label"> Harga </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="nilai_pasar">
                                <span class="sort"> <span class="sort-label"> Nilai Pasar </span>
                                    <span class="sort-icon"> </span> </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="location">
                                <span class="sort"> <span class="sort-label"> Location </span>
                                <span class="sort-icon"> </span> </span>
                            </th>
                        </tr>
                        </thead>
                    </table>
                </div>
                <div class="card-footer justify-center md:justify-between flex-col md:flex-row gap-3 text-gray-600 text-2sm font-medium">
                    <div class="flex items-center gap-2">
                        Show
                        <select class="select select-sm w-16" data-datatable-size="true" name="perpage"> </select> per
                        page
                    </div>
                    <div class="flex items-center gap-4">
                        <span data-datatable-info="true"> </span>
                        <div class="pagination" data-datatable-pagination="true">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="imageModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white p-4 rounded-lg max-w-3xl max-h-[100vh] overflow-auto">
            <img id="modalImage" src="" alt="Zoomed Image" class="max-w-full h-auto">
            <button id="closeModal" class="mt-4 px-4 py-2 bg-red-300 text-gray-800 rounded hover:bg-red-400" onclick="closeImageModal()">Close</button>
        </div>
    </div>
@endsection

@push('scripts')
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDQTNRxyr0w7kXHsO2hmarDTa9-1LyLmS8&callback=initMap" async defer></script>
    <script>
        let map;
        let markers = [];
        let infoWindows = [];
        let dataTable;

        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: -6.200000, lng: 106.816666}, // Jakarta coordinates
                zoom: 10
            });
        }

        function openImageModal(src) {
            const modal = document.getElementById('imageModal');
            const modalImage = document.getElementById('modalImage');
            modalImage.src = src;
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }

        function closeImageModal() {
            const modal = document.getElementById('imageModal');
            modal.classList.remove('flex');
            modal.classList.add('hidden');
        }

        function changeMainPhoto(thumbnail, index) {
            const mainPhoto = thumbnail.closest('.photo-gallery').querySelector('.main-photo img');
            mainPhoto.src = thumbnail.src;
            mainPhoto.alt = thumbnail.alt;
        }

        function updateMapMarkers(data) {
            // Clear existing markers
            markers.forEach(marker => marker.setMap(null));
            infoWindows.forEach(infoWindow => infoWindow.close());
            markers = [];
            infoWindows = [];

            // Add new markers
            data.forEach(item => {
                if (item.location) {
                    let lat, lng;

                    // Check if item.location is a string containing comma-separated coordinates
                    if (typeof item.location === 'string' && item.location.includes(',')) {
                        [lat, lng] = item.location.split(',').map(coord => parseFloat(coord.trim()));
                    }
                    // Check if item.location is an object with lat and lng properties
                    else if (typeof item.location === 'object' && item.location.lat && item.location.lng) {
                        lat = parseFloat(item.location.lat);
                        lng = parseFloat(item.location.lng);
                    }
                    // Check if item.location is an array with two elements
                    else if (Array.isArray(item.location) && item.location.length === 2) {
                        [lat, lng] = item.location.map(coord => parseFloat(coord));
                    }

                    const markerColors = {
                        data_pembanding: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
                        penilaian: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
                        input: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
                    };

                    if (lat && lng) {
                        const marker = new google.maps.Marker({
                            position: {lat: lat, lng: lng},
                            map: map,
                            title: item.jenis_aset,
                            icon: markerColors[item.kategori] || 'http://maps.google.com/mapfiles/ms/icons/red-dot.png' // Default to red if category is not recognized
                        });

                        // Create info window content
                        const contentString = `
                            <div id='content' style='width: 550px; max-width: 100%;'>
                                <div id='siteNotice'></div>
                                <h2 class='card-title mb-5'>
                                    ${item.jenis_aset}
                                </h2>
                                <div class="grid gap-3">
                                    <div class='flex items-center justify-between flex-wrap gap-1.5'>
                                        <div class='flex items-center gap-1.5'>
                                            <span class='text-sm font-normal text-gray-900'>
                                                Tanggal Penilaian
                                            </span>
                                        </div>
                                        <div class='flex items-center text-sm font-medium text-gray-800 gap-6'>
                                            <span class='lg:text-right'>
                                                ${window.formatTanggalIndonesia(item.tanggal)}
                                            </span>
                                        </div>
                                    </div>
                                    <div class="border-t border-gray-300 border-dashed"></div>
                                    <div class='flex items-center justify-between flex-wrap gap-1.5'>
                                        <div class='flex items-center gap-1.5'>
                                            <span class='text-sm font-normal text-gray-900'>
                                                Tahun
                                            </span>
                                        </div>
                                        <div class='flex items-center text-sm font-medium text-gray-800 gap-6'>
                                            <span class='lg:text-right'>
                                                ${item.tahun}
                                            </span>
                                        </div>
                                    </div>
                                    <div class="border-t border-gray-300 border-dashed"></div>
                                    <div class='flex items-center justify-between flex-wrap gap-1.5'>
                                        <div class='flex items-center gap-1.5'>
                                            <span class='text-sm font-normal text-gray-900'>
                                                Luas Tanah
                                            </span>
                                        </div>
                                        <div class='flex items-center text-sm font-medium text-gray-800 gap-6'>
                                            <span class='lg:text-right'>
                                                ${item.luas_tanah} m²
                                            </span>
                                        </div>
                                    </div>
                                    <div class="border-t border-gray-300 border-dashed"></div>
                                    <div class='flex items-center justify-between flex-wrap gap-1.5'>
                                        <div class='flex items-center gap-1.5'>
                                            <span class='text-sm font-normal text-gray-900'>
                                                Luas Bangunan
                                            </span>
                                        </div>
                                        <div class='flex items-center text-sm font-medium text-gray-800 gap-6'>
                                            <span class='lg:text-right'>
                                                ${item.luas_bangunan} m²
                                            </span>
                                        </div>
                                    </div>
                                    <div class="border-t border-gray-300 border-dashed"></div>
                                    <div class='flex items-center justify-between flex-wrap gap-1.5'>
                                        <div class='flex items-center gap-1.5'>
                                            <span class='text-sm font-normal text-gray-900'>
                                                Harga
                                            </span>
                                        </div>
                                        <div class='flex items-center text-sm font-medium text-gray-800 gap-6'>
                                            <span class='lg:text-right'>
                                                ${window.formatRupiah(item.harga)}
                                            </span>
                                        </div>
                                    </div>
                                    <div class="border-t border-gray-300 border-dashed"></div>
                                    <div class='flex items-center justify-between flex-wrap gap-1.5'>
                                        <div class='flex items-center gap-1.5'>
                                            <span class='text-sm font-normal text-gray-900'>
                                                Nilai Pasar
                                            </span>
                                        </div>
                                        <div class='flex items-center text-sm font-medium text-gray-800 gap-6'>
                                            <span class='lg:text-right'>
                                                ${window.formatRupiah(item.nilai_pasar)}
                                            </span>
                                        </div>
                                    </div>
                                    <div class="border-t border-gray-300 border-dashed"></div>
                                    <div class='flex items-start justify-between flex-wrap gap-1.5'>
                                        <div class='flex items-start gap-1.5'>
                                            <span class='text-sm font-normal text-gray-900'>
                                                Location
                                            </span>
                                        </div>
                                        <div class='flex items-center text-sm font-medium text-gray-800 gap-6'>
                                            <span class='text-right whitespace-normal break-words'>
                                                ${item.address.split(' ').reduce((acc, word, index, array) => {
                                                    if (index > 0 && index % 7 === 0) {
                                                        acc += '<br>';
                                                    }
                                                    acc += word + (index < array.length - 1 ? ' ' : '');
                                                    return acc;
                                                }, '')}
                                            </span>
                                        </div>
                                    </div>
                                    ${item.photos && item.photos.length > 0 ? `
                                        <div class="photo-gallery mb-5">
                                            <div class="main-photo mb-2">
                                                <img src="storage/${item.photos[0]}" alt="${item.jenis_aset}"
                                                     style="width: 100%; height: auto; object-fit: cover; cursor: pointer;"
                                                     onclick="openImageModal(this.src)">
                                            </div>
                                            <div class="thumbnail-container flex gap-2 overflow-x-auto">
                                                ${item.photos.map((photo, index) => `
                                                    <img src="storage/${photo}" alt="${item.jenis_aset} ${index + 1}"
                                                         class="thumbnail cursor-pointer"
                                                         style="width: 60px; height: 60px; object-fit: cover;"
                                                         onclick="changeMainPhoto(this, ${index})">
                                                `).join('')}
                                            </div>
                                        </div>
                                    ` : ''}
                                    <div class="border-t border-gray-300 border-dashed"></div>
                                    <div class='flex justify-end mt-3'>
                                        <button onclick="getDirections(${lat}, ${lng})" class='btn btn-sm btn-primary'>
                                            Get Directions
                                        </button>
                                    </div>
                                </div>
                            </div>
                        `;

                        // Create info window
                        const infoWindow = new google.maps.InfoWindow({
                            content: contentString
                        });

                        // Add click event to marker
                        marker.addListener('click', () => {
                            // Close all open info windows
                            infoWindows.forEach(window => window.close());
                            // Open this marker's info window
                            infoWindow.open(map, marker);
                        });

                        markers.push(marker);
                        infoWindows.push(infoWindow);

                    } else {
                        console.error('Invalid location format for item:', item);
                    }
                }
            });

            // Adjust map bounds to fit all markers
            if (markers.length > 0) {
                const bounds = new google.maps.LatLngBounds();
                markers.forEach(marker => bounds.extend(marker.getPosition()));
                map.fitBounds(bounds);
            }
        }


        function getDirections(lat, lng) {
            console.log('Getting directions to:', lat, lng);
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        const origin = position.coords.latitude + ',' + position.coords.longitude;
                        const destination = lat + ',' + lng;
                        const url = `https://www.google.com/maps/dir/?api=1&origin=${origin}&destination=${destination}`;
                        window.open(url, '_blank');
                    },
                    () => {
                        alert('Unable to get your current location. Please enable location services.');
                    }
                );
            } else {
                alert('Geolocation is not supported by your browser.');
            }
        }

        function initializeDataTable() {
            const element = document.querySelector('#bank-data-table');
            const searchInput = document.getElementById('search');

            const apiUrl = element.getAttribute('data-api-url');
            const dataTableOptions = {
                apiEndpoint: apiUrl,
                pageSize: 5,
                columns: {
                    select: {
                        render: (item, data, context) => {
                            const checkbox = document.createElement('input');
                            checkbox.className = 'checkbox checkbox-sm';
                            checkbox.type = 'checkbox';
                            checkbox.value = data.id.toString();
                            checkbox.setAttribute('data-datatable-row-check', 'true');
                            return checkbox.outerHTML.trim();
                        },
                    },
                    sumber: {
                        title: 'Sumber'
                    },
                    jenis_aset: {
                        title: 'Jenis Aset'
                    },
                    tanggal: {
                        title: 'Tanggal',
                        render: (item, data) => {
                            return data.tanggal;
                        },
                    },
                    tahun: {
                        title: 'Tahun',
                        render: (item, data) => {
                            return data.tahun;
                        },
                    },
                    luas_tanah: {
                        title: 'Luas Tanah',
                        render: (item, data) => {
                            return `${data.luas_tanah} m²`;
                        },
                    },
                    luas_bangunan: {
                        title: 'Luas Bangunan',
                        render: (item, data) => {
                            return `${data.luas_bangunan} m²`;
                        },
                    },
                    harga: {
                        title: 'Harga',
                        render: (item, data) => {
                            return window.formatRupiah(data.harga);
                        },
                    },
                    nilai_pasar: {
                        title: 'Nilai Pasar',
                        render: (item, data) => {
                            return window.formatRupiah(data.nilai_pasar);
                        },
                    },
                    location: {
                        title: 'Location'
                    }
                },
            };

            dataTable = new KTDataTable(element, dataTableOptions);
            dataTable.on('draw', () => {
                const data = dataTable._data;
                updateMapMarkers(data);
                updatePagination(data);
            })
            // Custom search functionality
            searchInput.addEventListener('input', function () {
                const searchValue = this.value.trim();
                dataTable.search(searchValue, true);
            });
        }

        const filterForm = document.getElementById('filter-form');
        filterForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const formData = new FormData(this);
            const filters = Object.fromEntries(formData.entries());

            // Apply the new search/filter
            if (filters) {
                dataTable.search(filters, true);
            }

            // Reload the table to apply the new filters
            dataTable.reload();
        });

        function updatePagination(response) {
            const paginationInfo = document.querySelector('[data-datatable-info="true"]');

            if (paginationInfo) {
                if (response.recordsFiltered > 0) {
                    const start = (response.page - 1) * response.pageSize + 1;
                    const end = Math.min(start + response.pageSize - 1, response.recordsFiltered);
                    paginationInfo.textContent = `Showing ${start} to ${end} of ${response.recordsFiltered} entries`;
                } else {
                    paginationInfo.textContent = 'No entries to show';
                }
            }
        }

        function initializeEverything() {
            initMap();
            initializeDataTable();

            dataTable.on('draw', () => {
                console.log("Table redrawn");
            });
        }

        // Check if Google Maps API is loaded
        function checkGoogleMapsLoaded() {
            if (window.google && window.google.maps) {
                initializeEverything();
            } else {
                setTimeout(checkGoogleMapsLoaded, 100);
            }
        }

        // Start checking if Google Maps is loaded
        checkGoogleMapsLoaded();
    </script>
@endpush
