<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Function\CalcController;
use App\Models\Personality;
use App\Models\Result;
use App\Models\Rule;
use App\Models\Statement;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class QuisionnareController extends Controller
{
    public function index(Request $request): View
    {
        $user = $request->user();

        $hasCompleteProfile = empty($user->student->nim) || empty($user->student->department_id) || empty($user->student->faculty);

        $hasStatement = Rule::count();

        return view('student.pages.quisionnare.index', compact('hasCompleteProfile', 'hasStatement'));
    }

    public function quest(): View
    {
        $quests = Statement::join('rules', 'statements.id', '=', 'rules.statement_id')
            ->orderByRaw('rules.rule_code ASC')
            ->whereRaw('rules.id = (select id from rules where statement_id = statements.id limit 1)')
            ->get();

        $hasStatement = Rule::count();

        return view('student.pages.quisionnare.quest', compact('quests', 'hasStatement'));
    }

    public function store(Request $request): RedirectResponse
    {
        // dd($request->all());
        //! Jika semua pernyataan dijawab tidak, kembalikan ke halaman sebelumnya
        // Mengambil semua input kecuali '_token'
        $inputValues = $request->except('_token');

        // Memeriksa apakah semua nilai adalah 'on'
        if (count(array_filter($inputValues, fn ($value) => $value !== 'on')) === 0) {
            return redirect()->route('student.quisionnare.start')->with('error', 'Hasil tes tidak dapat diidentifikasi, silahkan melakukan tes ulang');
        }

        $quests = Statement::orderBy('statement_code', 'asc')->get();

        // Inisialisasi array untuk menyimpan ID pernyataan yang dijawab
        $answeredQuestIds = [];

        // Loop melalui setiap pernyataan untuk memeriksa jawaban yang diinput
        foreach ($quests as $quest) {
            // Dapatkan nilai input untuk pernyataan saat ini
            $inputValue = $request->input($quest->statement_code);

            // Periksa apakah nilai input tidak kosong dan tidak sama dengan "on"
            if (!empty($inputValue) && $inputValue !== 'on') {
                // Jika dijawab, tambahkan ID pernyataan ke dalam array
                $answeredQuestIds[] = $quest->id;
            }
        }
        // dd($answeredQuestIds);

        $calc = new CalcController();

        $rulesQuery = $calc->getRulesData($answeredQuestIds);
        $rulesData = $calc->mapRulesData($rulesQuery);

        $statementData = $calc->getStatementData($rulesData);

        $personalitiesQuery = $calc->getPersonalitiesData();
        $personalitiesData = $calc->mapPersonalitiesData($personalitiesQuery);

        $result = $calc->processEvidence($rulesData, $personalitiesData);

        // dd($result);
        // calculate the result with dempster shafer theory
        // Menghitung total nilai
        // $total = array_sum($result);

        //? Ambil kode personality teratas
        // $topPersonalityCode = array_key_first($result);
        $arrayPersonalities = array_keys($result);

        // dd($arrayPersonalities);

        $firstPersonalityCode = $arrayPersonalities[0];
        if (count($arrayPersonalities) > 1) {
            $secondPersonalityCode = $arrayPersonalities[1];
        }
        if (count($arrayPersonalities) > 2) {
            $thirdPersonalityCode = $arrayPersonalities[2];
        }


        // dd($topPersonalityCode, $firstPersonalityCode, $secondPersonalityCode, $thirdPersonalityCode);

        $topPersonalityId = Personality::where('personality_code', $firstPersonalityCode)->first()->id;
        $secondPersonalityId = null;
        $thirdPersonalityId = null;

        //? Inisialisasi array untuk menyimpan nama personality dan nilai
        $personalityNames = [];
        $personalityValues = [];

        foreach ($result as $key => $value) {
            // Hitung persentase untuk setiap nilai
            $percentage = round($value, 3); //* Bulatkan ke tiga angka desimal
            $percentageRound = $percentage * 100; //* Ubah ke persen

            // Cari nama personality berdasarkan kode personality
            $personality = Personality::where('personality_code', $key)->first();

            // Periksa apakah personality ditemukan
            if ($personality) {
                // Jika ditemukan, simpan nama personality dan persentase ke dalam array
                $personalityNames[] = $personality->personality;
                $personalityValues[] = $percentageRound;
            }
        }
        // dd($result, $topPersonalityCode, $topPersonalityId, $personalityNames, $personalityValues);

        // dd($personalityValues);

        if (count($arrayPersonalities) > 1  && $personalityValues[1] > 0) {
            $secondPersonalityId = Personality::where('personality_code', $secondPersonalityCode)->first()->id;
        }

        if (count($arrayPersonalities) > 2 && $personalityValues[2] > 0) {
            $thirdPersonalityId = Personality::where('personality_code', $thirdPersonalityCode)->first()->id;
        }

        $overallPersonality = serialize($personalityNames);
        $overallScore = serialize($personalityValues);

        $result = Result::create([
            'user_id' => auth()->id(),
            'overall_personality' => $overallPersonality,
            'overall_score' => $overallScore,
        ]);

        $personalitiesToSync = [];

        if ($topPersonalityId) {
            $personalitiesToSync[] = $topPersonalityId;
        }

        if ($secondPersonalityId) {
            $personalitiesToSync[] = $secondPersonalityId;
        }

        if ($thirdPersonalityId) {
            $personalitiesToSync[] = $thirdPersonalityId;
        }

        $result->personality()->sync($personalitiesToSync);

        return redirect()->route('student.result');
    }
}
