@extends('layouts.anggota')

@section('content')
<div class="container-fluid py-4">
    <div class="header-section mb-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5">
                <li class="breadcrumb-item text-sm">
                    <a class="opacity-5 text-dark" href="{{ route('admin.anggota.index') }}">Anggota</a>
                </li>
                <li class="breadcrumb-item text-sm text-dark active" aria-current="page">Edit Profil</li>
            </ol>
        </nav>
        <h3 class="font-weight-bolder mb-0 text-primary">Edit Data Anggota 🖋️</h3>
    </div>

    <div class="row">
        <div class="col-lg-10 mx-auto">
            
            {{-- 🌟 KOTAK DETEKSI ERROR --}}
            @if ($errors->any())
                <div class="alert alert-danger text-white p-3 mb-4 shadow-sm" style="border-radius: 0.5rem; background-image: linear-gradient(310deg, #ea0606, #ff3d3d);">
                    <h6 class="text-white font-weight-bold mb-2">⚠️ Gagal Menyimpan Perubahan:</h6>
                    <ul class="mb-0 text-sm">
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <div class="card shadow-lg border-0" style="border-radius: 1rem;">
                <div class="card-body p-4">
                    <form action="{{ route('admin.anggota.update', $member->id) }}" method="POST">
                        @csrf
                        @method('PUT')

                        <div class="row">
                            <!-- Kolom Kiri: Data Personal -->
                            <div class="col-md-6 border-end-md">
                                <h6 class="text-uppercase text-muted mt-2 mb-3">Informasi Dasar</h6>
                                
                                <div class="mb-3">
                                    <label class="form-label font-weight-bold">Nama Lengkap</label>
                                    <input type="text" name="nama" class="form-control @error('nama') is-invalid @enderror" 
                                        value="{{ old('nama', $member->nama) }}" maxlength="100" required>
                                    @error('nama')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label class="form-label font-weight-bold">Jenis Kelamin</label>
                                    <select name="gender" class="form-select @error('gender') is-invalid @enderror" required>
                                        <option value="">Pilih Jenis Kelamin</option>
                                        <option value="Laki-laki" {{ old('gender', $member->gender) == 'Laki-laki' ? 'selected' : '' }}>Laki-laki</option>
                                        <option value="Perempuan" {{ old('gender', $member->gender) == 'Perempuan' ? 'selected' : '' }}>Perempuan</option>
                                    </select>
                                    @error('gender')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label class="form-label font-weight-bold">NIK / NIP</label>
                                    <input type="text" name="nik_nip" class="form-control @error('nik_nip') is-invalid @enderror" 
                                        value="{{ old('nik_nip', $member->nik_nip ?? ($member->nik ?? $member->nip)) }}" 
                                        maxlength="18" 
                                        oninput="this.value = this.value.replace(/[^0-9]/g, '')"
                                        placeholder="Masukkan 16 digit NIK atau 18 digit NIP"
                                        required>
                                    @error('nik_nip')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label class="form-label font-weight-bold">Email</label>
                                    <input type="email" name="email" class="form-control @error('email') is-invalid @enderror" 
                                        value="{{ old('email', $member->email) }}" maxlength="150" required>
                                    @error('email')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label class="form-label font-weight-bold">Nomor HP</label>
                                    <input type="text" name="no_hp" class="form-control @error('no_hp') is-invalid @enderror" 
                                        value="{{ old('no_hp', $member->no_hp) }}" maxlength="20" placeholder="08xxxxxxxxxx">
                                    @error('no_hp')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <!-- Kolom Kanan: Data Alamat -->
                            <div class="col-md-6">
                                <h6 class="text-uppercase text-muted mt-2 mb-3">Lokasi & Alamat</h6>
                                
                                <div class="mb-3">
                                    <label class="form-label font-weight-bold">Provinsi</label>
                                    <select id="provinsi" name="provinsi" class="form-select @error('provinsi') is-invalid @enderror" 
                                        data-selected="{{ old('provinsi', $member->provinsi) }}" required>
                                        <option value="">Pilih Provinsi</option>
                                    </select>
                                    @error('provinsi')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label class="form-label font-weight-bold">Kota/Kabupaten</label>
                                    <select id="kota" name="kota" class="form-select @error('kota') is-invalid @enderror" 
                                        data-selected="{{ old('kota', $member->kota) }}" required>
                                        <option value="">Pilih Kota</option>
                                    </select>
                                    @error('kota')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label font-weight-bold">Kecamatan</label>
                                        <select id="kecamatan" name="kecamatan" class="form-select @error('kecamatan') is-invalid @enderror" 
                                            data-selected="{{ old('kecamatan', $member->kecamatan) }}" required>
                                            <option value="">Pilih Kecamatan</option>
                                        </select>
                                        @error('kecamatan')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label font-weight-bold">Kelurahan / Desa</label>
                                        <select id="kelurahan" name="desa" class="form-select @error('desa') is-invalid @enderror" 
                                            data-selected="{{ old('desa', $member->desa ?? $member->kelurahan) }}" required>
                                            <option value="">Pilih Kelurahan</option>
                                        </select>
                                        @error('desa')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label font-weight-bold">Alamat Lengkap (Jalan/No. Rumah)</label>
                                    <textarea id="alamat_textarea" name="alamat" class="form-control @error('alamat') is-invalid @enderror" rows="4" minlength="10" maxlength="255" placeholder="Nama Jalan, RT/RW, No. Rumah, dst..." required>{{ old('alamat', $member->alamat) }}</textarea>
                                    @error('alamat')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <hr class="horizontal dark my-4">

                        <div class="d-flex justify-content-between align-items-center">
                            <a href="{{ route('admin.anggota.index') }}" class="btn btn-light px-4 mb-0">
                                <i class="fas fa-times me-1"></i> Batal
                            </a>
                            <button type="submit" class="btn btn-primary px-5 shadow-sm mb-0">
                                <i class="fas fa-save me-1"></i> Simpan Perubahan
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- SCRIPT API WILAYAH INDONESIA + SORT ABJAD + AUTO-FILL -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const provSelect = document.getElementById('provinsi');
        const kotaSelect = document.getElementById('kota');
        const kecSelect = document.getElementById('kecamatan');
        const kelSelect = document.getElementById('kelurahan');
        const alamatTextarea = document.getElementById('alamat_textarea');

        function sortByName(array) {
            return array.sort((a, b) => a.name.localeCompare(b.name));
        }

        function updateAlamatLengkap() {
            if (provSelect.value && kotaSelect.value && kecSelect.value && kelSelect.value) {
                const provText = provSelect.options[provSelect.selectedIndex].text;
                const kotaText = kotaSelect.options[kotaSelect.selectedIndex].text;
                const kecText = kecSelect.options[kecSelect.selectedIndex].text;
                const kelText = kelSelect.options[kelSelect.selectedIndex].text;

                const textWilayahOtomatis = `Desa/Kel. ${kelText}, Kec. ${kecText}, ${kotaText}, Prov. ${provText}`;
                let alamatUserSaatIni = alamatTextarea.value.trim();
                const indexPemisah = alamatUserSaatIni.indexOf(', Desa/Kel.');

                if (indexPemisah !== -1) {
                    let bagianJalanSaja = alamatUserSaatIni.substring(0, indexPemisah);
                    alamatTextarea.value = bagianJalanSaja + ', ' + textWilayahOtomatis;
                } else {
                    if(alamatUserSaatIni === "") {
                        alamatTextarea.value = textWilayahOtomatis;
                    } else {
                        alamatTextarea.value = alamatUserSaatIni + ', ' + textWilayahOtomatis;
                    }
                }
            }
        }

        kelSelect.addEventListener('change', updateAlamatLengkap);

        // 1. Load Provinsi
        fetch(`https://www.emsifa.com/api-wilayah-indonesia/api/provinces.json`)
            .then(response => response.json())
            .then(provinces => {
                sortByName(provinces).forEach(prov => {
                    let opt = document.createElement('option');
                    opt.value = prov.id;
                    opt.text = prov.name;
                    if(prov.id == provSelect.getAttribute('data-selected') || prov.name == provSelect.getAttribute('data-selected')) {
                        opt.selected = true;
                    }
                    provSelect.add(opt);
                });
                if (provSelect.value) provSelect.dispatchEvent(new Event('change'));
            });

        // 2. Load Kota
        provSelect.addEventListener('change', function() {
            if(!this.value) {
                kotaSelect.innerHTML = '<option value="">Pilih Kota</option>';
                kecSelect.innerHTML = '<option value="">Pilih Kecamatan</option>';
                kelSelect.innerHTML = '<option value="">Pilih Kelurahan</option>';
                return;
            }
            fetch(`https://www.emsifa.com/api-wilayah-indonesia/api/regencies/${this.value}.json`)
                .then(response => response.json())
                .then(data => {
                    kotaSelect.innerHTML = '<option value="">Pilih Kota</option>';
                    kecSelect.innerHTML = '<option value="">Pilih Kecamatan</option>';
                    kelSelect.innerHTML = '<option value="">Pilih Kelurahan</option>';
                    
                    sortByName(data).forEach(row => {
                        let opt = document.createElement('option');
                        opt.value = row.id;
                        opt.text = row.name;
                        if(row.id == kotaSelect.getAttribute('data-selected') || row.name == kotaSelect.getAttribute('data-selected')) {
                            opt.selected = true;
                        }
                        kotaSelect.add(opt);
                    });
                    if (kotaSelect.value) kotaSelect.dispatchEvent(new Event('change'));
                });
        });

        // 3. Load Kecamatan
        kotaSelect.addEventListener('change', function() {
            if(!this.value) {
                kecSelect.innerHTML = '<option value="">Pilih Kecamatan</option>';
                kelSelect.innerHTML = '<option value="">Pilih Kelurahan</option>';
                return;
            }
            fetch(`https://www.emsifa.com/api-wilayah-indonesia/api/districts/${this.value}.json`)
                .then(response => response.json())
                .then(data => {
                    kecSelect.innerHTML = '<option value="">Pilih Kecamatan</option>';
                    kelSelect.innerHTML = '<option value="">Pilih Kelurahan</option>';
                    
                    sortByName(data).forEach(row => {
                        let opt = document.createElement('option');
                        opt.value = row.id;
                        opt.text = row.name;
                        if(row.id == kecSelect.getAttribute('data-selected') || row.name == kecSelect.getAttribute('data-selected')) {
                            opt.selected = true;
                        }
                        kecSelect.add(opt);
                    });
                    if (kecSelect.value) kecSelect.dispatchEvent(new Event('change'));
                });
        });

        // 4. Load Kelurahan
        kecSelect.addEventListener('change', function() {
            if(!this.value) {
                kelSelect.innerHTML = '<option value="">Pilih Kelurahan</option>';
                return;
            }
            fetch(`https://www.emsifa.com/api-wilayah-indonesia/api/villages/${this.value}.json`)
                .then(response => response.json())
                .then(data => {
                    kelSelect.innerHTML = '<option value="">Pilih Kelurahan</option>';
                    
                    sortByName(data).forEach(row => {
                        let opt = document.createElement('option');
                        opt.value = row.id;
                        opt.text = row.name;
                        if(row.id == kelSelect.getAttribute('data-selected') || row.name == kelSelect.getAttribute('data-selected')) {
                            opt.selected = true;
                        }
                        kelSelect.add(opt);
                    });
                });
        });
    });
</script>
@endsection