<?php

namespace App\Http\Controllers\Admin;

use App\Models\Survey;
use App\Http\Controllers\Controller;

use App\Models\Question;
use App\Models\Response;
use Illuminate\Http\Request;

class StatsController extends Controller
{
    public function showStats($id)
    {
        $survey = Survey::with(['sections.questions.options', 'sections.questions.answers'])->findOrFail($id);

        $totalSurveyRespondents = \App\Models\Response::where('survey_id', $id)->count();
        $totalSurveyQuestions = \App\Models\Question::whereHas('section', function ($q) use ($id) {
            $q->where('survey_id', $id);
        })->count();

        $results = [];

        foreach ($survey->sections as $section) {
            foreach ($section->questions as $question) {
                
                $totalRespondents = $question->answers->count();
                $stats = [];
                $allAnswers = $question->answers->pluck('answer_text')->map(fn($item) => trim($item))->toArray();

                // HANDLE TEXT QUESTIONS
                if ($question->type === 'text') {
                     $results[$question->id] = [
                        'question' => $question->question_text,
                        'type' => 'text',
                        'total' => $totalRespondents,
                        'data' => array_filter($allAnswers) // Filter empty answers if any
                    ];
                    continue; // Skip the rest of the loop (chart logic)
                }

                // HANDLE RADIO/CHECKBOX (EXISTING LOGIC)
                foreach ($question->options as $option) {
                    $optionLabel = trim($option->option_text);
                    $count = 0;
                    foreach ($allAnswers as $ans) {
                        if ($ans === $optionLabel) {
                            $count++;
                        }
                    }

                    $stats[] = [
                        'label' => $optionLabel,
                        'count' => $count,
                        'percentage' => $totalRespondents > 0 ? round(($count / $totalRespondents) * 100, 1) : 0
                    ];
                }

                $optionTexts = $question->options->pluck('option_text')->map(fn($item) => trim($item))->toArray();
                $othersCount = 0;
                $otherAnswersList = [];

                foreach ($allAnswers as $ans) {
                    if (!in_array($ans, $optionTexts)) {
                        $othersCount++;
                        // Clean up "Lain-lain: " prefix if exists (based on public view logic)
                        $cleanAns = str_replace("Lain-lain: ", "", $ans);
                        $otherAnswersList[] = $cleanAns;
                    }
                }

                if ($question->allow_other_option && $othersCount > 0) {
                    $stats[] = [
                        'label' => 'Lain-lain',
                        'count' => $othersCount,
                        'percentage' => $totalRespondents > 0 ? round(($othersCount / $totalRespondents) * 100, 1) : 0
                    ];
                }

                $results[$question->id] = [
                    'question' => $question->question_text,
                    'type' => 'chart', // Mark as chart
                    'total' => $totalRespondents,
                    'data' => $stats,
                    'other_answers' => $otherAnswersList
                ];
            }
        }

        return view('admin.surveys.statistics', compact('survey', 'results', 'totalSurveyRespondents', 'totalSurveyQuestions'));
    }

    public function printStats($id)
    {
        $survey = Survey::with(['sections.questions.options', 'sections.questions.answers'])->findOrFail($id);

        $totalSurveyRespondents = \App\Models\Response::where('survey_id', $id)->count();
        $totalSurveyQuestions = \App\Models\Question::whereHas('section', function ($q) use ($id) {
            $q->where('survey_id', $id);
        })->count();

        $results = [];

        foreach ($survey->sections as $section) {
            foreach ($section->questions as $question) {
                
                $totalRespondents = $question->answers->count();
                $stats = [];
                $allAnswers = $question->answers->pluck('answer_text')->map(fn($item) => trim($item))->toArray();

                // HANDLE TEXT QUESTIONS
                if ($question->type === 'text') {
                     $results[$question->id] = [
                        'question' => $question->question_text,
                        'type' => 'text',
                        'total' => $totalRespondents,
                        'data' => array_filter($allAnswers) // Filter empty answers if any
                    ];
                    continue; 
                }

                // HANDLE RADIO/CHECKBOX (EXISTING LOGIC)
                foreach ($question->options as $option) {
                    $optionLabel = trim($option->option_text);
                    $count = 0;
                    foreach ($allAnswers as $ans) {
                        if ($ans === $optionLabel) {
                            $count++;
                        }
                    }

                    $stats[] = [
                        'label' => $optionLabel,
                        'count' => $count,
                        'percentage' => $totalRespondents > 0 ? round(($count / $totalRespondents) * 100, 1) : 0
                    ];
                }

                $optionTexts = $question->options->pluck('option_text')->map(fn($item) => trim($item))->toArray();
                $othersCount = 0;
                $otherAnswersList = [];

                foreach ($allAnswers as $ans) {
                    if (!in_array($ans, $optionTexts)) {
                        $othersCount++;
                        // Clean up "Lain-lain: " prefix if exists
                        $cleanAns = str_replace("Lain-lain: ", "", $ans);
                        $otherAnswersList[] = $cleanAns;
                    }
                }

                if ($question->allow_other_option && $othersCount > 0) {
                    $stats[] = [
                        'label' => 'Lain-lain',
                        'count' => $othersCount,
                        'percentage' => $totalRespondents > 0 ? round(($othersCount / $totalRespondents) * 100, 1) : 0
                    ];
                }

                $results[$question->id] = [
                    'question' => $question->question_text,
                    'type' => 'chart', 
                    'total' => $totalRespondents,
                    'data' => $stats,
                    'other_answers' => $otherAnswersList
                ];
            }
        }

        return view('admin.surveys.print_statistics', compact('survey', 'results', 'totalSurveyRespondents', 'totalSurveyQuestions'));
    }
}
