@extends('layouts.app')
@section('title', 'Edit Panel Test')
@section('content')

<div class="d-flex align-items-center gap-2 mb-4">
    <a href="{{ route('panel-tests.show', $panelTest) }}" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-arrow-left"></i>
    </a>
    <div>
        <h4 class="fw-bold mb-0">Edit Panel Test</h4>
        <small class="text-muted">{{ $panelTest->title }}</small>
    </div>
</div>

@if(session('success'))
<div class="alert alert-success alert-dismissible fade show">
    {!! session('success') !!}
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

@if($errors->any())
<div class="alert alert-danger alert-dismissible fade show">
    <ul class="mb-0">
        @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
        @endforeach
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

<div class="row g-3">

    {{-- Kolom Kiri: Form Info Panel Test --}}
    <div class="col-lg-4">
        <div class="card mb-3">
            <div class="card-header bg-white py-3">
                <h6 class="fw-semibold mb-0">
                    <i class="bi bi-pencil-square text-primary"></i>
                    Informasi Panel Test
                </h6>
            </div>
            <div class="card-body">
                <form method="POST" action="{{ route('panel-tests.update', $panelTest) }}">
                    @csrf
                    @method('PUT')

                    {{-- Produk --}}
                    <div class="mb-3">
                        <label class="form-label fw-medium small">
                            Produk <span class="text-danger">*</span>
                        </label>
                        <select name="product_id"
                            class="form-select form-select-sm @error('product_id') is-invalid @enderror"
                            required>
                            <option value="">-- Pilih Produk --</option>
                            @foreach($products as $product)
                            <option value="{{ $product->id }}"
                                {{ old('product_id', $panelTest->product_id) == $product->id ? 'selected' : '' }}>
                                {{ $product->name }}
                            </option>
                            @endforeach
                        </select>
                        @error('product_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    {{-- Judul --}}
                    <div class="mb-3">
                        <label class="form-label fw-medium small">
                            Judul <span class="text-danger">*</span>
                        </label>
                        <input type="text" name="title"
                            class="form-control form-control-sm @error('title') is-invalid @enderror"
                            value="{{ old('title', $panelTest->title) }}"
                            required>
                        @error('title')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    {{-- Deskripsi --}}
                    <div class="mb-3">
                        <label class="form-label fw-medium small">Deskripsi</label>
                        <textarea name="description"
                            class="form-control form-control-sm @error('description') is-invalid @enderror"
                            rows="2">{{ old('description', $panelTest->description) }}</textarea>
                        @error('description')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    {{-- Tanggal --}}
                    <div class="mb-3">
                        <label class="form-label fw-medium small">
                            Tanggal Test <span class="text-danger">*</span>
                        </label>
                        <input type="date" name="test_date"
                            class="form-control form-control-sm @error('test_date') is-invalid @enderror"
                            value="{{ old('test_date', $panelTest->test_date->format('Y-m-d')) }}"
                            required>
                        @error('test_date')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    {{-- Lokasi --}}
                    <div class="mb-3">
                        <label class="form-label fw-medium small">Lokasi</label>
                        <input type="text" name="location"
                            class="form-control form-control-sm @error('location') is-invalid @enderror"
                            value="{{ old('location', $panelTest->location) }}"
                            placeholder="Contoh: Jakarta Pusat">
                        @error('location')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    {{-- Status --}}
                    <div class="mb-3">
                        <label class="form-label fw-medium small">
                            Status <span class="text-danger">*</span>
                        </label>
                        <select name="status"
                            class="form-select form-select-sm @error('status') is-invalid @enderror"
                            required>
                            <option value="draft"
                                {{ old('status', $panelTest->status) === 'draft' ? 'selected' : '' }}>
                                📝 Draft
                            </option>
                            <option value="active"
                                {{ old('status', $panelTest->status) === 'active' ? 'selected' : '' }}>
                                ✅ Active
                            </option>
                            <option value="closed"
                                {{ old('status', $panelTest->status) === 'closed' ? 'selected' : '' }}>
                                🔒 Closed
                            </option>
                        </select>
                        @error('status')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    {{-- Info Unit readonly --}}
                    <div class="p-2 rounded mb-3" style="background:#f8fafc;border:1px solid #e2e8f0">
                        <p class="text-muted small fw-medium mb-2">
                            <i class="bi bi-info-circle"></i> Info Unit (tidak dapat diubah)
                        </p>
                        <div class="row g-2">
                            <div class="col-4">
                                <label class="form-label small text-muted mb-1">Tipe</label>
                                <input type="text" class="form-control form-control-sm"
                                    value="{{ ucfirst($panelTest->unit_type ?? '-') }}" readonly>
                            </div>
                            <div class="col-4">
                                <label class="form-label small text-muted mb-1">Wilayah</label>
                                <input type="text" class="form-control form-control-sm"
                                    value="{{ ucfirst($panelTest->region ?? '-') }}" readonly>
                            </div>
                            <div class="col-4">
                                <label class="form-label small text-muted mb-1">Divisi</label>
                                <input type="text" class="form-control form-control-sm"
                                    value="{{ ucfirst($panelTest->division ?? '-') }}" readonly>
                            </div>
                        </div>
                    </div>

                    {{-- Tombol Simpan --}}
                    <div class="d-flex gap-2">
                        <a href="{{ route('panel-tests.show', $panelTest) }}"
                            class="btn btn-outline-secondary btn-sm flex-grow-1">
                            <i class="bi bi-x"></i> Batal
                        </a>
                        <button type="submit" class="btn btn-primary btn-sm flex-grow-1">
                            <i class="bi bi-check-lg"></i> Simpan
                        </button>
                    </div>

                </form>
            </div>
        </div>
    </div>

    {{-- Kolom Kanan: Sampel & Pertanyaan --}}
    <div class="col-lg-8">

        @php
            $sampleColors = ['3b82f6','22c55e','f59e0b','ef4444','8b5cf6'];
        @endphp

        {{-- Pertanyaan Umum --}}
        <div class="card mb-3">
            <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                <h6 class="fw-semibold mb-0">
                    <i class="bi bi-list-check text-primary"></i>
                    Pertanyaan Umum
                    <span class="badge bg-secondary ms-1" style="font-size:11px">
                        Berlaku untuk semua sampel
                    </span>
                </h6>
                <span class="badge bg-primary">
                    {{ $panelTest->generalQuestions->count() }} pertanyaan
                </span>
            </div>
            <div class="card-body">
                @forelse($panelTest->generalQuestions as $i => $q)
                <div class="d-flex gap-2 p-2 border rounded mb-2" style="background:#f8fafc">
                    <div style="width:24px;height:24px;background:#1e3a5f;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:600;flex-shrink:0;margin-top:2px">
                        {{ $i + 1 }}
                    </div>
                    <div class="flex-grow-1">
                        <div class="fw-medium small">{{ $q->question_text }}</div>
                        <div class="d-flex gap-1 mt-1 flex-wrap">
                            <span class="badge"
                                style="background:#e2e8f0;color:#475569;font-size:10px">
                                {{ $q->question_type }}
                            </span>
                            @if($q->options)
                            @foreach($q->options as $opt)
                            <span class="badge bg-light text-dark" style="font-size:10px">
                                {{ $opt }}
                            </span>
                            @endforeach
                            @endif
                        </div>
                    </div>
                    {{-- ✅ Tombol hapus pertanyaan selalu tampil --}}
                    <form method="POST" action="{{ route('questions.destroy', $q) }}"
                        onsubmit="return confirm('Hapus pertanyaan ini?')">
                        @csrf @method('DELETE')
                        <button class="btn btn-sm btn-outline-danger py-0">
                            <i class="bi bi-trash"></i>
                        </button>
                    </form>
                </div>
                @empty
                <p class="text-muted small text-center py-2">
                    Belum ada pertanyaan umum
                </p>
                @endforelse

                {{-- ✅ Form tambah pertanyaan umum selalu tampil --}}
                <form method="POST"
                    action="{{ route('questions.store', $panelTest) }}" class="mt-3">
                    @csrf
                    <div class="row g-2">
                        <div class="col-12">
                            <textarea name="question_text"
                                class="form-control form-control-sm" rows="2"
                                placeholder="Pertanyaan umum..." required></textarea>
                        </div>
                        <div class="col-md-5">
                            <select name="question_type"
                                class="form-select form-select-sm"
                                id="generalType" onchange="toggleGeneralOptions()">
                                <option value="rating">⭐ Rating (1-5)</option>
                                <option value="text">💬 Teks Bebas</option>
                                <option value="yes_no">✅ Ya/Tidak</option>
                                <option value="multiple_choice">📋 Pilihan Ganda</option>
                            </select>
                        </div>
                        <div class="col-md-4" id="generalOptionsField" style="display:none">
                            <textarea name="options" class="form-control form-control-sm"
                                rows="2"
                                placeholder="Pilihan A&#10;Pilihan B&#10;Pilihan C"></textarea>
                        </div>
                        <div class="col-md-3">
                            <button type="submit" class="btn btn-primary btn-sm w-100">
                                <i class="bi bi-plus"></i> Tambah
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        {{-- Daftar Sampel --}}
        @foreach($panelTest->samples as $si => $sample)
        @php $color = $sampleColors[$si % 5]; @endphp

        <div class="card mb-3" style="border-left:4px solid #{{ $color }}">
            <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
                <div>
                    <h6 class="fw-bold mb-0">
                        <span class="badge me-2" style="background:#{{ $color }}">
                            Sampel {{ $si + 1 }}
                        </span>
                        {{-- ✅ Nama sampel bisa diedit inline --}}
                        <form method="POST" action="{{ route('samples.update', $sample) }}"
                            class="d-inline-flex gap-1 align-items-center">
                            @csrf @method('PUT')
                            <input type="text" name="name"
                                class="form-control form-control-sm"
                                style="width:120px;display:inline-block"
                                value="{{ $sample->name }}" required>
                            <input type="text" name="code"
                                class="form-control form-control-sm"
                                style="width:80px;display:inline-block"
                                value="{{ $sample->code }}"
                                placeholder="Kode">
                            <input type="text" name="description"
                                class="form-control form-control-sm"
                                style="width:120px;display:inline-block"
                                value="{{ $sample->description }}"
                                placeholder="Keterangan">
                            <button type="submit" class="btn btn-sm btn-outline-primary py-0 px-2">
                                <i class="bi bi-check-lg"></i>
                            </button>
                        </form>
                    </h6>
                </div>
                <div class="d-flex gap-2 align-items-center">
                    <span class="badge bg-light text-dark">
                        {{ $sample->questions->count() }} pertanyaan
                    </span>
                    {{-- ✅ Tombol hapus sampel selalu tampil --}}
                    <form method="POST" action="{{ route('samples.destroy', $sample) }}"
                        onsubmit="return confirm('Hapus sampel ini beserta semua pertanyaannya?')">
                        @csrf @method('DELETE')
                        <button class="btn btn-sm btn-outline-danger">
                            <i class="bi bi-trash"></i> Hapus
                        </button>
                    </form>
                </div>
            </div>

            <div class="card-body">

                {{-- Salin pertanyaan dari sampel lain --}}
                @if($panelTest->samples->count() > 1)
                <div class="mb-3 p-3 rounded" style="background:#fffbeb;border:1px solid #fde68a">
                    <div class="fw-medium small text-warning-emphasis mb-2">
                        <i class="bi bi-files text-warning"></i>
                        Salin pertanyaan dari sampel lain ke <strong>{{ $sample->name }}</strong>:
                    </div>
                    <form method="POST"
                        action="{{ route('samples.copy-questions', $sample) }}"
                        class="d-flex gap-2 align-items-center flex-wrap">
                        @csrf
                        <select name="source_sample_id"
                            class="form-select form-select-sm"
                            style="max-width:200px" required>
                            <option value="">-- Pilih sumber --</option>
                            @foreach($panelTest->samples->where('id', '!=', $sample->id) as $other)
                            <option value="{{ $other->id }}">
                                {{ $other->name }} ({{ $other->questions->count() }} soal)
                            </option>
                            @endforeach
                        </select>
                        <div class="form-check form-check-inline mb-0">
                            <input class="form-check-input" type="checkbox"
                                name="replace_existing" value="1"
                                id="replace-{{ $sample->id }}">
                            <label class="form-check-label small"
                                for="replace-{{ $sample->id }}">
                                Hapus pertanyaan lama
                            </label>
                        </div>
                        <button type="submit" class="btn btn-warning btn-sm"
                            onclick="return confirm('Salin pertanyaan?')">
                            <i class="bi bi-files"></i> Salin
                        </button>
                    </form>
                </div>
                @endif

                {{-- Daftar pertanyaan --}}
                @forelse($sample->questions as $qi => $q)
                <div class="d-flex gap-2 p-2 border rounded mb-2" style="background:#f8fafc">
                    <div style="width:24px;height:24px;background:#{{ $color }};border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:600;flex-shrink:0;margin-top:2px">
                        {{ $qi + 1 }}
                    </div>
                    <div class="flex-grow-1">
                        <div class="fw-medium small">{{ $q->question_text }}</div>
                        <div class="d-flex gap-1 mt-1 flex-wrap">
                            <span class="badge"
                                style="background:#e2e8f0;color:#475569;font-size:10px">
                                {{ $q->question_type }}
                            </span>
                            @if($q->options)
                            @foreach($q->options as $opt)
                            <span class="badge bg-light text-dark" style="font-size:10px">
                                {{ $opt }}
                            </span>
                            @endforeach
                            @endif
                        </div>
                    </div>
                    {{-- ✅ Tombol hapus pertanyaan selalu tampil --}}
                    <form method="POST" action="{{ route('questions.destroy', $q) }}"
                        onsubmit="return confirm('Hapus pertanyaan ini?')">
                        @csrf @method('DELETE')
                        <button class="btn btn-sm btn-outline-danger py-0">
                            <i class="bi bi-trash"></i>
                        </button>
                    </form>
                </div>
                @empty
                <div class="text-center text-muted py-3 small">
                    <i class="bi bi-question-circle d-block fs-4 mb-1"></i>
                    Belum ada pertanyaan.
                </div>
                @endforelse

                {{-- ✅ Form tambah pertanyaan selalu tampil --}}
                <div class="mt-3 pt-3" style="border-top:1px dashed #e2e8f0">
                    <div class="small fw-medium text-muted mb-2">
                        <i class="bi bi-plus-circle"></i>
                        Tambah pertanyaan ke {{ $sample->name }}:
                    </div>
                    <form method="POST"
                        action="{{ route('samples.questions.store', $sample) }}">
                        @csrf
                        <div class="row g-2">
                            <div class="col-12">
                                <textarea name="question_text"
                                    class="form-control form-control-sm" rows="2"
                                    placeholder="Contoh: Bagaimana rasa manis {{ $sample->name }}?"
                                    required></textarea>
                            </div>
                            <div class="col-md-4">
                                <select name="question_type"
                                    class="form-select form-select-sm"
                                    id="type-{{ $sample->id }}"
                                    onchange="toggleOptions({{ $sample->id }})">
                                    <option value="rating">⭐ Rating (1-5)</option>
                                    <option value="text">💬 Teks Bebas</option>
                                    <option value="yes_no">✅ Ya/Tidak</option>
                                    <option value="multiple_choice">📋 Pilihan Ganda</option>
                                </select>
                            </div>
                            <div class="col-md-5"
                                id="options-{{ $sample->id }}" style="display:none">
                                <textarea name="options"
                                    class="form-control form-control-sm" rows="2"
                                    placeholder="A. Pas&#10;B. Kurang&#10;C. Terlalu Manis"></textarea>
                                <small class="text-muted">Satu pilihan per baris</small>
                            </div>
                            <div class="col-md-3">
                                <button type="submit" class="btn btn-sm w-100"
                                    style="background:#{{ $color }};color:#fff;border:none">
                                    <i class="bi bi-plus"></i> Tambah
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

            </div>
        </div>
        @endforeach

        {{-- ✅ Form tambah sampel baru selalu tampil --}}
        <div class="card" style="border:2px dashed #cbd5e1">
            <div class="card-body">
                <h6 class="fw-semibold mb-3">
                    <i class="bi bi-plus-circle text-success"></i>
                    Tambah Sampel Baru
                    <small class="text-muted fw-normal ms-1">(Gelas A, Gelas B, dst)</small>
                </h6>
                <form method="POST" action="{{ route('samples.store', $panelTest) }}">
                    @csrf
                    <div class="row g-2">
                        <div class="col-md-3">
                            <label class="form-label small fw-medium">
                                Nama <span class="text-danger">*</span>
                            </label>
                            <input type="text" name="name"
                                class="form-control form-control-sm"
                                placeholder="Gelas A" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label small fw-medium">Kode</label>
                            <input type="text" name="code"
                                class="form-control form-control-sm"
                                placeholder="Opsional">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small fw-medium">Keterangan</label>
                            <input type="text" name="description"
                                class="form-control form-control-sm"
                                placeholder="Opsional">
                        </div>
                        @if($panelTest->samples->count() > 0)
                        <div class="col-md-2">
                            <label class="form-label small fw-medium">
                                <i class="bi bi-files text-warning"></i> Salin dari
                            </label>
                            <select name="copy_from_sample_id"
                                class="form-select form-select-sm">
                                <option value="">-- Tidak --</option>
                                @foreach($panelTest->samples as $s)
                                <option value="{{ $s->id }}">
                                    {{ $s->name }} ({{ $s->questions->count() }} soal)
                                </option>
                                @endforeach
                            </select>
                        </div>
                        @endif
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-success btn-sm w-100">
                                <i class="bi bi-plus-lg"></i> Tambah
                            </button>
                        </div>
                    </div>
                    @if($panelTest->samples->count() > 0)
                    <div class="mt-2 p-2 rounded" style="background:#f0fdf4;border:1px solid #bbf7d0">
                        <small class="text-success">
                            <i class="bi bi-lightbulb"></i>
                            <strong>Tips:</strong> Pilih "Salin dari" untuk menyalin pertanyaan otomatis!
                        </small>
                    </div>
                    @endif
                </form>
            </div>
        </div>

    </div>
</div>

@endsection

@push('scripts')
<script>
function toggleOptions(sampleId) {
    const type  = document.getElementById('type-' + sampleId).value;
    const field = document.getElementById('options-' + sampleId);
    if (field) field.style.display = type === 'multiple_choice' ? 'block' : 'none';
}

function toggleGeneralOptions() {
    const type  = document.getElementById('generalType').value;
    const field = document.getElementById('generalOptionsField');
    if (field) field.style.display = type === 'multiple_choice' ? 'block' : 'none';
}
</script>
@endpush
