<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah Alamat - Glowify Beauty</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #ffe4f0 0%, #ffd0e4 100%);
        }
        .focus-ring:focus {
            outline: none;
            ring: 2px solid #f472b6;
        }
    </style>
</head>
<body class="min-h-screen py-8">

<div class="max-w-2xl mx-auto px-4">
    <div class="bg-white rounded-2xl shadow-xl overflow-hidden border border-pink-100">

        {{-- Header Pink Glow --}}
        <div class="bg-gradient-to-r from-pink-400 via-pink-500 to-rose-400 p-6 text-white">
            <div class="flex items-center gap-3">
                <i class="fa-regular fa-face-smile text-2xl"></i>
                <div>
                    <h2 class="text-2xl font-bold">✨ Tambah Alamat Baru</h2>
                    <p class="text-pink-100 text-sm">Lengkapi data alamat pengiriman skincare-mu</p>
                </div>
            </div>
        </div>

        <form action="{{ route('user-alamat.store') }}" method="POST" class="p-6 space-y-4">
            @csrf

            @if(request('pesanan_id'))
                <input type="hidden" name="pesanan_id" value="{{ request('pesanan_id') }}">
            @endif

            {{-- Nama Penerima --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">🌸 Nama Penerima</label>
                <input type="text" name="nama_penerima" value="{{ old('nama_penerima') }}"
                       class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400 focus:border-transparent transition"
                       placeholder="Contoh: Budi Santoso" required>
            </div>

            {{-- No HP --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">📱 No. HP</label>
                <input type="text" name="no_hp" value="{{ old('no_hp') }}"
                       class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400 focus:border-transparent transition"
                       placeholder="Contoh: 08123456789" required>
            </div>

            {{-- Provinsi --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">📍 Provinsi</label>
                <select name="province_code" id="province_code"
                        class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400 bg-white"
                        onchange="loadCities(this.value)" required>
                    <option value="">-- Pilih Provinsi --</option>
                    @foreach($provinces as $prov)
                        <option value="{{ $prov->code }}"
                                data-name="{{ $prov->name }}"
                                {{ old('province_code') == $prov->code ? 'selected' : '' }}>
                            {{ $prov->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            {{-- Kota --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">🏙️ Kota / Kabupaten</label>
                <select name="city_code" id="city_code"
                        class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400 bg-white"
                        onchange="loadDistricts(this.value)" required>
                    <option value="">-- Pilih Kota --</option>
                </select>
            </div>

            {{-- Kecamatan --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">🗺️ Kecamatan</label>
                <select name="district_code" id="district_code"
                        class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400 bg-white"
                        onchange="loadVillages(this.value)" required>
                    <option value="">-- Pilih Kecamatan --</option>
                </select>
            </div>

            {{-- Kelurahan --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">🏡 Kelurahan / Desa</label>
                <select name="village_code" id="village_code"
                        class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400 bg-white"
                        onchange="geocodeFromWilayah()" required>
                    <option value="">-- Pilih Kelurahan --</option>
                </select>
            </div>

            {{-- Alamat Lengkap --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">📝 Alamat Lengkap</label>
                <textarea name="alamat_lengkap" rows="3"
                          class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400"
                          placeholder="Nama jalan, nomor rumah, RT/RW, dll" required>{{ old('alamat_lengkap') }}</textarea>
            </div>

            {{-- Kode Pos --}}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">✉️ Kode Pos</label>
                <input type="text" name="kode_pos" value="{{ old('kode_pos') }}"
                    class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400"
                    placeholder="Contoh: 16412"
                    inputmode="numeric" pattern="[0-9]*" maxlength="10"
                    oninput="this.value = this.value.replace(/[^0-9]/g, '')">
            </div>

            {{-- Koordinat --}}
            <div class="border border-pink-200 rounded-xl p-4 bg-pink-50/40">
                <label class="block text-sm font-semibold text-gray-700 mb-3">
                    <i class="fas fa-map-marker-alt mr-1 text-pink-500"></i>
                    📍 Koordinat Alamat
                    <span class="text-xs font-normal text-gray-400 ml-1">(untuk perhitungan ongkir)</span>
                </label>

                {{-- Status geocoding --}}
                <div id="geocodeStatus" class="hidden mb-3 p-2.5 rounded-lg text-xs flex items-center gap-2">
                </div>

                <div class="grid grid-cols-2 gap-3 mb-3">
                    <div>
                        <input type="text" name="latitude" id="latitude"
                               value="{{ old('latitude') }}"
                               placeholder="-8.720000"
                               class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400 bg-white"
                               readonly>
                        <p class="text-xs text-gray-400 mt-1">Latitude</p>
                    </div>
                    <div>
                        <input type="text" name="longitude" id="longitude"
                               value="{{ old('longitude') }}"
                               placeholder="115.170000"
                               class="w-full border border-pink-200 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-pink-400 bg-white"
                               readonly>
                        <p class="text-xs text-gray-400 mt-1">Longitude</p>
                    </div>
                </div>

                <p class="text-xs text-gray-500 text-center">
                    <i class="fas fa-info-circle text-pink-400 mr-1"></i>
                    ✨ Koordinat diisi otomatis saat kamu memilih kelurahan
                </p>
            </div>

            {{-- Alamat Utama --}}
            <div class="flex items-center gap-2">
                <input type="checkbox" name="alamat_utama" id="alamat_utama" value="1"
                       class="w-4 h-4 text-pink-500 rounded border-pink-300 focus:ring-pink-400" {{ old('alamat_utama') ? 'checked' : '' }}>
                <label for="alamat_utama" class="text-sm text-gray-700">⭐ Jadikan sebagai alamat utama</label>
            </div>

            {{-- Tombol --}}
            <div class="flex gap-3 pt-2">
                <a href="{{ $fromCheckout ? url()->previous() : route('user-alamat.index') }}"
                   class="flex-1 border-2 border-pink-300 text-pink-600 py-3 rounded-xl font-semibold text-center hover:bg-pink-50 transition-colors">
                    Batal
                </a>
                <button type="submit" id="submitBtn"
                        class="flex-1 bg-gradient-to-r from-pink-400 to-rose-400 text-white py-3 rounded-xl font-bold hover:from-pink-500 hover:to-rose-500 transition-all shadow-md hover:shadow-pink-200">
                    <i class="fa-regular fa-heart mr-1"></i> Simpan Alamat
                </button>
            </div>

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

<script>
// Simpan nama wilayah yang dipilih untuk geocoding
let selectedWilayah = {
    province: '',
    city: '',
    district: '',
    village: '',
};

// ============================================================
// LOAD WILAYAH (fungsi asli tidak diubah)
// ============================================================
function loadCities(provinceCode) {
    if (!provinceCode) return;

    const sel = document.getElementById('province_code');
    selectedWilayah.province = sel.options[sel.selectedIndex].dataset.name || sel.options[sel.selectedIndex].text;
    selectedWilayah.city = '';
    selectedWilayah.district = '';
    selectedWilayah.village = '';
    clearKoordinat();

    fetch(`/get-cities/${provinceCode}`)
        .then(r => r.json())
        .then(data => {
            const select = document.getElementById('city_code');
            select.innerHTML = '<option value="">-- Pilih Kota --</option>';
            data.forEach(item => {
                select.innerHTML += `<option value="${item.code}" data-name="${item.name}">${item.name}</option>`;
            });
            document.getElementById('district_code').innerHTML = '<option value="">-- Pilih Kecamatan --</option>';
            document.getElementById('village_code').innerHTML  = '<option value="">-- Pilih Kelurahan --</option>';
        });
}

function loadDistricts(cityCode) {
    if (!cityCode) return;

    const sel = document.getElementById('city_code');
    selectedWilayah.city = sel.options[sel.selectedIndex].dataset.name || sel.options[sel.selectedIndex].text;
    selectedWilayah.district = '';
    selectedWilayah.village = '';
    clearKoordinat();

    fetch(`/get-districts/${cityCode}`)
        .then(r => r.json())
        .then(data => {
            const select = document.getElementById('district_code');
            select.innerHTML = '<option value="">-- Pilih Kecamatan --</option>';
            data.forEach(item => {
                select.innerHTML += `<option value="${item.code}" data-name="${item.name}">${item.name}</option>`;
            });
            document.getElementById('village_code').innerHTML = '<option value="">-- Pilih Kelurahan --</option>';
        });
}

function loadVillages(districtCode) {
    if (!districtCode) return;

    const sel = document.getElementById('district_code');
    selectedWilayah.district = sel.options[sel.selectedIndex].dataset.name || sel.options[sel.selectedIndex].text;
    selectedWilayah.village = '';
    clearKoordinat();

    fetch(`/get-villages/${districtCode}`)
        .then(r => r.json())
        .then(data => {
            const select = document.getElementById('village_code');
            select.innerHTML = '<option value="">-- Pilih Kelurahan --</option>';
            data.forEach(item => {
                select.innerHTML += `<option value="${item.code}" data-name="${item.name}">${item.name}</option>`;
            });
        });
}

// ============================================================
// GEOCODE OTOMATIS DARI NAMA WILAYAH (via Nominatim)
// Fungsi asli tetap sama persis
// ============================================================
function geocodeFromWilayah() {
    const villageSel = document.getElementById('village_code');
    selectedWilayah.village = villageSel.options[villageSel.selectedIndex]?.dataset.name
        || villageSel.options[villageSel.selectedIndex]?.text || '';

    if (!selectedWilayah.village || !selectedWilayah.district) return;

    const parts = [
        selectedWilayah.village,
        selectedWilayah.district,
        selectedWilayah.city,
        selectedWilayah.province,
        'Indonesia'
    ].filter(Boolean);

    const query = parts.join(', ');

    showGeoStatus('loading', '<i class="fas fa-circle-notch fa-spin"></i> Mencari koordinat...');

    fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&limit=1&countrycodes=id`, {
        headers: { 'Accept-Language': 'id,en' }
    })
    .then(r => r.json())
    .then(data => {
        if (data && data.length > 0) {
            const lat = parseFloat(data[0].lat).toFixed(7);
            const lng = parseFloat(data[0].lon).toFixed(7);

            document.getElementById('latitude').value  = lat;
            document.getElementById('longitude').value = lng;

            showGeoStatus('success',
                `<i class="fas fa-check-circle"></i> Koordinat ditemukan: ${lat}, ${lng}`);
        } else {
            const queryShort = [selectedWilayah.city, selectedWilayah.province, 'Indonesia'].filter(Boolean).join(', ');
            return geocodeWithQuery(queryShort);
        }
    })
    .catch(() => {
        showGeoStatus('error', '<i class="fas fa-exclamation-triangle"></i> Gagal mencari koordinat otomatis');
    });
}

function geocodeWithQuery(query) {
    fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&limit=1&countrycodes=id`, {
        headers: { 'Accept-Language': 'id,en' }
    })
    .then(r => r.json())
    .then(data => {
        if (data && data.length > 0) {
            const lat = parseFloat(data[0].lat).toFixed(7);
            const lng = parseFloat(data[0].lon).toFixed(7);
            document.getElementById('latitude').value  = lat;
            document.getElementById('longitude').value = lng;
            showGeoStatus('success',
                `<i class="fas fa-check-circle"></i> Koordinat perkiraan (${selectedWilayah.city}): ${lat}, ${lng}`);
        } else {
            showGeoStatus('error', '<i class="fas fa-exclamation-triangle"></i> Koordinat tidak ditemukan, isi manual');
        }
    })
    .catch(() => {
        showGeoStatus('error', '<i class="fas fa-exclamation-triangle"></i> Gagal koneksi ke layanan peta');
    });
}

function showGeoStatus(type, html) {
    const el = document.getElementById('geocodeStatus');
    el.classList.remove('hidden', 'bg-blue-50', 'text-blue-600', 'bg-green-50', 'text-green-600', 'bg-red-50', 'text-red-600');

    if (type === 'loading') {
        el.classList.add('bg-pink-100', 'text-pink-600');
    } else if (type === 'success') {
        el.classList.add('bg-green-100', 'text-green-700');
    } else {
        el.classList.add('bg-rose-100', 'text-rose-600');
    }

    el.innerHTML = html;
    el.classList.remove('hidden');
}

function clearKoordinat() {
    document.getElementById('latitude').value  = '';
    document.getElementById('longitude').value = '';
    document.getElementById('geocodeStatus').classList.add('hidden');
}
</script>

</body>
</html>