<?php

namespace App\Http\Controllers;

use App\Models\KuesionerLearningStyle;
use App\Models\KuesionerMetakognitif;
use App\Models\Instruksi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MateriController extends Controller
{
    public function getListInstruction($style = null)
    {
        $currentRoute = request()->route()->getName();
        $styleMap = [
            'materi-auditory' => 'auditory',
            'materi-kinesthetic' => 'kinesthetic',
            'materi-read/write' => 'read_write',
            'materi-visual' => 'visual',
            'materi-multimodal' => 'multimodal',
        ];

        $style = $style ?? ($styleMap[$currentRoute] ?? 'kinesthetic');

        $kuesionerls = KuesionerLearningStyle::where('email', Auth::user()->email)->first();
        $kuesionermeta = KuesionerMetakognitif::where('category', Auth::user()->category_meta)->first();

        $instruksi = Instruksi::where('id_lstyle', $kuesionerls->id_lstyle)
                              ->where('lv_meta', $kuesionermeta->lv_meta)
                              ->get();

        Log::info('Data Instruksi', [
            'style' => $style,
            'instruksi' => $instruksi->pluck('instruksi')->toArray()
        ]);

        $styleTitles = [
            'auditory' => 'Auditory',
            'kinesthetic' => 'Kinesthetic',
            'read_write' => 'Read/Write',
            'visual' => 'Visual',
            'multimodal' => 'Multimodal',
        ];

        $helpInstructions = [
            "<h4>Selamat datang di Materi {$styleTitles[$style]}!</h4><p>Aku akan memberitahu kamu instruksi belajar materi {$styleTitles[$style]}.</p>"
        ];

        if ($instruksi->isNotEmpty()) {
            foreach ($instruksi as $item) {
                $helpInstructions[] = "<p>" . htmlspecialchars($item->instruksi, ENT_QUOTES, 'UTF-8') . "</p>";
            }
        } else {
            $helpInstructions[] = "<p>Tidak ada instruksi khusus untuk gaya belajar dan tingkat metakognitif kamu saat ini.</p>";
        }

        Log::info('Help Instructions', [
            'style' => $style,
            'helpInstructions' => $helpInstructions
        ]);

        $view = "main.page.materi.materi_{$style}";

        if ($style === 'read_write') {
            $view = 'main.page.materi.materi_readwrite';
        }

        return view($view, compact('instruksi', 'helpInstructions'));
    }
}