<?= $this->extend('backend/layouts/main') ?>

<?= $this->section('main') ?>

<div class="bg-white p-8 rounded-lg shadow-md max-w-4xl mx-auto">
    <h3 class="text-2xl font-semibold mb-6 border-b pb-4"><?= lang('Admin/Transactions.editParticipantTitle', [esc($participant->name)]) ?></h3>
    
    <?= $this->include('backend/layouts/_notifications') ?>

    <?= form_open(route_to('admin.participants.update', $participant->id)) ?>
        <?= csrf_field() ?>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">

            <!-- Paket (Read-only) -->
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700">Package</label>
                <input type="text" value="<?= esc($package->name) ?> (Rp <?= number_format($package->price) ?>)" class="mt-1 block w-full bg-gray-200 border-gray-300 rounded-md p-2 cursor-not-allowed" readonly>
                <p class="mt-1 text-xs text-gray-500">Package cannot be changed.</p>
            </div>
            
            <hr class="md:col-span-2">

            <!-- Data yang Bisa Diedit -->
            <div>
                <label for="name" class="block text-sm font-medium text-gray-700">Full Name</label>
                <input type="text" name="name" id="name" value="<?= old('name', $participant->name) ?>" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2" required>
            </div>
            <div>
                <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
                <input type="email" name="email" id="email" value="<?= old('email', $participant->email) ?>" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2" required>
            </div>
            <div>
                <label for="phone_number" class="block text-sm font-medium text-gray-700">Phone</label>
                <input type="tel" name="phone_number" id="phone_number" value="<?= old('phone_number', $participant->phone_number ?? '+') ?>" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2" required>
            </div>
             <div>
                <label for="gender" class="block text-sm font-medium text-gray-700">Gender</label>
                <select name="gender" id="gender" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2">
                    <option value="Male" <?= (old('gender', $participant->gender) == 'Male') ? 'selected' : '' ?>>Male</option>
                    <option value="Female" <?= (old('gender', $participant->gender) == 'Female') ? 'selected' : '' ?>>Female</option>
                </select>
            </div>
            
            <?php
                $selectedChurchId = old('church_id', $participant->church_id ?? 'other');
                if ($selectedChurchId === null) {
                    $selectedChurchId = 'other';
                }
            ?>
             <div class="md:col-span-2">
                <label for="church_id" class="block text-sm font-medium text-gray-700">Church</label>
                <select name="church_id" id="church_id" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2">
                    <option value="">-- Select Church --</option>
                     <?php foreach($churches as $church): ?>
                        <option value="<?= $church->id ?>" <?= ($selectedChurchId == $church->id) ? 'selected' : '' ?>><?= esc($church->name) ?></option>
                    <?php endforeach; ?>
                    <option value="other" <?= ($selectedChurchId === 'other') ? 'selected' : '' ?>>Other Church</option>
                </select>
            </div>
            <div id="other_church_container" class="md:col-span-2 <?= ($selectedChurchId === 'other') ? '' : 'hidden' ?>">
                <label for="church_name" class="block text-sm font-medium text-gray-700">Other Church Name</label>
                <input type="text" name="church_name" id="church_name" value="<?= old('church_name', $participant->church_name) ?>" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2">
            </div>

            <div>
                <label for="kta_number" class="block text-sm font-medium text-gray-700">KTA Number</label>
                <input type="text" name="kta_number" id="kta_number" value="<?= old('kta_number', $participant->kta_number) ?>" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2">
            </div>
             <div>
                <label for="birth_date" class="block text-sm font-medium text-gray-700">Date of Birth</label>
                <input type="date" name="birth_date" id="birth_date" value="<?= old('birth_date', $participant->birth_date) ?>" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2">
            </div>

            <!-- Custom Fields -->
            <?php if(!empty($customFields)): ?>
                <hr class="md:col-span-2 my-4">
                <h4 class="md:col-span-2 text-lg font-semibold text-gray-800">Additional Information</h4>
                <?php foreach ($customFields as $field): ?>
                    <div class="md:col-span-2">
                         <label for="custom_<?= $field->id ?>" class="block text-sm font-medium text-gray-700"><?= esc($field->label) . ($field->is_required ? ' <span class="text-red-500">*</span>' : '') ?></label>
                         <?php 
                            $currentValue = old('custom.'.$field->id, $participantValues[$field->id] ?? null);
                            $isRequiredAttr = $field->is_required ? 'required' : '';
                         ?>
                         <?php if ($field->type === 'select'): ?>
                            <select name="custom[<?= $field->id ?>]<?= $field->is_multiple ? '[]' : '' ?>" id="custom_<?= $field->id ?>" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2" <?= $field->is_multiple ? 'multiple' : '' ?> <?= $isRequiredAttr ?>>
                                <?php
                                    $selectedValues = [];
                                    if (is_array($currentValue)) {
                                        $selectedValues = $currentValue;
                                    } elseif ($currentValue !== null) {
                                        $decoded = json_decode($currentValue, true);
                                        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                                            $selectedValues = $decoded;
                                        } else {
                                            $selectedValues = [$currentValue];
                                        }
                                    }
                                ?>
                                <?php if (!$field->is_multiple): ?><option value="">-- Select --</option><?php endif; ?>
                                <?php if (is_array($field->options)): foreach ($field->options as $option): ?>
                                    <option value="<?= esc($option) ?>" <?= in_array($option, $selectedValues) ? 'selected' : '' ?>><?= esc($option) ?></option>
                                <?php endforeach; endif; ?>
                            </select>
                         <?php else: ?>
                            <input type="<?= $field->type ?>" name="custom[<?= $field->id ?>]" id="custom_<?= $field->id ?>" value="<?= esc($currentValue) ?>" class="mt-1 block w-full bg-gray-50 border border-gray-300 rounded-md p-2" <?= $isRequiredAttr ?>>
                         <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
            
        </div>

        <div class="mt-8 flex justify-end gap-4">
            <a href="<?= route_to('admin.transactions.show', $transaction->uuid) ?>" class="bg-gray-200 text-gray-800 px-4 py-2 rounded-md hover:bg-gray-300">Cancel</a>
            <button type="submit" class="bg-indigo-600 text-white font-bold px-4 py-2 rounded-md hover:bg-indigo-700"><?= lang('Admin/Transactions.btnUpdateParticipant') ?></button>
        </div>
    <?= form_close() ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Logika untuk menampilkan/menyembunyikan input "Other Church"
    const churchSelect = document.getElementById('church_id');
    const otherChurchContainer = document.getElementById('other_church_container');

    function toggleOtherChurch() {
        if (churchSelect.value === 'other') {
            otherChurchContainer.classList.remove('hidden');
        } else {
            otherChurchContainer.classList.add('hidden');
        }
    }
    churchSelect.addEventListener('change', toggleOtherChurch);


    // --- LOGIKA BARU UNTUK NOMOR TELEPON ---
    const phoneInput = document.getElementById('phone_number');

    function formatPhoneNumber() {
        // Hapus semua karakter yang bukan angka atau '+'
        let cleaned = ('+' + this.value).replace(/[^\d+]/g, '');

        // Pastikan hanya ada satu '+' di awal
        if (cleaned.lastIndexOf('+') > 0) {
            cleaned = '+' + cleaned.replace(/\+/g, '');
        }
        
        // Jika hanya ada '+', biarkan
        if (cleaned.length === 1 && cleaned[0] === '+') {
            this.value = cleaned;
            return;
        }
        
        // Jika tidak diawali '+', tambahkan
        if (cleaned.length > 0 && cleaned[0] !== '+') {
            cleaned = '+' + cleaned;
        }

        this.value = cleaned;
    }
    
    // Tambahkan '+' saat pengguna pertama kali fokus jika field kosong
    phoneInput.addEventListener('focus', function() {
        if (this.value === '') {
            this.value = '+';
        }
    });

    // Jalankan format setiap kali pengguna mengetik
    phoneInput.addEventListener('input', formatPhoneNumber);
});
</script>

<?= $this->endSection() ?>