<?php

namespace App\Http\Controllers\Admin;

use App\Models\Survey;
use App\Models\Section;
use App\Models\Question;
use App\Models\Option;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;

class SurveyController extends Controller
{

    public function index(Request $request)
    {
        $query = Survey::with('user', 'questions', 'responses');

        if ($request->filled('search')) {
            $s = $request->search;
            $query->where('title', 'like', "%$s%");
        }

        $surveys = $query->latest()->paginate(20);

        return view('admin.surveys.index', compact('surveys'));
    }

    public function create()
    {
        return view('admin.surveys.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'perincian' => 'nullable|string',
            'date' => 'required|date',
            'sections' => 'required|array|min:1',
            'sections.*.title' => 'required|string',
            'sections.*.questions' => 'required|array|min:1',
            'sections.*.questions.*.text' => 'required|string',
            'sections.*.questions.*.type' => 'required|in:radio,text,checkbox',
            'sections.*.questions.*.allow_other_option' => 'nullable|boolean',
            'sections.*.questions.*.options' => 'required_if:sections.*.questions.*.type,radio|required_if:sections.*.questions.*.type,checkbox|array',
            'sections.*.questions.*.options.*' => 'required|string',
        ]);

        try {
            DB::beginTransaction();

            $survey = Survey::create([
                'title' => $request->title,
                'perincian' => $request->perincian,
                'date' => $request->date,
                'user_id' => Auth::id(),
            ]);


            foreach ($request->sections as $sectionIndex => $sectionData) {
                $section = $survey->sections()->create([
                    'title' => $sectionData['title'],
                    'description' => $sectionData['description'] ?? null,
                    'order' => $sectionIndex,
                ]);


                foreach ($sectionData['questions'] as $questionIndex => $questionData) {
                    $question = $section->questions()->create([
                        'question_text' => $questionData['text'],
                        'type' => $questionData['type'],
                        'allow_other_option' => $questionData['allow_other_option'] ?? false,
                        'order' => $questionIndex,
                    ]);


                    if (isset($questionData['options'])) {
                        foreach ($questionData['options'] as $optionText) {
                            $question->options()->create([
                                'option_text' => $optionText,
                            ]);
                        }
                    }
                }
            }

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error($e->getMessage());
            return redirect()->back()->with('error', 'Gagal menyimpan borang. Sila cuba lagi.')->withInput();
        }

        return redirect()->route('admin.surveys.index')->with('success', 'Borang berjaya dicipta.');
    }

    public function edit(Survey $survey)
    {
        $survey->load('sections.questions.options');

        $sections_with_questions = $survey->sections->map(function ($section) {
            return [
                'title' => $section->title,
                'description' => $section->description,
                'questions' => $section->questions->map(function ($q) {
                    return [
                        'text' => $q->question_text,
                        'type' => $q->type,
                        'allow_other_option' => (bool) $q->allow_other_option,
                        'options' => $q->options->map(function ($opt) {
                            return ['text' => $opt->option_text];
                        })->toArray(),
                    ];
                })->toArray(),
            ];
        })->toArray();

        return view('admin.surveys.edit', compact('survey', 'sections_with_questions'));
    }

    public function update(Request $request, Survey $survey)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'perincian' => 'nullable|string',
            'date' => 'required|date',
            'sections' => 'required|array|min:1',
            'sections.*.title' => 'required|string',
            'sections.*.questions' => 'required|array|min:1',
            'sections.*.questions.*.text' => 'required|string',
            'sections.*.questions.*.type' => 'required|in:radio,text,checkbox',
            'sections.*.questions.*.allow_other_option' => 'nullable|boolean',
            'sections.*.questions.*.options' => 'required_if:sections.*.questions.*.type,radio|required_if:sections.*.questions.*.type,checkbox|array',
            'sections.*.questions.*.options.*' => 'required|string',
        ]);

        try {
            DB::beginTransaction();

            $survey->update([
                'title' => $request->title,
                'perincian' => $request->perincian,
                'date' => $request->date,

            ]);

            foreach ($survey->sections as $oldSection) {
                foreach ($oldSection->questions as $oldQuestion) {

                    $oldQuestion->options()->delete();
                }

                $oldSection->questions()->delete();
            }

            $survey->sections()->delete();

            foreach ($request->sections as $sectionIndex => $sectionData) {
                $section = $survey->sections()->create([
                    'title' => $sectionData['title'],
                    'description' => $sectionData['description'] ?? null,
                    'order' => $sectionIndex,
                ]);

                foreach ($sectionData['questions'] as $questionIndex => $questionData) {
                    $question = $section->questions()->create([
                        'question_text' => $questionData['text'],
                        'type' => $questionData['type'],
                        'allow_other_option' => $questionData['allow_other_option'] ?? false,
                        'order' => $questionIndex,
                    ]);

                    if (isset($questionData['options']) && is_array($questionData['options'])) {
                        foreach ($questionData['options'] as $optionText) {
                            if (is_array($optionText)) {
                                $optionText = $optionText['text'] ?? '';
                            }
                            $question->options()->create([
                                'option_text' => $optionText,
                            ]);
                        }
                    }
                }
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Survey update failed: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Gagal kemaskini borang. Sila cuba lagi.')->withInput();
        }

        return redirect()->route('admin.surveys.index')->with('success', 'Borang berjaya dikemaskini.');
    }

    public function destroy(Survey $survey)
    {
        $survey->delete();
        return redirect()->route('admin.surveys.index')->with('success', 'Borang berjaya dihapuskan.');
    }

}

