@extends('layouts.staff')

@section('content')
<div class="container">

    <div class="card shadow-sm">
        <div class="card-header bg-dark text-white text-center">
            <h4 class="mb-1">{{ $survey->title }}</h4>
            <small class="text-white-50">Tarikh: {{ \Carbon\Carbon::parse($survey->date)->format('d M Y') }}</small>
        </div>
        <div class="card-body p-4">

            @if($survey->perincian)
                <div class="mb-4 text-dark">
                    {!! nl2br(e($survey->perincian)) !!}
                </div>
            @endif

            @if ($errors->any())
                <div class="alert alert-danger">
                    <strong>Ralat!</strong> {{ $errors->first() }}
                </div>
            @endif

            <form action="{{ route('surveys.store', $survey->uuid) }}" method="POST" id="survey-form">
                @csrf
                <div class="card shadow-sm mb-4 border-primary">
                        <div class="card-header bg-primary text-white small fw-bold">MAKLUMAT RESPONDEN</div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Nama Penuh</label>
                                <input type="text" name="respondent_name" class="form-control" placeholder="Nama Penuh Anda" required>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label small fw-bold">No. Pekerja</label>
                                    <input type="text" name="respondent_no_pekerja" class="form-control" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label small fw-bold">Jabatan</label>
                                    <select name="respondent_jabatan" class="form-select" required>
                                        <option value="">Pilih Jabatan</option>
                                        <option value="DatukBandar">Datuk Bandar</option>
                                        <option value="SU">Setiausaha</option>
                                        <option value="TSU">Timbalan Setiausaha</option>
                                        <option value="JKP">Khidmat Pengurusan</option>
                                        <option value="Kewangan">Kewangan</option>
                                        <option value="JPPH">Penilaian dan Pengurusan Harta</option>
                                        <option value="JPP">Perancangan Pembangunan</option>
                                        <option value="Kejuruteraan">Kejuruteraan</option>
                                        <option value="Bangunan">Bangunan</option>
                                        <option value="JKA">Kesihatan Awam</option>
                                        <option value="Pelesenan">Pelesenan</option>
                                        <option value="Penguatkuasaan">Penguatkuasaan</option>
                                        <option value="JPM">Pembangunan Masyarakat</option>
                                        <option value="Lanskap">Lanskap</option>
                                        <option value="Undang-undang">Undang-undang</option>
                                        <option value="Korporat">Korporat dan Perhubungan Awam</option>
                                        <option value="JTM">Teknologi Maklumat</option>
                                        <option value="Audit">Unit Audi Dalam</option>
                                        <option value="PengurusanStrategik">Unit Pengurusan Strategik</option>
                                        <option value="Integriti">Unit Integriti</option>
                                        <option value="OSC">Unit Pusat Sehenti (OSC)</option>
                                        <option value="COB">Unit Pesuruhjaya Bangunan (COB)</option>
                                        <option value="UBP">Unit Bandar Pintar (Smart City)</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                {{-- LOOP BAHAGIAN --}}
                @foreach($survey->sections as $section)
                    <fieldset class="mb-5">
                        <legend class="border-bottom pb-2 mb-3 fw-bold text-primary">{{ $section->title }}</legend>
                        @if($section->description)
                            <p class="text-muted mb-4">{{ $section->description }}</p>
                        @endif

                        {{-- LOOP SOALAN --}}
                        @foreach($section->questions as $question)
                            <div class="card mb-4 border-0 shadow-sm bg-light">
                                <div class="card-body">
                                    <label class="form-label fw-bold mb-3">
                                        {{ $loop->iteration }}. {{ $question->question_text }}
                                        @if($question->type != 'checkbox' && $question->type != 'text')
                                            <span class="text-danger">*</span>
                                        @endif
                                    </label>

                                    {{-- TYPE: RADIO --}}
                                    @if($question->type == 'radio')
                                        <div class="radio-group" data-id="{{ $question->id }}">
                                            @foreach($question->options as $option)
                                            <div class="form-check mb-2">
                                                <input class="form-check-input normal-option" type="radio"
                                                       name="answers[{{ $question->id }}]"
                                                       id="q{{ $question->id }}_opt{{ $option->id }}"
                                                       value="{{ $option->option_text }}" required>
                                                <label class="form-check-label" for="q{{ $question->id }}_opt{{ $option->id }}">
                                                    {{ $option->option_text }}
                                                </label>
                                            </div>
                                            @endforeach

                                            {{-- OTHERS OPTION FOR RADIO --}}
                                            @if($question->allow_other_option)
                                            <div class="form-check mt-2">
                                                <input class="form-check-input other-radio" type="radio"
                                                       name="answers[{{ $question->id }}]"
                                                       id="q{{ $question->id }}_other"
                                                       value="Other">
                                                <label class="form-check-label fw-bold" for="q{{ $question->id }}_other">
                                                    Lain-lain (Sila nyatakan):
                                                </label>
                                                <input type="text" class="form-control mt-1 other-text-input"
                                                       style="display:none;"
                                                       placeholder="Sila tulis jawapan anda..." disabled>
                                            </div>
                                            @endif
                                        </div>

                                    {{-- TYPE: CHECKBOX --}}
                                    @elseif($question->type == 'checkbox')
                                        <div class="checkbox-group" data-id="{{ $question->id }}">
                                            @foreach($question->options as $option)
                                            <div class="form-check mb-2">
                                                <input class="form-check-input normal-option" type="checkbox"
                                                       name="answers[{{ $question->id }}][]"
                                                       id="q{{ $question->id }}_opt{{ $option->id }}"
                                                       value="{{ $option->option_text }}">
                                                <label class="form-check-label" for="q{{ $question->id }}_opt{{ $option->id }}">
                                                    {{ $option->option_text }}
                                                </label>
                                            </div>
                                            @endforeach

                                            {{-- OTHERS OPTION FOR CHECKBOX --}}
                                            @if($question->allow_other_option)
                                            <div class="form-check mt-2">
                                                <input class="form-check-input other-checkbox" type="checkbox"
                                                       name="answers[{{ $question->id }}][]"
                                                       id="q{{ $question->id }}_other_check"
                                                       value="Other">
                                                <label class="form-check-label fw-bold" for="q{{ $question->id }}_other_check">
                                                    Lain-lain (Sila nyatakan):
                                                </label>
                                                <input type="text" class="form-control mt-1 other-text-input"
                                                       style="display:none;"
                                                       placeholder="Sila tulis jawapan anda..." disabled>
                                            </div>
                                            @endif
                                        </div>

                                    {{-- TYPE: TEXT --}}
                                    @elseif($question->type == 'text')
                                        <textarea name="answers[{{ $question->id }}]"
                                                  class="form-control"
                                                  rows="3"
                                                  placeholder="Tulis jawapan anda di sini..." required></textarea>
                                    @endif
                                </div>
                            </div>
                        @endforeach
                    </fieldset>
                @endforeach

                <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4 mb-5">
                    <button type="submit" class="btn btn-primary btn-lg">Hantar Jawapan</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {

    // 1. Handle RADIO logic
    const radioGroups = document.querySelectorAll('.radio-group');
    radioGroups.forEach(group => {
        const otherRadio = group.querySelector('.other-radio');
        const otherInput = group.querySelector('.other-text-input');
        const normalRadios = group.querySelectorAll('.normal-option');

        if(otherRadio && otherInput) {
            otherRadio.addEventListener('change', function() {
                if(this.checked) {
                    otherInput.style.display = 'block';
                    otherInput.disabled = false;
                    otherInput.focus();
                    otherInput.required = true; // Paksa isi
                }
            });

            normalRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    if(this.checked) {
                        otherInput.style.display = 'none';
                        otherInput.disabled = true;
                        otherInput.value = ''; 
                        otherInput.required = false;
                    }
                });
            });
        }
    });

    // 2. Handle CHECKBOX logic
    const checkboxGroups = document.querySelectorAll('.checkbox-group');
    checkboxGroups.forEach(group => {
        const otherCheck = group.querySelector('.other-checkbox');
        const otherInput = group.querySelector('.other-text-input');

        if(otherCheck && otherInput) {
            otherCheck.addEventListener('change', function() {
                if(this.checked) {
                    otherInput.style.display = 'block';
                    otherInput.disabled = false;
                    otherInput.focus();
                    otherInput.required = true;
                } else {
                    otherInput.style.display = 'none';
                    otherInput.disabled = true;
                    otherInput.value = '';
                    otherInput.required = false;
                }
            });
        }
    });

    // 3. FORM SUBMISSION INTERCEPTOR
    // Ini trick paling penting. Sebelum hantar ke server, kita tukar value radio/checkbox
    // "Other" tu menjadi text yang user tulis.
    const form = document.getElementById('survey-form');
    form.addEventListener('submit', function(e) {

        // Cari semua input text "Lain-lain" yang aktif (tidak disabled)
        const activeOtherInputs = document.querySelectorAll('.other-text-input:not(:disabled)');

        activeOtherInputs.forEach(input => {
            // Cari radio/checkbox kawannya (previous element sibling dalam DOM structure wrapper)
            // Dalam struktur HTML di atas, input text adalah adik beradik dengan label, dan label dengan input radio.

            // Kita cari wrapper parent div
            const wrapper = input.closest('.form-check');
            const relatedOption = wrapper.querySelector('input[type="radio"], input[type="checkbox"]');

            if(relatedOption && relatedOption.checked) {
                // TUKAR VALUE radio/checkbox menjadi apa yang user tulis
                // Contoh: dari value="Other" jadi value="Saya suka makan nasi ayam"
                relatedOption.value = "Lain-lain: " + input.value;
            }
        });

        // Benarkan form submit seperti biasa
    });

});
</script>
@endpush
