@extends('layouts.app')

@section('title', 'Edit Anggota - Sistem Informasi PKS')

@section('content')
<!-- Success/Error Messages -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i>
        {{ session('success') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
@endif

@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i>
        {{ session('error') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
@endif

<style>
    .form-container {
        max-width: 100%;
        overflow-x: hidden;
    }
    
    .card {
        margin-bottom: 1.5rem;
    }
    
    .form-control, .form-select {
        width: 100%;
    }
    
    @media (max-width: 768px) {
        .col-md-6, .col-md-4, .col-md-3 {
            margin-bottom: 1rem;
        }
    }
</style>
<div class="row mb-4">
    <div class="col-md-6">
        <h1 class="h3 text-gray-800 mb-0">Edit Data Anggota</h1>
        <p class="text-muted">Update informasi anggota: <strong>{{ $anggota->nama_lengkap }}</strong></p>
    </div>
    <div class="col-md-6 text-end">
        <a href="{{ $anggota->show_url }}" class="btn btn-outline-info me-2">
            <i class="fas fa-eye me-1"></i> Lihat Detail
        </a>
        <a href="{{ route('anggota.index') }}" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-1"></i> Kembali ke Daftar
        </a>
    </div>
</div>

<div class="form-container">
<form action="{{ route('anggota.update', \App\Helpers\UrlHelper::generateAnggotaUrl($anggota->id, $anggota->nama_lengkap)) }}" method="POST" enctype="multipart/form-data">
    @csrf
    @method('PUT')
    
    <!-- Data Identitas -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-white">
                <i class="fas fa-id-card me-2"></i>Data Identitas
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label required">Nomor Identitas Anggota (NIA)</label>
                    <input type="text" class="form-control @error('nomor_identitas_anggota') is-invalid @enderror" 
                           name="nomor_identitas_anggota" value="{{ old('nomor_identitas_anggota', $anggota->nomor_identitas_anggota) }}" 
                           placeholder="Contoh: PKS-001-2024" required>
                    @error('nomor_identitas_anggota')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label required">Nama Lengkap</label>
                    <input type="text" class="form-control @error('nama_lengkap') is-invalid @enderror" 
                           name="nama_lengkap" value="{{ old('nama_lengkap', $anggota->nama_lengkap) }}" 
                           placeholder="Masukkan nama lengkap" required>
                    @error('nama_lengkap')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label required">Tempat Lahir</label>
                    <input type="text" class="form-control @error('tempat_lahir') is-invalid @enderror" 
                           name="tempat_lahir" value="{{ old('tempat_lahir', $anggota->tempat_lahir) }}" 
                           placeholder="Kota kelahiran" required>
                    @error('tempat_lahir')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label required">Tanggal Lahir</label>
                    <input type="date" class="form-control @error('tanggal_lahir') is-invalid @enderror" 
                           name="tanggal_lahir" value="{{ old('tanggal_lahir', $anggota->tanggal_lahir->format('Y-m-d')) }}" required>
                    @error('tanggal_lahir')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label required">Jenis Kelamin</label>
                    <select class="form-select @error('jenis_kelamin') is-invalid @enderror" 
                            name="jenis_kelamin" required>
                        <option value="">Pilih Jenis Kelamin</option>
                        <option value="L" {{ old('jenis_kelamin', $anggota->jenis_kelamin) == 'L' ? 'selected' : '' }}>Laki-laki</option>
                        <option value="P" {{ old('jenis_kelamin', $anggota->jenis_kelamin) == 'P' ? 'selected' : '' }}>Perempuan</option>
                    </select>
                    @error('jenis_kelamin')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
        </div>
    </div>

    <!-- Data Alamat -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-white">
                <i class="fas fa-map-marker-alt me-2"></i>Data Alamat
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-8 mb-3">
                    <label class="form-label required">Alamat Jalan</label>
                    <textarea class="form-control @error('alamat_jalan') is-invalid @enderror" 
                              name="alamat_jalan" rows="2" 
                              placeholder="Alamat lengkap termasuk nomor rumah" required>{{ old('alamat_jalan', $anggota->alamat_jalan) }}</textarea>
                    @error('alamat_jalan')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-2 mb-3">
                    <label class="form-label required">RT</label>
                    <input type="text" class="form-control @error('rt') is-invalid @enderror" 
                           name="rt" value="{{ old('rt', $anggota->rt) }}" placeholder="001" maxlength="3" required>
                    @error('rt')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-2 mb-3">
                    <label class="form-label required">RW</label>
                    <input type="text" class="form-control @error('rw') is-invalid @enderror" 
                           name="rw" value="{{ old('rw', $anggota->rw) }}" placeholder="001" maxlength="3" required>
                    @error('rw')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="form-label required">Kelurahan/Desa</label>
                    <input type="text" class="form-control @error('kelurahan') is-invalid @enderror" 
                           name="kelurahan" value="{{ old('kelurahan', $anggota->kelurahan) }}" 
                           placeholder="Nama kelurahan" required>
                    @error('kelurahan')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label required">Kecamatan</label>
                    <input type="text" class="form-control @error('kecamatan') is-invalid @enderror" 
                           name="kecamatan" value="{{ old('kecamatan', $anggota->kecamatan) }}" 
                           placeholder="Nama kecamatan" required>
                    @error('kecamatan')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label required">Kota/Kabupaten</label>
                    <input type="text" class="form-control @error('kota') is-invalid @enderror" 
                           name="kota" value="{{ old('kota', $anggota->kota) }}" 
                           placeholder="Nama kota/kabupaten" required>
                    @error('kota')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label required">Provinsi</label>
                    <select class="form-select @error('provinsi') is-invalid @enderror" 
                            name="provinsi" required>
                        <option value="">Pilih Provinsi</option>
                        <option value="Jawa Barat" {{ old('provinsi', $anggota->provinsi) == 'Jawa Barat' ? 'selected' : '' }}>Jawa Barat</option>
                        <option value="DKI Jakarta" {{ old('provinsi', $anggota->provinsi) == 'DKI Jakarta' ? 'selected' : '' }}>DKI Jakarta</option>
                        <option value="Jawa Tengah" {{ old('provinsi', $anggota->provinsi) == 'Jawa Tengah' ? 'selected' : '' }}>Jawa Tengah</option>
                        <option value="Jawa Timur" {{ old('provinsi', $anggota->provinsi) == 'Jawa Timur' ? 'selected' : '' }}>Jawa Timur</option>
                        <option value="Sumatera Utara" {{ old('provinsi', $anggota->provinsi) == 'Sumatera Utara' ? 'selected' : '' }}>Sumatera Utara</option>
                        <option value="Sumatera Barat" {{ old('provinsi', $anggota->provinsi) == 'Sumatera Barat' ? 'selected' : '' }}>Sumatera Barat</option>
                        <option value="Sumatera Selatan" {{ old('provinsi', $anggota->provinsi) == 'Sumatera Selatan' ? 'selected' : '' }}>Sumatera Selatan</option>
                        <option value="Kalimantan Timur" {{ old('provinsi', $anggota->provinsi) == 'Kalimantan Timur' ? 'selected' : '' }}>Kalimantan Timur</option>
                        <option value="Sulawesi Selatan" {{ old('provinsi', $anggota->provinsi) == 'Sulawesi Selatan' ? 'selected' : '' }}>Sulawesi Selatan</option>
                    </select>
                    @error('provinsi')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">Kode Pos</label>
                    <input type="text" class="form-control @error('kode_pos') is-invalid @enderror" 
                           name="kode_pos" value="{{ old('kode_pos', $anggota->kode_pos) }}" 
                           placeholder="Contoh: 12345" maxlength="5">
                    @error('kode_pos')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
        </div>
    </div>

    <!-- Data Kontak -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-white">
                <i class="fas fa-phone me-2"></i>Data Kontak
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Nomor Telepon</label>
                    <input type="tel" class="form-control @error('no_telepon') is-invalid @enderror" 
                           name="no_telepon" value="{{ old('no_telepon', $anggota->no_telepon) }}" 
                           placeholder="081234567890">
                    @error('no_telepon')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Email</label>
                    <input type="email" class="form-control @error('email') is-invalid @enderror" 
                           name="email" value="{{ old('email', $anggota->email) }}" 
                           placeholder="nama@email.com">
                    @error('email')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
        </div>
    </div>

    <!-- Data Keanggotaan -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-white">
                <i class="fas fa-id-badge me-2"></i>Data Keanggotaan
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label required">Jenjang Anggota</label>
                    <select class="form-select @error('ref_jenjang_id') is-invalid @enderror" 
                            name="ref_jenjang_id" required>
                        <option value="">Pilih Jenjang</option>
                        @foreach(\App\Models\RefJenjang::whereIn('jenjang', ['Pendukung', 'Penggerak', 'Madya', 'Dewasa', 'Utama'])->where('is_active', true)->orderByRaw("FIELD(jenjang, 'Pendukung', 'Penggerak', 'Madya', 'Dewasa', 'Utama')")->get() as $jenjang)
                            <option value="{{ $jenjang->ref_jenjang_id }}" {{ old('ref_jenjang_id', $anggota->ref_jenjang_id) == $jenjang->ref_jenjang_id ? 'selected' : '' }}>
                                {{ $jenjang->jenjang }}
                            </option>
                        @endforeach
                    </select>
                    @error('ref_jenjang_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">DPD</label>
                    <select class="form-select @error('dpd_id') is-invalid @enderror" 
                            name="dpd_id" id="dpd_id" onchange="loadDpcByDpd()">
                        <option value="">Pilih DPD</option>
                        @foreach(\App\Models\Dpd::active()->get() as $dpd)
                            <option value="{{ $dpd->dpd_id }}" {{ old('dpd_id', $anggota->dpd_id) == $dpd->dpd_id ? 'selected' : '' }}>
                                {{ $dpd->nama_dpd }}
                            </option>
                        @endforeach
                    </select>
                    @error('dpd_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">DPC</label>
                    <select class="form-select @error('dpc_id') is-invalid @enderror" 
                            name="dpc_id" id="dpc_id" onchange="loadUpaByDpc()">
                        <option value="">Pilih DPC</option>
                        @if(old('dpc_id', $anggota->dpc_id))
                            @foreach(\App\Models\Dpc::where('dpd_id', old('dpd_id', $anggota->dpd_id))->active()->get() as $dpc)
                                <option value="{{ $dpc->dpc_id }}" {{ old('dpc_id', $anggota->dpc_id) == $dpc->dpc_id ? 'selected' : '' }}>
                                    {{ $dpc->nama_dpc }}
                                </option>
                            @endforeach
                        @endif
                    </select>
                    @error('dpc_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">UPA</label>
                    <select class="form-select @error('upa_id') is-invalid @enderror" 
                            name="upa_id" id="upa_id">
                        <option value="">Pilih UPA</option>
                        @if(old('upa_id', $anggota->upa_id))
                            @foreach(\App\Models\Upa::where('dpc_id', old('dpc_id', $anggota->dpc_id))->active()->get() as $upa)
                                <option value="{{ $upa->upa_id }}" {{ old('upa_id', $anggota->upa_id) == $upa->upa_id ? 'selected' : '' }}>
                                    {{ $upa->nama_upa }}
                                </option>
                            @endforeach
                        @endif
                    </select>
                    @error('upa_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label required">Tanggal Bergabung</label>
                    <input type="date" class="form-control @error('tanggal_bergabung') is-invalid @enderror" 
                           name="tanggal_bergabung" value="{{ old('tanggal_bergabung', $anggota->tanggal_bergabung->format('Y-m-d')) }}" required>
                    @error('tanggal_bergabung')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label required">Status Keanggotaan</label>
                    <select class="form-select @error('status_keanggotaan') is-invalid @enderror" 
                            name="status_keanggotaan" required>
                        <option value="">Pilih Status</option>
                        <option value="Aktif" {{ old('status_keanggotaan', $anggota->status_keanggotaan) == 'Aktif' ? 'selected' : '' }}>Aktif</option>
                        <option value="Tidak Aktif" {{ old('status_keanggotaan', $anggota->status_keanggotaan) == 'Tidak Aktif' ? 'selected' : '' }}>Tidak Aktif</option>
                        <option value="Diberhentikan" {{ old('status_keanggotaan', $anggota->status_keanggotaan) == 'Diberhentikan' ? 'selected' : '' }}>Diberhentikan</option>
                        <option value="Pindah" {{ old('status_keanggotaan', $anggota->status_keanggotaan) == 'Pindah' ? 'selected' : '' }}>Pindah</option>
                    </select>
                    @error('status_keanggotaan')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            
            <!-- Keahlian -->
            <div class="row">
                <div class="col-md-12 mb-3">
                    <label class="form-label">Keahlian</label>
                    <div class="row">
                        @foreach($keahlianList as $keahlian)
                            <div class="col-md-4 col-lg-3 mb-2">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" 
                                           name="keahlian_ids[]" 
                                           value="{{ $keahlian->ref_keahlian_id }}"
                                           id="keahlian_{{ $keahlian->ref_keahlian_id }}"
                                           {{ in_array($keahlian->ref_keahlian_id, old('keahlian_ids', $anggota->keahlian->pluck('ref_keahlian_id')->toArray())) ? 'checked' : '' }}>
                                    <label class="form-check-label" for="keahlian_{{ $keahlian->ref_keahlian_id }}">
                                        {{ $keahlian->nama_keahlian }}
                                    </label>
                                </div>
                            </div>
                        @endforeach
                        
                        <!-- Checkbox Lainnya -->
                        <div class="col-md-4 col-lg-3 mb-2">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" 
                                       name="keahlian_lainnya_check" 
                                       value="1"
                                       id="keahlian_lainnya_check"
                                       {{ old('keahlian_lainnya_check', $anggota->keahlian_lainnya ? '1' : '') ? 'checked' : '' }}
                                       onchange="toggleKeahlianLainnya()">
                                <label class="form-check-label fw-bold text-primary" for="keahlian_lainnya_check">
                                    Lainnya
                                </label>
                            </div>
                        </div>
                    </div>
                    @error('keahlian_ids')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                    @enderror
                    
                    <!-- Keahlian Lainnya Textarea -->
                    <div id="keahlian_lainnya_textarea" class="mt-3" style="display: none;">
                        <label class="form-label">Tuliskan Keahlian Lainnya</label>
                        <textarea class="form-control @error('keahlian_lainnya') is-invalid @enderror" 
                                  name="keahlian_lainnya" 
                                  rows="3" 
                                  placeholder="Tuliskan keahlian lainnya yang tidak ada dalam daftar di atas...">{{ old('keahlian_lainnya', $anggota->keahlian_lainnya) }}</textarea>
                        @error('keahlian_lainnya')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
            
            <!-- Aktivitas di Luar Pekerjaan -->
            <div class="row">
                <div class="col-md-12 mb-3">
                    <label class="form-label">Aktivitas di Luar Pekerjaan</label>
                    <div class="row">
                        @php
                            $aktivitasLuars = \App\Models\AktivitasLuar::active()->orderBy('nama_aktivitas')->get();
                            $selectedAktivitas = old('aktivitas_luar_ids', $anggota->aktivitasLuar->pluck('id')->toArray());
                            $lainnyaChecked = old('aktivitas_luar_lainnya_check', $anggota->aktivitas->where('uraian_aktivitas', '!=', '')->count() > 0);
                            $lainnyaText = old('aktivitas_luar_lainnya_text', $anggota->aktivitas->pluck('uraian_aktivitas')->filter()->implode(', '));
                        @endphp
                        @foreach($aktivitasLuars as $aktivitas)
                        <div class="col-md-4 col-lg-3 mb-2">
                            <div class="form-check">
                                <input class="form-check-input" 
                                       type="checkbox" 
                                       name="aktivitas_luar_ids[]" 
                                       value="{{ $aktivitas->id }}" 
                                       id="aktivitas_{{ $aktivitas->id }}"
                                       {{ in_array($aktivitas->id, $selectedAktivitas) ? 'checked' : '' }}>
                                <label class="form-check-label" for="aktivitas_{{ $aktivitas->id }}">
                                    {{ $aktivitas->nama_aktivitas }}
                                </label>
                            </div>
                        </div>
                        @endforeach
                        
                        <!-- Pilihan Lainnya dengan warna berbeda -->
                        <div class="col-md-4 col-lg-3 mb-2">
                            <div class="form-check">
                                <input class="form-check-input" 
                                       type="checkbox" 
                                       name="aktivitas_luar_lainnya_check" 
                                       value="1" 
                                       id="aktivitas_lainnya"
                                       {{ $lainnyaChecked ? 'checked' : '' }}
                                       onchange="toggleLainnyaInput()">
                                <label class="form-check-label text-warning fw-bold" for="aktivitas_lainnya">
                                    <i class="fas fa-edit me-1"></i>Lainnya
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Input untuk aktivitas lainnya -->
                    <div id="lainnya-input" class="mt-3" style="display: {{ $lainnyaChecked ? 'block' : 'none' }};">
                        <label for="aktivitas_luar_lainnya_text" class="form-label text-warning">
                            <i class="fas fa-pen me-1"></i>Tuliskan aktivitas lainnya:
                        </label>
                        <textarea class="form-control @error('aktivitas_luar_lainnya_text') is-invalid @enderror" 
                                  id="aktivitas_luar_lainnya_text" 
                                  name="aktivitas_luar_lainnya_text" 
                                  rows="2" 
                                  placeholder="Contoh: Pengurus Masjid Al-Ikhlas, Ketua Majelis Taklim, dll">{{ $lainnyaText }}</textarea>
                        @error('aktivitas_luar_lainnya_text')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    @error('aktivitas_luar_ids')
                        <div class="invalid-feedback d-block">{{ $message }}</div>
                    @enderror
                </div>
            </div>
        </div>
    </div>

    <!-- Data Ekonomi -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-white">
                <i class="fas fa-money-bill-wave me-2"></i>Data Ekonomi
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">Penghasilan per Bulan</label>
                    <div class="input-group">
                        <span class="input-group-text">Rp</span>
                        <input type="number" class="form-control @error('penghasilan_per_bulan') is-invalid @enderror" 
                               name="penghasilan_per_bulan" value="{{ old('penghasilan_per_bulan', $anggota->penghasilan_per_bulan) }}" 
                               placeholder="5000000" min="0">
                        @error('penghasilan_per_bulan')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="form-text">Kosongkan jika tidak ingin diisi</div>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Status Muzaki/Mustahiq</label>
                    <select class="form-select @error('muzaki_mustahiq') is-invalid @enderror" 
                            name="muzaki_mustahiq">
                        <option value="">Pilih Status</option>
                        <option value="Muzaki" {{ old('muzaki_mustahiq', $anggota->muzaki_mustahiq) == 'Muzaki' ? 'selected' : '' }}>Muzaki</option>
                        <option value="Mustahiq" {{ old('muzaki_mustahiq', $anggota->muzaki_mustahiq) == 'Mustahiq' ? 'selected' : '' }}>Mustahiq</option>
                    </select>
                    @error('muzaki_mustahiq')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Nomor Identitas Pasangan</label>
                    <input type="text" class="form-control @error('nomor_identitas_pasangan') is-invalid @enderror" 
                           name="nomor_identitas_pasangan" value="{{ old('nomor_identitas_pasangan', $anggota->nomor_identitas_pasangan) }}" 
                           placeholder="NIA Pasangan (jika ada)">
                    @error('nomor_identitas_pasangan')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
        </div>
    </div>

    <!-- Data Tambahan -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-white">
                <i class="fas fa-file-alt me-2"></i>Data Tambahan
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-8 mb-3">
                    <label class="form-label">Catatan/Profil</label>
                    <textarea class="form-control @error('catatan_profil') is-invalid @enderror" 
                              name="catatan_profil" rows="3" 
                              placeholder="Catatan tambahan tentang anggota...">{{ old('catatan_profil', $anggota->catatan_profil) }}</textarea>
                    @error('catatan_profil')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Foto Profil</label>
                    
                    <!-- Current photo -->
                    @if($anggota->foto)
                        <div class="mb-2">
                            <img src="{{ Storage::url($anggota->foto) }}?v={{ $anggota->updated_at ? $anggota->updated_at->timestamp : time() }}" 
                                 alt="Foto {{ $anggota->nama_lengkap }}"
                                 style="max-width: 120px; max-height: 120px; border-radius: 8px; border: 2px solid #ddd;">
                            <div class="form-text">Foto saat ini</div>
                        </div>
                    @endif
                    
                    <input type="file" class="form-control @error('foto') is-invalid @enderror" 
                           name="foto" accept="image/*">
                    @error('foto')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                    <div class="form-text">
                        Format: JPG, PNG. Maksimal 4MB.
                        @if($anggota->foto) Biarkan kosong jika tidak ingin mengubah foto. @endif
                    </div>
                    
                    <!-- Preview foto baru -->
                    <div id="imagePreview" class="mt-2" style="display: none;">
                        <img id="preview" src="#" alt="Preview" 
                             style="max-width: 150px; max-height: 150px; border-radius: 8px; border: 2px solid #ddd;">
                        <div class="form-text">Preview foto baru</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Form Actions -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow">
                <div class="card-body text-center">
                    <button type="submit" class="btn btn-primary btn-lg me-3">
                        <i class="fas fa-save me-2"></i> Update Data Anggota
                    </button>
                    <a href="{{ $anggota->show_url }}" class="btn btn-outline-info btn-lg me-3">
                        <i class="fas fa-eye me-2"></i> Lihat Detail
                    </a>
                    <a href="{{ route('anggota.index') }}" class="btn btn-outline-secondary btn-lg">
                        <i class="fas fa-times me-2"></i> Batal
                    </a>
                </div>
            </div>
        </div>
    </div>
</form>
</div>
@endsection

@push('styles')
<style>
.required::after {
    content: " *";
    color: #F0833A;
    font-weight: bold;
}

.form-control:focus, .form-select:focus {
    border-color: #F0833A;
    box-shadow: 0 0 0 0.2rem rgba(240, 131, 58, 0.25);
}

.input-group-text {
    background-color: #fff;
    border-color: #ddd;
    color: #F0833A;
    font-weight: 600;
}

.card {
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
}

.alert-info {
    background-color: rgba(240, 131, 58, 0.1);
    border-color: #F0833A;
    color: #E67E22;
}
</style>
@endpush

@push('scripts')
<script>
function toggleKeahlianLainnya() {
    const checkbox = document.getElementById('keahlian_lainnya_check');
    const textarea = document.getElementById('keahlian_lainnya_textarea');
    
    if (checkbox.checked) {
        textarea.style.display = 'block';
    } else {
        textarea.style.display = 'none';
        // Clear textarea when unchecked
        textarea.querySelector('textarea').value = '';
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Check if there's existing keahlian_lainnya data
    const keahlianLainnyaValue = '{{ $anggota->keahlian_lainnya }}';
    if (keahlianLainnyaValue) {
        document.getElementById('keahlian_lainnya_check').checked = true;
        toggleKeahlianLainnya();
    }
});

// Preview foto sebelum upload
document.querySelector('input[name="foto"]').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('preview').src = e.target.result;
            document.getElementById('imagePreview').style.display = 'block';
        }
        reader.readAsDataURL(file);
    } else {
        document.getElementById('imagePreview').style.display = 'none';
    }
});

// Konfirmasi sebelum update
document.querySelector('form').addEventListener('submit', function(e) {
    if (!confirm('Apakah Anda yakin ingin mengupdate data anggota ini?')) {
        e.preventDefault();
    }
});

// Track changes
let formChanged = false;
document.querySelectorAll('input, select, textarea').forEach(field => {
    const originalValue = field.value;
    field.addEventListener('input', function() {
        if (this.value !== originalValue) {
            formChanged = true;
        }
    });
});

// Warn before leaving if there are unsaved changes
window.addEventListener('beforeunload', function(e) {
    if (formChanged) {
        e.preventDefault();
        e.returnValue = 'Ada perubahan yang belum disimpan. Yakin ingin meninggalkan halaman?';
    }
});

// Mark form as submitted to avoid warning
document.querySelector('form').addEventListener('submit', function() {
    formChanged = false;
});

// Auto-save draft (optional - could save to localStorage)
function saveDraft() {
    const formData = new FormData(document.querySelector('form'));
    const draftData = {};
    for (let [key, value] of formData.entries()) {
        if (key !== 'foto') { // Don't save file uploads
            draftData[key] = value;
        }
    }
    localStorage.setItem('anggota_edit_draft_{{ $anggota->id }}', JSON.stringify(draftData));
}

// Save draft every 30 seconds
setInterval(saveDraft, 30000);

// Load draft on page load
document.addEventListener('DOMContentLoaded', function() {
    const draft = localStorage.getItem('anggota_edit_draft_{{ $anggota->id }}');
    if (draft && confirm('Ditemukan draft yang belum tersimpan. Muat draft tersebut?')) {
        const draftData = JSON.parse(draft);
        for (let [key, value] of Object.entries(draftData)) {
            const field = document.querySelector(`[name="${key}"]`);
            if (field && field.type !== 'file') {
                field.value = value;
                formChanged = true;
            }
        }
    }
});

// Clear draft after successful submission
window.addEventListener('beforeunload', function() {
    if (!formChanged) {
        localStorage.removeItem('anggota_edit_draft_{{ $anggota->id }}');
    }
});

// Aktivitas functions
function addAktivitas() {
    const container = document.getElementById('aktivitas-container');
    const newItem = document.createElement('div');
    newItem.className = 'aktivitas-item mb-2';
    newItem.innerHTML = `
        <div class="input-group">
            <input type="text" class="form-control" name="aktivitas[]" 
                   placeholder="Contoh: Pengurus Masjid Al-Ikhlas, Ketua Majelis Taklim, dll">
            <button type="button" class="btn btn-outline-danger" onclick="removeAktivitas(this)">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    `;
    container.appendChild(newItem);
}

function removeAktivitas(button) {
    const container = document.getElementById('aktivitas-container');
    if (container.children.length > 1) {
        button.closest('.aktivitas-item').remove();
    }
}

function toggleLainnyaInput() {
    const checkbox = document.getElementById('aktivitas_lainnya');
    const inputDiv = document.getElementById('lainnya-input');
    const textarea = document.getElementById('aktivitas_luar_lainnya_text');
    
    if (checkbox.checked) {
        inputDiv.style.display = 'block';
        textarea.focus();
    } else {
        inputDiv.style.display = 'none';
        textarea.value = '';
    }
}

// Cascading dropdown functions
function loadDpcByDpd() {
    const dpdId = document.getElementById('dpd_id').value;
    const dpcSelect = document.getElementById('dpc_id');
    const upaSelect = document.getElementById('upa_id');
    
    console.log('Loading DPC for DPD ID:', dpdId);
    
    // Clear DPC and UPA dropdowns
    dpcSelect.innerHTML = '<option value="">Pilih DPC</option>';
    upaSelect.innerHTML = '<option value="">Pilih UPA</option>';
    
    if (dpdId) {
        const url = `/api/anggota/dpc-by-dpd?dpd_id=${dpdId}`;
        console.log('Fetching URL:', url);
        
        fetch(url)
            .then(response => {
                console.log('Response status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('DPC data received:', data);
                data.forEach(dpc => {
                    const option = document.createElement('option');
                    option.value = dpc.dpc_id;
                    option.textContent = dpc.nama_dpc;
                    dpcSelect.appendChild(option);
                });
                console.log('DPC options added:', dpcSelect.children.length - 1);
            })
            .catch(error => {
                console.error('Error loading DPC:', error);
            });
    }
}

function loadUpaByDpc() {
    const dpcId = document.getElementById('dpc_id').value;
    const upaSelect = document.getElementById('upa_id');
    
    // Clear UPA dropdown
    upaSelect.innerHTML = '<option value="">Pilih UPA</option>';
    
    if (dpcId) {
        fetch(`/api/anggota/upa-by-dpc?dpc_id=${dpcId}`)
            .then(response => response.json())
            .then(data => {
                data.forEach(upa => {
                    const option = document.createElement('option');
                    option.value = upa.upa_id;
                    option.textContent = upa.nama_upa;
                    upaSelect.appendChild(option);
                });
            })
            .catch(error => {
                console.error('Error loading UPA:', error);
            });
    }
}

// Set default DPD to Jakarta Timur on page load (only if no existing value)
document.addEventListener('DOMContentLoaded', function() {
    const dpdSelect = document.getElementById('dpd_id');
    
    // Only set default if no value is already selected
    if (!dpdSelect.value) {
        // Find Jakarta Timur option
        for (let i = 0; i < dpdSelect.options.length; i++) {
            if (dpdSelect.options[i].textContent.includes('Jakarta Timur')) {
                dpdSelect.value = dpdSelect.options[i].value;
                console.log('Set default DPD to Jakarta Timur with ID:', dpdSelect.options[i].value);
                
                // Trigger DPC loading
                loadDpcByDpd();
                break;
            }
        }
    }
});
</script>
@endpush