

<?php $__env->startSection('title', 'Edit family · FamilyTree'); ?>
<?php $__env->startSection('page-title', 'Edit family space'); ?>

<?php $__env->startSection('content'); ?>
    <section class="space-y-6">
        <div class="rounded-2xl border border-slate-100 bg-white p-6">
            <form method="POST" action="<?php echo e(route('families.update', $family)); ?>" class="space-y-5">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PATCH'); ?>

                <div>
                    <label for="name" class="block text-sm text-slate-600 mb-1">Family name</label>
                    <input id="name" name="name" type="text" value="<?php echo e(old('name', $family->name)); ?>" required
                           class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary" />
                    <?php $__errorArgs = ['name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <div>
                    <label for="description" class="block text-sm text-slate-600 mb-1">Description (optional)</label>
                    <textarea id="description" name="description" rows="3"
                              class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary"><?php echo e(old('description', $family->description)); ?></textarea>
                    <?php $__errorArgs = ['description'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <div>
                    <label class="block text-sm text-slate-600 mb-1">Cover image</label>
                    <?php ($currentCover = data_get($family->settings, 'cover_photo')); ?>
                    <input type="hidden" name="cover_photo" id="cover_photo" value="<?php echo e(old('cover_photo', $currentCover)); ?>">
                    <div class="rounded-xl border border-dashed border-slate-300 bg-slate-50 p-3 flex items-center gap-3">
                        <img id="coverPreview" src="<?php echo e(old('cover_photo', $currentCover)); ?>" alt="Cover preview" class="h-16 w-28 object-cover rounded-lg <?php echo e(old('cover_photo', $currentCover) ? '' : 'hidden'); ?>">
                        <div class="flex-1">
                            <p class="text-xs text-slate-500">Select an image to represent your family space.</p>
                            <div class="mt-2">
                                <label class="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-white border border-slate-200 text-sm cursor-pointer hover:bg-slate-50">
                                    <span class="material-symbols-rounded text-base">image</span>
                                    <span>Choose image</span>
                                    <input id="coverFile" type="file" accept="image/*" class="hidden">
                                </label>
                            </div>
                        </div>
                    </div>
                    <?php $__errorArgs = ['cover_photo'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <?php ($loc = (array) ($family->settings['location'] ?? [])); ?>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label for="country" class="block text-sm text-slate-600 mb-1">Country</label>
                        <select id="country" name="country" required class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary"></select>
                        <?php $__errorArgs = ['country'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div>
                        <label for="region" class="block text-sm text-slate-600 mb-1">Region</label>
                        <select id="region" name="region" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary"></select>
                        <?php $__errorArgs = ['region'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div>
                        <label for="district" class="block text-sm text-slate-600 mb-1">District / Metropolitan</label>
                        <select id="district" name="district" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary"></select>
                        <?php $__errorArgs = ['district'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div>
                        <label for="town" class="block text-sm text-slate-600 mb-1">Closest known town</label>
                        <input id="town" name="town" list="townOptions" value="<?php echo e(old('town', $loc['town'] ?? '')); ?>" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary" />
                        <datalist id="townOptions"></datalist>
                        <?php $__errorArgs = ['town'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label for="ethnic_group_id" class="block text-sm text-slate-600 mb-1">Ethnic group</label>
                        <select id="ethnic_group_id" name="ethnic_group_id" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary"></select>
                        <?php $__errorArgs = ['ethnic_group_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div>
                        <label for="clan_id" class="block text-sm text-slate-600 mb-1">Clan / Lineage</label>
                        <select id="clan_id" name="clan_id" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary"></select>
                        <?php $__errorArgs = ['clan_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div class="sm:col-span-2">
                        <label for="language" class="block text-sm text-slate-600 mb-1">Shared language / dialect</label>
                        <?php ($lang = data_get($family->settings, 'culture.language')); ?>
                        <input id="language" name="language" type="text" value="<?php echo e(old('language', $lang)); ?>" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary" />
                        <?php $__errorArgs = ['language'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>

                <div>
                    <label for="head_person_id" class="block text-sm text-slate-600 mb-1">Head of family</label>
                    <select id="head_person_id" name="head_person_id" class="w-full rounded-xl border-slate-200 focus:border-primary focus:ring-primary">
                        <option value="">— Select member —</option>
                        <?php $__currentLoopData = $members; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($m['id']); ?>" <?php if((int) old('head_person_id', (int) $family->head_person_id) === (int) $m['id']): echo 'selected'; endif; ?>><?php echo e($m['name']); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    <p class="text-xs text-slate-500 mt-1">Only members of this family can be selected.</p>
                    <?php $__errorArgs = ['head_person_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <p class="mt-1 text-xs text-rose-600"><?php echo e($message); ?></p>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                <button type="submit" class="w-full inline-flex items-center justify-center gap-2 bg-primary text-white px-4 py-2.5 rounded-xl">
                    <span class="material-symbols-rounded">save</span>
                    Update family
                </button>
            </form>
        </div>
    </section>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('head'); ?>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
    const LOCATIONS = <?php echo json_encode($locations ?? [], 15, 512) ?>;
    const DEFAULT_COUNTRY = <?php echo json_encode($defaultCountry ?? null, 15, 512) ?>;

    const countryEl = document.getElementById('country');
    const regionEl = document.getElementById('region');
    const districtEl = document.getElementById('district');
    const townEl = document.getElementById('town');
    const townListEl = document.getElementById('townOptions');
    const groupEl = document.getElementById('ethnic_group_id');
    const clanEl = document.getElementById('clan_id');
    const languageEl = document.getElementById('language');
    const coverHidden = document.getElementById('cover_photo');
    const coverFile = document.getElementById('coverFile');
    const coverPreview = document.getElementById('coverPreview');

    const csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    function clearOptions(sel){ sel.innerHTML=''; }
    function addOption(sel, value, text){ const opt=document.createElement('option'); opt.value=value; opt.textContent=text ?? value; sel.appendChild(opt); }

    function populateCountries(){
        clearOptions(countryEl);
        const entries = Object.entries(LOCATIONS).map(([code, data]) => ({code, name: data.name || code}));
        entries.forEach(({code, name}) => addOption(countryEl, code, `${name} (${code})`));
        const preset = <?php echo json_encode(old('country', $loc['country'] ?? null), 512) ?> || DEFAULT_COUNTRY || (entries[0]?.code ?? '');
        if (preset) countryEl.value = preset;
        populateRegions();
        populateGroups();
    }

    function populateRegions(){
        clearOptions(regionEl); clearOptions(districtEl); townListEl.innerHTML='';
        const code = countryEl.value; const data = LOCATIONS[code];
        if (!data || !data.regions) { regionEl.disabled = true; districtEl.disabled = true; return; }
        const regions = Object.keys(data.regions);
        regions.forEach(r => addOption(regionEl, r, r));
        regionEl.disabled = regions.length === 0;
        const preset = <?php echo json_encode(old('region', $loc['region'] ?? null), 512) ?>;
        if (preset && regions.includes(preset)) regionEl.value = preset;
        populateDistricts();
    }

    function populateDistricts(){
        clearOptions(districtEl); townListEl.innerHTML='';
        const code = countryEl.value; const region = regionEl.value;
        const districts = Object.keys(LOCATIONS[code]?.regions?.[region]?.districts || {});
        districts.forEach(d => addOption(districtEl, d, d));
        districtEl.disabled = districts.length === 0;
        const preset = <?php echo json_encode(old('district', $loc['district'] ?? null), 512) ?>;
        if (preset && districts.includes(preset)) districtEl.value = preset;
        populateTowns();
    }

    function populateTowns(){
        townListEl.innerHTML='';
        const code = countryEl.value; const region = regionEl.value; const district = districtEl.value;
        const towns = LOCATIONS[code]?.regions?.[region]?.districts?.[district] || [];
        towns.forEach(t => { const opt=document.createElement('option'); opt.value=t; townListEl.appendChild(opt); });
        const preset = <?php echo json_encode(old('town', $loc['town'] ?? null), 512) ?>;
        if (preset && !townEl.value) townEl.value = preset;
    }

    async function populateGroups(){
        groupEl.innerHTML=''; clanEl.innerHTML=''; clanEl.disabled = true;
        const code = countryEl.value; if (!code) { groupEl.disabled = true; return; }
        try {
            const res = await fetch(`<?php echo e(url('/ethnic/groups')); ?>?country=${encodeURIComponent(code)}`, { headers: { 'X-Requested-With': 'XMLHttpRequest' }});
            const data = await res.json();
            (data || []).forEach(g => addOption(groupEl, g.id, g.name));
            groupEl.disabled = (data || []).length === 0;
            const preset = <?php echo json_encode(old('ethnic_group_id', (int) $family->ethnic_group_id), 512) ?>;
            if (preset) groupEl.value = preset;
            await populateClans();
            const selected = (data || []).find(g => String(g.id) === String(groupEl.value));
            if (selected && languageEl && !languageEl.value && selected.languages) { languageEl.value = selected.languages; }
        } catch {}
    }

    async function populateClans(){
        clanEl.innerHTML='';
        const gid = groupEl.value; if (!gid) { clanEl.disabled = true; return; }
        try {
            const res = await fetch(`<?php echo e(url('/ethnic/clans')); ?>?ethnic_group_id=${encodeURIComponent(gid)}`, { headers: { 'X-Requested-With': 'XMLHttpRequest' }});
            const data = await res.json();
            (data || []).forEach(c => addOption(clanEl, c.id, c.name));
            clanEl.disabled = (data || []).length === 0;
            const preset = <?php echo json_encode(old('clan_id', (int) $family->clan_id), 512) ?>;
            if (preset) clanEl.value = preset;
        } catch {}
    }

    countryEl.addEventListener('change', function(){ populateRegions(); populateGroups(); });
    regionEl.addEventListener('change', populateDistricts);
    districtEl.addEventListener('change', populateTowns);
    groupEl.addEventListener('change', function(){ populateClans(); if (languageEl && !languageEl.value) { /* prefill handled */ } });

    document.addEventListener('DOMContentLoaded', populateCountries);

    if (coverFile) {
        coverFile.addEventListener('change', function(){
            if (!coverFile.files || !coverFile.files.length) return;
            const fd = new FormData();
            fd.append('files[]', coverFile.files[0]);
            fetch(`<?php echo e(url('/uploads')); ?>`, {
                method: 'POST', headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }, credentials: 'same-origin', body: fd
            })
            .then(r => { if (!r.ok) throw new Error('Upload failed'); return r.json(); })
            .then(data => { const f = (data && data.files && data.files[0]) ? data.files[0] : null; if (f && f.url) { coverHidden.value = f.url; if (coverPreview) { coverPreview.src = f.url; coverPreview.classList.remove('hidden'); } } })
            .catch(() => alert('Unable to upload image. Please try again.'))
            .finally(() => { coverFile.value = ''; });
        });
    }
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\familytree\api\resources\views/families/edit.blade.php ENDPATH**/ ?>