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

<?= $this->section('pageTitle') ?><?= lang('Transaction.form_title', [esc($event->name)]) ?><?= $this->endSection() ?>

<?= $this->section('mainContent') ?>
<div class="container mx-auto px-4 py-8" 
     x-data="transactionForm(<?= htmlspecialchars(json_encode($packages)) ?>, <?= htmlspecialchars(json_encode($paymentMethods)) ?>, <?= htmlspecialchars(json_encode($churches)) ?>)">

    <div class="bg-white rounded-lg shadow-md mb-8 overflow-hidden">
        <img src="<?= $event->thumbnail ?? 'https://via.placeholder.com/1200x400?text=Event+Banner' ?>" alt="<?= esc($event->name) ?>" class="w-full h-48 md:h-64 object-cover">
        <div class="p-6">
            <h1 class="text-4xl font-bold text-gray-800"><?= esc($event->name) ?></h1>
            <?php if(!empty($event->description)): ?>
                <div class="mt-4 text-gray-600 prose max-w-none">
                    <?= nl2br($event->description) ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <form method="POST" action="<?= route_to('transaction.create') ?>" @submit="isSubmitting = true">
    <?= csrf_field() ?>
    <input type="hidden" name="event_id" value="<?= $event->id ?>">
    <!-- Kirim kode promo yang valid ke controller -->
    <input type="hidden" name="promo_code" :value="appliedPromo ? appliedPromo.code : ''">

    <div class="lg:grid lg:grid-cols-3 lg:gap-8">
        <!-- Kolom Kiri: Form Peserta -->
        <div class="lg:col-span-2 space-y-6">
            <div class="bg-white p-6 sm:p-8 rounded-lg shadow-md">
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center border-b border-gray-200 pb-6 mb-6">
                    <div>
                        <h2 class="text-3xl font-bold text-gray-800"><?= lang('Transaction.step1_title') ?></h2>
                        <p class="text-gray-500 mt-1"><?= lang('Transaction.max_participant_note') ?></p>
                    </div>
                    <button type="button" @click="addParticipant()" class="mt-4 sm:mt-0 flex-shrink-0 bg-indigo-600 text-white px-4 py-2 text-sm font-semibold rounded-md hover:bg-indigo-700 disabled:bg-gray-400" :disabled="participants.length >= 5">
                        <?= lang('Transaction.button_add_participant') ?>
                    </button>
                </div>

                <div class="space-y-10">
                    <template x-for="(participant, index) in participants" :key="participant.id">
                        <div class="border-t-4 border-indigo-100 pt-6">
                            <div class="flex justify-between items-center mb-6">
                                <h3 class="text-2xl font-semibold text-indigo-700" x-text="`<?= lang('Transaction.participant_label', ['${index + 1}']) ?>`"></h3>
                                <button type="button" @click="removeParticipant(index)" x-show="participants.length > 1" class="text-sm text-red-500 hover:text-red-700 font-medium"><?= lang('Transaction.button_remove') ?></button>
                            </div>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div class="md:col-span-2">
                                    <label :for="`package_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.participant_package_label') ?> <span class="text-red-500">*</span></label>
                                    <select :name="`participants[${index}][package_id]`" :id="`package_${participant.id}`" x-model="participant.package_id" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg w-full p-2.5" required>
                                        <option value=""><?= lang('Transaction.option_choose_package') ?></option>
                                        <?php foreach($packages as $pkg): ?><option value="<?= $pkg->id ?>"><?= esc($pkg->name) ?> (IDR <?= number_format($pkg->price) ?>)</option><?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div><label :for="`name_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_fullname') ?> <span class="text-red-500">*</span></label><input :name="`participants[${index}][name]`" :id="`name_${participant.id}`" type="text" x-model="participant.name" class="bg-gray-50 border border-gray-300 w-full p-2.5" placeholder="<?= lang('Transaction.placeholder_fullname') ?>" required></div>
                                <div><label :for="`phone_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_phone') ?> <span class="text-red-500">*</span></label><input :name="`participants[${index}][phone_number]`" :id="`phone_${participant.id}`" type="tel" x-model="participant.phone_number" class="bg-gray-50 border border-gray-300 w-full p-2.5" placeholder="<?= lang('Transaction.placeholder_phone') ?>" required></div>
                                <div><label :for="`email_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_email') ?> <span class="text-red-500">*</span></label><input :name="`participants[${index}][email]`" :id="`email_${participant.id}`" type="email" x-model="participant.email" class="bg-gray-50 border border-gray-300 w-full p-2.5" placeholder="<?= lang('Transaction.placeholder_email') ?>" required></div>
                                <div><label :for="`gender_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_gender') ?> <span class="text-red-500">*</span></label><select :name="`participants[${index}][gender]`" :id="`gender_${participant.id}`" x-model="participant.gender" class="bg-gray-50 border border-gray-300 w-full p-2.5" required><option value="Male"><?= lang('Transaction.option_male') ?></option><option value="Female"><?= lang('Transaction.option_female') ?></option></select></div>
                                
                                <div class="md:col-span-2">
                                    <label :for="`church_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_church') ?> <span class="text-red-500">*</span></label>
                                    <select :name="`participants[${index}][church_id]`" :id="`church_${participant.id}`" x-model="participant.church_id" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg w-full p-2.5" required>
                                        <option value=""><?= lang('Transaction.option_choose_church') ?></option>
                                        <?php foreach($churches as $church): ?>
                                            <option value="<?= $church->id ?>"><?= esc($church->name) ?></option>
                                        <?php endforeach; ?>
                                        <option value="other"><?= lang('Transaction.option_other_church') ?></option>
                                    </select>
                                </div>
                                
                                <template x-if="participant.church_id === 'other'">
                                    <div class="md:col-span-2">
                                        <label :for="`church_name_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_other_church_name') ?> <span class="text-red-500">*</span></label>
                                        <input :name="`participants[${index}][church_name]`" :id="`church_name_${participant.id}`" type="text" x-model="participant.church_name" class="bg-gray-50 border border-gray-300 w-full p-2.5" placeholder="<?= lang('Transaction.placeholder_other_church') ?>" required>
                                    </div>
                                </template>
                                
                                <template x-if="isKtaRequired(participant.package_id)"><div class="md:col-span-2 bg-yellow-50 border-l-4 border-yellow-400 p-4 rounded-r-lg"><p class="text-sm text-yellow-800 font-semibold"><?= lang('Transaction.kta_required_note') ?></p></div></template>
                                <div><label :for="`kta_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_kta') ?></label><input :name="`participants[${index}][kta_number]`" :id="`kta_${participant.id}`" type="text" x-model="participant.kta_number" :required="isKtaRequired(participant.package_id)" class="bg-gray-50 border border-gray-300 w-full p-2.5" placeholder="<?= lang('Transaction.placeholder_kta') ?>"></div>
                                <div><label :for="`birthdate_${participant.id}`" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_birthdate') ?></label><input :name="`participants[${index}][birth_date]`" :id="`birthdate_${participant.id}`" type="date" x-model="participant.birth_date" class="bg-gray-50 border border-gray-300 w-full p-2.5"></div>
                                
                                <?php if(!empty($customFields)): ?>
                                    <div class="md:col-span-2 mt-4"><h4 class="text-lg font-semibold border-b border-gray-200 pb-2"><?= lang('Transaction.additional_info') ?></h4></div>
                                    <?php foreach ($customFields as $field): ?>
                                        <div class="md:col-span-2">
                                            <?php
                                                $label = esc($field->label) . ($field->is_required ? ' <span class="text-red-500">*</span>' : '');
                                                $isRequiredAttr = $field->is_required ? 'required' : '';
                                                $fieldId = $field->id;
                                            ?>
                                            <label :for="`custom_${participant.id}_<?= $fieldId ?>`" class="block mb-2 text-sm font-medium text-gray-900"><?= $label ?></label>
                                            <?php if ($field->type === 'select'): ?>
                                                <?php $isMultiple = $field->is_multiple ? 'true' : 'false'; ?>
                                                <select x-model="participant.custom['<?= $fieldId ?>']" :name="`participants[${index}][custom][<?= $fieldId ?>]${<?= $isMultiple ?> ? '[]' : ''}`" :id="`custom_${participant.id}_<?= $fieldId ?>`" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg w-full p-2.5" <?= $field->is_multiple ? 'multiple' : '' ?> <?= $isRequiredAttr ?>>
                                                    <?php if (!$field->is_multiple): ?><option value="">-- Select an option --</option><?php endif; ?>
                                                    <?php if (is_array($field->options)): ?><?php foreach ($field->options as $option): ?><option value="<?= esc($option) ?>"><?= esc($option) ?></option><?php endforeach; ?><?php endif; ?>
                                                </select>
                                                <?php if ($field->is_multiple): ?><p class="mt-1 text-xs text-gray-500">You can select multiple options (hold Ctrl/Cmd and click).</p><?php endif; ?>
                                            <?php else: ?>
                                                <input x-model="participant.custom['<?= $fieldId ?>']" :name="`participants[${index}][custom][<?= $fieldId ?>]`" :id="`custom_${participant.id}_<?= $fieldId ?>`" type="<?= $field->type ?>" class="bg-gray-50 border border-gray-300 w-full p-2.5" <?= $isRequiredAttr ?>>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Kolom Kanan: Ringkasan & Pembayaran (Sticky) -->
        <div class="lg:col-span-1 mt-8 lg:mt-0">
            <div class="sticky top-24">
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <h2 class="text-2xl font-bold mb-4"><?= lang('Transaction.step2_title') ?></h2>
                    <?= $this->include('frontend/components/_notifications') ?>

                    <div class="mt-4">
                        <label for="promo_code_input" class="block text-sm font-medium text-gray-700"><?= lang('Transaction.field_promo_code') ?></label>
                        <div class="mt-1 flex rounded-md shadow-sm">
                            <input type="text" id="promo_code_input" x-model="promoCode" @keydown.enter.prevent="applyPromo()" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-none rounded-l-md focus:ring-indigo-600 focus:border-indigo-600 block w-full p-2.5 uppercase" placeholder="<?= lang('Transaction.placeholder_promo_code') ?>" :disabled="appliedPromo" :class="{'bg-gray-100 cursor-not-allowed': appliedPromo}">
                            
                            <template x-if="!appliedPromo">
                                <button type="button" @click="applyPromo()" class="inline-flex items-center px-3 rounded-r-md border border-l-0 border-gray-300 bg-gray-50 text-sm disabled:cursor-not-allowed" :disabled="isApplyingPromo">
                                    <span x-show="!isApplyingPromo"><?= lang('Transaction.btn_apply_promo') ?></span>
                                    <svg x-show="isApplyingPromo" class="animate-spin h-4 w-4 text-gray-500" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                                </button>
                            </template>
                            <template x-if="appliedPromo">
                                <button type="button" @click="removePromo()" class="inline-flex items-center px-3 rounded-r-md border border-l-0 border-gray-300 bg-red-50 text-red-600 hover:bg-red-100 text-sm">
                                    <span>×</span>
                                </button>
                            </template>
                        </div>
                        <p x-show="promoError" x-text="promoError" class="mt-2 text-xs text-red-600" x-cloak></p>
                        <p x-show="appliedPromo" class="mt-2 text-xs text-green-600" x-cloak><?= lang('Transaction.promo_applied_success') ?></p>
                    </div>

                    <div class="space-y-3 text-gray-700 mt-6">
                        <div class="flex justify-between"><span><?= lang('Transaction.summary_subtotal') ?></span><span x-text="formatCurrency(subTotal)"></span></div>
                        <template x-if="appliedPromo">
                            <div class="flex justify-between text-green-600">
                                <span><?= lang('Transaction.summary_discount') ?> (<span x-text="appliedPromo.code"></span>)</span>
                                <span x-text="'-' + formatCurrency(appliedPromo.discount_amount)"></span>
                            </div>
                        </template>
                        <div class="flex justify-between"><span><?= lang('Transaction.summary_handling_fee') ?></span><span x-text="formatCurrency(handlingFee)"></span></div>
                    </div>

                    <div class="flex justify-between font-bold text-xl pt-4 mt-4 border-t border-gray-200">
                        <span><?= lang('Transaction.summary_total') ?></span><span x-text="formatCurrency(totalAmount)"></span>
                    </div>

                    <div class="mt-6">
                        <label for="payment_method" class="block mb-2 text-sm font-medium text-gray-900"><?= lang('Transaction.field_payment_method') ?> <span class="text-red-500">*</span></label>
                        <select name="payment_method" id="payment_method" x-model="selectedPaymentMethod" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg w-full p-2.5" required>
                            <option value=""><?= lang('Transaction.option_choose_payment') ?></option>
                            <template x-for="method in paymentMethods" :key="method.method"><option :value="method.method" x-text="`${method.name} (Fee: ${formatCurrency(method.fee)})`"></option></template>
                        </select>
                    </div>
                    <?php if(!empty($event->terms_conditions)): ?>
                    <div class="mt-6 pt-6 border-t">
                        <div class="flex items-start">
                            <div class="flex items-center h-5">
                                <input id="agree_terms" name="agree_terms" type="checkbox" value="1" class="h-4 w-4 text-indigo-600 border-gray-300 rounded" required>
                            </div>
                            <div class="ml-3 text-sm">
                                <label for="agree_terms" class="font-medium text-gray-700">I agree to the 
                                    <a href="<?= route_to('terms.show', $event->slug) ?>" target="_blank" class="text-indigo-600 hover:underline">Terms and Conditions</a>.
                                </label>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    <div class="mt-8">
                        <button type="submit" class="w-full flex justify-center items-center text-white bg-green-600 hover:bg-green-700 font-medium rounded-lg text-lg px-5 py-3 disabled:bg-gray-400 disabled:cursor-wait" :disabled="isSubmitting">
                            <svg x-show="isSubmitting" class="animate-spin -ml-1 mr-3 h-5 w-5" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                            <span x-show="!isSubmitting"><?= lang('Transaction.button_process') ?></span>
                            <span x-show="isSubmitting">Processing...</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
</div>

<script>
    function transactionForm(packagesData, paymentMethodsData, churchesData) {
        const oldParticipantsData = <?= json_encode(old('participants')) ?? 'null' ?>;
        
        const initialParticipants = oldParticipantsData 
            ? oldParticipantsData.map((p, index) => ({ id: Date.now() + index, package_id: p.package_id || '', name: p.name || '', phone_number: p.phone_number || '', email: p.email || '', gender: p.gender || 'Male', church_id: p.church_id || '', church_name: p.church_name || '', kta_number: p.kta_number || '', birth_date: p.birth_date || '', custom: p.custom || {} }))
            : [{ id: Date.now(), package_id: '', church_id: '', church_name: '', custom: {} }];

        return {
            packages: packagesData,
            paymentMethods: paymentMethodsData,
            churches: churchesData,
            participants: initialParticipants,
            selectedPaymentMethod: '<?= old('payment_method') ?? '' ?>',
            isSubmitting: false,
            promoCode: '<?= old('promo_code') ?? '' ?>',
            isApplyingPromo: false,
            appliedPromo: null,
            promoError: '',
            
            init() {
                this.participants.forEach(p => { 
                    p.church_id = p.church_id || '';
                    p.church_name = p.church_name || '';
                    if (typeof p.custom === 'undefined') p.custom = {};
                });
            },
            isKtaRequired(packageId) { if (!packageId) return false; const pkg = this.packages.find(p => p.id == packageId); return pkg ? pkg.require_kta == 1 : false; },
            get subTotal() { return this.participants.reduce((total, p) => { if (!p.package_id) return total; const pkg = this.packages.find(item => item.id == p.package_id); return total + (pkg ? parseFloat(pkg.price) : 0); }, 0); },
            get handlingFee() { if (!this.selectedPaymentMethod) return 0; const method = this.paymentMethods.find(m => m.method === this.selectedPaymentMethod); return method ? parseFloat(method.fee) : 0; },
            get totalAmount() { const discount = this.appliedPromo ? parseFloat(this.appliedPromo.discount_amount) : 0; return this.subTotal - discount + this.handlingFee; },
            addParticipant() { if (this.participants.length < 5) { this.participants.push({ id: Date.now(), package_id: '', church_id: '', church_name: '', custom: {} }); } },
            removeParticipant(index) { if (this.participants.length > 1) { this.participants.splice(index, 1); } },
            formatCurrency(value) { if (isNaN(value)) return 'IDR 0'; return `IDR ${new Intl.NumberFormat('id-ID').format(value || 0)}`; },
            
            // Mengembalikan fungsi yang hilang
            formatPaymentMethodName(methodName) {
                const method = this.paymentMethods.find(m => m.method === methodName);
                return method ? method.name : methodName.charAt(0).toUpperCase() + methodName.slice(1).replace(/_/g, ' ');
            },
            
            removePromo() {
                this.appliedPromo = null;
                this.promoCode = '';
                this.promoError = '';
            },

            async applyPromo() {
                if (!this.promoCode || this.isApplyingPromo || this.appliedPromo) return;
                
                this.isApplyingPromo = true;
                this.promoError = '';

                const formData = new FormData();
                formData.append('promo_code', this.promoCode);
                formData.append('subtotal', this.subTotal);
                formData.append('quantity', this.participants.length);
                formData.append('event_id', '<?= $event->id ?>');
                formData.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

                try {
                    const response = await fetch('<?= route_to("transaction.promo.validate") ?>', { method: 'POST', body: formData });
                    const data = await response.json();
                    if (!response.ok) {
                        this.promoError = data.error || 'An unknown error occurred.';
                        this.appliedPromo = null;
                    } else {
                        data.code = this.promoCode.toUpperCase();
                        this.appliedPromo = data;
                    }
                } catch (error) {
                    this.promoError = 'Could not connect to the server.';
                } finally {
                    this.isApplyingPromo = false;
                }
            }
        }
    }
</script>
<?= $this->endSection() ?>