@extends('layouts.frontend')

@section('title', 'Уулзалт товлох — NSMA')

@section('content')

<section class="py-16 lg:py-20">
    <div class="max-w-4xl mx-auto px-4 lg:px-8">
        <div class="text-center mb-10">
            <h1 class="text-3xl lg:text-4xl font-black mb-3">Уулзалт <span class="text-nsma-red">товлох</span></h1>
            <p class="text-gray-600">Бидэнтэй биечлэн, утсаар эсвэл онлайнаар уулзах боломжтой.</p>
        </div>

        <div class="bg-white rounded-2xl shadow-xl p-6 lg:p-10 border border-gray-100">
            <form id="meeting-form" action="{{ route('meeting.store') }}" method="POST" class="space-y-5">
                @csrf

                <div class="grid md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold mb-1">Бүтэн нэр <span class="text-nsma-red">*</span></label>
                        <input type="text" name="full_name" required value="{{ auth('client')->user()->name ?? '' }}" class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-nsma-red focus:ring-2 focus:ring-nsma-red/20 outline-none">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold mb-1">Байгууллага</label>
                        <input type="text" name="company_name" value="{{ auth('client')->user()->company_name ?? '' }}" class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-nsma-red focus:ring-2 focus:ring-nsma-red/20 outline-none">
                    </div>
                </div>

                <div class="grid md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold mb-1">И-мэйл <span class="text-nsma-red">*</span></label>
                        <input type="email" name="email" required value="{{ auth('client')->user()->email ?? '' }}" class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-nsma-red focus:ring-2 focus:ring-nsma-red/20 outline-none">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold mb-1">Утас <span class="text-nsma-red">*</span></label>
                        <input type="tel" name="phone" required value="{{ auth('client')->user()->phone ?? '' }}" class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-nsma-red focus:ring-2 focus:ring-nsma-red/20 outline-none">
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-semibold mb-1">Уулзалтын сэдэв <span class="text-nsma-red">*</span></label>
                    <input type="text" name="subject" required class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-nsma-red focus:ring-2 focus:ring-nsma-red/20 outline-none">
                </div>

                <div>
                    <label class="block text-sm font-semibold mb-2">Уулзалтын төрөл <span class="text-nsma-red">*</span></label>
                    <div class="grid grid-cols-3 gap-3">
                        <label class="flex items-center gap-2 px-4 py-3 rounded-lg border border-gray-200 cursor-pointer hover:border-nsma-red has-[:checked]:border-nsma-red has-[:checked]:bg-nsma-red/5">
                            <input type="radio" name="meeting_type" value="office" checked class="text-nsma-red focus:ring-nsma-red">
                            <span class="text-sm">Оффис</span>
                        </label>
                        <label class="flex items-center gap-2 px-4 py-3 rounded-lg border border-gray-200 cursor-pointer hover:border-nsma-red has-[:checked]:border-nsma-red has-[:checked]:bg-nsma-red/5">
                            <input type="radio" name="meeting_type" value="online" class="text-nsma-red focus:ring-nsma-red">
                            <span class="text-sm">Онлайн</span>
                        </label>
                        <label class="flex items-center gap-2 px-4 py-3 rounded-lg border border-gray-200 cursor-pointer hover:border-nsma-red has-[:checked]:border-nsma-red has-[:checked]:bg-nsma-red/5">
                            <input type="radio" name="meeting_type" value="phone" class="text-nsma-red focus:ring-nsma-red">
                            <span class="text-sm">Утсаар</span>
                        </label>
                    </div>
                </div>

                <div class="grid md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold mb-1">Огноо <span class="text-nsma-red">*</span></label>
                        <input type="date" name="preferred_date" id="preferred_date" required min="{{ now()->addDay()->format('Y-m-d') }}" class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-nsma-red focus:ring-2 focus:ring-nsma-red/20 outline-none">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold mb-1">Цаг <span class="text-nsma-red">*</span></label>
                        <select name="preferred_time" id="preferred_time" required disabled class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-nsma-red focus:ring-2 focus:ring-nsma-red/20 outline-none disabled:opacity-50">
                            <option value="">Эхлээд огноо сонгоно уу</option>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-semibold mb-1">Нэмэлт мэдээлэл</label>
                    <textarea name="message" rows="3" class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:border-nsma-red focus:ring-2 focus:ring-nsma-red/20 outline-none"></textarea>
                </div>

                <button type="submit" class="w-full bg-nsma-red text-white font-semibold px-6 py-3 rounded-lg hover:bg-red-600 transition flex items-center justify-center gap-2">
                    <span class="btn-text">Уулзалт товлох</span>
                    <svg class="btn-loading hidden w-5 h-5 animate-spin" 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-8v8H4z"></path></svg>
                </button>
                <div id="meeting-errors" class="hidden text-sm text-red-600"></div>
            </form>
        </div>
    </div>
</section>

@push('scripts')
<script>
    const dateInput = document.getElementById('preferred_date');
    const timeSelect = document.getElementById('preferred_time');

    // Огноо сонгох үед боломжтой цагуудыг AJAX-аар авах
    dateInput.addEventListener('change', async () => {
        const date = dateInput.value;
        if (! date) return;

        timeSelect.innerHTML = '<option value="">Цаг ачаалж байна...</option>';
        timeSelect.disabled = true;

        try {
            const res = await fetch(`{{ url('/meeting/slots') }}?date=${date}`, {
                headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
            });
            const data = await res.json();

            timeSelect.innerHTML = '<option value="">Цаг сонгох</option>';
            if (data.slots.length === 0) {
                timeSelect.innerHTML = '<option value="">Боломжтой цаг байхгүй</option>';
            } else {
                data.slots.forEach(slot => {
                    const opt = document.createElement('option');
                    opt.value = slot;
                    opt.textContent = slot;
                    timeSelect.appendChild(opt);
                });
            }
            timeSelect.disabled = false;
        } catch (e) {
            console.error(e);
        }
    });

    document.getElementById('meeting-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const form = e.target;
        const btn = form.querySelector('button[type=submit]');
        const errorBox = document.getElementById('meeting-errors');

        btn.disabled = true;
        form.querySelector('.btn-text').textContent = 'Илгээж байна...';
        form.querySelector('.btn-loading').classList.remove('hidden');
        errorBox.classList.add('hidden');

        const result = await window.ajaxSubmit(form);

        btn.disabled = false;
        form.querySelector('.btn-text').textContent = 'Уулзалт товлох';
        form.querySelector('.btn-loading').classList.add('hidden');

        if (result.ok && result.data.success) {
            window.showToast(result.data.message, 'success');
            form.reset();
            timeSelect.innerHTML = '<option value="">Эхлээд огноо сонгоно уу</option>';
            timeSelect.disabled = true;
        } else if (result.data.errors) {
            errorBox.textContent = Object.values(result.data.errors).flat().join(', ');
            errorBox.classList.remove('hidden');
        } else {
            window.showToast(result.data.message || 'Алдаа гарлаа.', 'error');
        }
    });
</script>
@endpush

@endsection
