<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah Alamat - Raja Futsal</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">
</head>
<body class="bg-gray-100 min-h-screen py-8">

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

        
        <div class="bg-gradient-to-r from-orange-500 to-orange-600 p-6 text-white">
            <h2 class="text-2xl font-bold">Tambah Alamat Baru</h2>
            <p class="text-orange-100 text-sm">Lengkapi data alamat pengiriman kamu</p>
        </div>

        <form action="<?php echo e(route('user-alamat.store')); ?>" method="POST" class="p-6 space-y-4">
            <?php echo csrf_field(); ?>

            <?php if(request('pesanan_id')): ?>
                <input type="hidden" name="pesanan_id" value="<?php echo e(request('pesanan_id')); ?>">
            <?php endif; ?>

            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Nama Penerima</label>
                <input type="text" name="nama_penerima" value="<?php echo e(old('nama_penerima')); ?>"
                       class="w-full border border-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-400"
                       placeholder="Contoh: Budi Santoso" required>
            </div>

            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">No. HP</label>
                <input type="text" name="no_hp" value="<?php echo e(old('no_hp')); ?>"
                       class="w-full border border-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-400"
                       placeholder="Contoh: 08123456789" required>
            </div>

            
            <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-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-400"
                        onchange="loadCities(this.value)" required>
                    <option value="">-- Pilih Provinsi --</option>
                    <?php $__currentLoopData = $provinces; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $prov): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($prov->code); ?>"
                                data-name="<?php echo e($prov->name); ?>"
                                <?php echo e(old('province_code') == $prov->code ? 'selected' : ''); ?>>
                            <?php echo e($prov->name); ?>

                        </option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </div>

            
            <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-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-400"
                        onchange="loadDistricts(this.value)" required>
                    <option value="">-- Pilih Kota --</option>
                </select>
            </div>

            
            <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-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-400"
                        onchange="loadVillages(this.value)" required>
                    <option value="">-- Pilih Kecamatan --</option>
                </select>
            </div>

            
            <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-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-400"
                        onchange="geocodeFromWilayah()" required>
                    <option value="">-- Pilih Kelurahan --</option>
                </select>
            </div>

            
            <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-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-400"
                          placeholder="Nama jalan, nomor rumah, RT/RW, dll" required><?php echo e(old('alamat_lengkap')); ?></textarea>
            </div>

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

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

                
                <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="<?php echo e(old('latitude')); ?>"
                               placeholder="-8.720000"
                               class="w-full border border-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-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="<?php echo e(old('longitude')); ?>"
                               placeholder="115.170000"
                               class="w-full border border-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-orange-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-orange-400 mr-1"></i>
                    Koordinat diisi otomatis saat kamu memilih kelurahan
                </p>
            </div>

            
            <div class="flex items-center gap-2">
                <input type="checkbox" name="alamat_utama" id="alamat_utama" value="1"
                       class="w-4 h-4 text-orange-500" <?php echo e(old('alamat_utama') ? 'checked' : ''); ?>>
                <label for="alamat_utama" class="text-sm text-gray-700">Jadikan sebagai alamat utama</label>
            </div>

    
<div class="flex gap-3 pt-2">
    <button type="submit" id="submitBtn"
            class="flex-1 bg-gradient-to-r from-orange-500 to-orange-600 text-white py-3 rounded-xl font-bold hover:from-orange-600 hover:to-orange-700 transition-all flex items-center justify-center gap-2">
        <i class="fas fa-save"></i>
        <span>Simpan Alamat</span>
    </button>
    <a href="<?php echo e($fromCheckout ? url()->previous() : route('user-alamat.index')); ?>"
       class="flex-1 border-2 border-gray-300 text-gray-600 py-3 rounded-xl font-semibold text-center hover:bg-gray-50 transition-colors">
        Batal
    </a>
</div>

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

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

// ============================================================
// LOAD WILAYAH
// ============================================================
function loadCities(provinceCode) {
    if (!provinceCode) return;

    // Simpan nama provinsi
    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)
// ============================================================
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;

    // Susun query: "Kelurahan, Kecamatan, Kota, Provinsi, Indonesia"
    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 {
            // Coba query lebih singkat (kota + provinsi saja)
            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-blue-50', 'text-blue-600');
    } else if (type === 'success') {
        el.classList.add('bg-green-50', 'text-green-600');
    } else {
        el.classList.add('bg-red-50', 'text-red-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><?php /**PATH C:\laragon\www\ecommerce\resources\views/user_alamat/create.blade.php ENDPATH**/ ?>