<?php

namespace App\Http\Controllers\Backend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\Materi;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class MateriController extends Controller
{
    public function index()
    {
        $userId = Auth::id();

        $data = DB::table('hasil')->where('id_user', $userId)->first();

        if (!$data) {
            return view('backend.materipembelajaran', [
                'topStyles' => [],
                'isMultimodal' => false,
                'alternativeStyles' => [],
                'isEmpty' => true
            ]);
        }

        $styles = [
            'Visual' => $data->visual ?? 0,
            'Auditory' => $data->auditory ?? 0,
            'Read/ Write' => $data->readwrite ?? 0,
            'Kinesthetic' => $data->kinesthetic ?? 0,
        ];

        $maxValue = max($styles);
        $topStyles = array_keys($styles, $maxValue);
        $isMultimodal = count($topStyles) > 1;
        $alternativeStyles = array_diff(array_keys($styles), $topStyles);
        $isEmpty = empty(array_filter($styles));

        return view('backend.materipembelajaran', compact('topStyles', 'isMultimodal', 'alternativeStyles', 'isEmpty'));
    }

    public function showByStyle($style)
    {
        $userId = Auth::id();

        $hasil = DB::table('hasil')->where('id_user', $userId)->first();

        if (!$hasil) {
            return redirect()->route('user.questionnaire.check')->with('error', 'Silakan isi kuesioner terlebih dahulu untuk mengakses materi.');
        }

        $bladeMap = [
            'visual' => 'visual',
            'auditory' => 'auditory',
            'read-write' => 'readwrite',
            'kinesthetic' => 'kinesthetic',
        ];

        $style = strtolower($style);

        if (!array_key_exists($style, $bladeMap)) {
            abort(404);
        }

        $id_style_map = [
            'visual' => 1,
            'auditory' => 2,
            'read-write' => 3,
            'kinesthetic' => 4,
        ];

        $id_style = $id_style_map[$style];

        $materi = DB::table('materi')
            ->where('id_style', $id_style)
            ->orderBy('id_materi')
            ->select('id_materi', 'konten', 'audio', 'teks', 'rangkuman')
            ->get();

        return view('backend.materi.' . $bladeMap[$style], compact('materi'));
    }

    public function visual($id_materi)
    {
        $userId = Auth::id();
        $hasil = DB::table('hasil')->where('id_user', $userId)->first();
        if (!$hasil || ($hasil->visual == 0 && $hasil->auditory == 0 && $hasil->readwrite == 0 && $hasil->kinesthetic == 0)) {
            return redirect('/materi')->with('error', 'Silakan isi kuesioner terlebih dahulu.');
        }

        $id_style = 1;

        $materi = DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->first();

        if (!$materi) {
            abort(404, 'Materi tidak ditemukan');
        }

        $next = DB::table('materi')->where('id_style', $id_style)->where('id_materi', '>', $id_materi)->orderBy('id_materi')->first();
        $prev = DB::table('materi')->where('id_style', $id_style)->where('id_materi', '<', $id_materi)->orderByDesc('id_materi')->first();

        $instruksi = DB::table('instruksi')->where('id_style', $id_style)->orderBy('id_instruksi')->pluck('instruksi');

        return view('backend.materi.visual', compact('materi', 'next', 'prev', 'instruksi'));
    }

    public function auditory($id_materi)
    {
        $userId = Auth::id();
        $hasil = DB::table('hasil')->where('id_user', $userId)->first();
        if (!$hasil || ($hasil->visual == 0 && $hasil->auditory == 0 && $hasil->readwrite == 0 && $hasil->kinesthetic == 0)) {
            return redirect('/materi')->with('error', 'Silakan isi kuesioner terlebih dahulu.');
        }

        $id_style = 2;

        $materi = DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->first();

        if (!$materi) {
            abort(404, 'Materi tidak ditemukan');
        }

        $next = DB::table('materi')->where('id_style', $id_style)->where('id_materi', '>', $id_materi)->orderBy('id_materi')->first();
        $prev = DB::table('materi')->where('id_style', $id_style)->where('id_materi', '<', $id_materi)->orderByDesc('id_materi')->first();

        $instruksi = DB::table('instruksi')->where('id_style', $id_style)->orderBy('id_instruksi')->pluck('instruksi');

        return view('backend.materi.auditory', compact('materi', 'next', 'prev', 'instruksi'));
    }

    public function readwrite($id_materi)
    {
        $userId = Auth::id();
        $hasil = DB::table('hasil')->where('id_user', $userId)->first();
        if (!$hasil || ($hasil->visual == 0 && $hasil->auditory == 0 && $hasil->readwrite == 0 && $hasil->kinesthetic == 0)) {
            return redirect('/materi')->with('error', 'Silakan isi kuesioner terlebih dahulu.');
        }

        $id_style = 3;

        $materi = DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->first();

        if (!$materi) {
            abort(404, 'Materi tidak ditemukan');
        }

        $next = DB::table('materi')->where('id_style', $id_style)->where('id_materi', '>', $id_materi)->orderBy('id_materi')->first();
        $prev = DB::table('materi')->where('id_style', $id_style)->where('id_materi', '<', $id_materi)->orderByDesc('id_materi')->first();

        $rangkuman = $hasil->rangkuman;
        $instruksi = DB::table('instruksi')->where('id_style', $id_style)->orderBy('id_instruksi')->pluck('instruksi');

        return view('backend.materi.readwrite', compact('materi', 'next', 'prev', 'rangkuman', 'instruksi'));
    }

    public function kinesthetic($id_materi)
    {
        $userId = Auth::id();
        $hasil = DB::table('hasil')->where('id_user', $userId)->first();
        if (!$hasil || ($hasil->visual == 0 && $hasil->auditory == 0 && $hasil->readwrite == 0 && $hasil->kinesthetic == 0)) {
            return redirect('/materi')->with('error', 'Silakan isi kuesioner terlebih dahulu.');
        }

        $id_style = 4;

        $materi = DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->first();

        if (!$materi) {
            abort(404, 'Materi tidak ditemukan');
        }

        $instruksi = DB::table('instruksi')->where('id_style', $id_style)->orderBy('id_instruksi')->pluck('instruksi');

        return view('backend.materi.kinesthetic', compact('materi', 'instruksi'));
    }

    public function submitRangkuman(Request $request)
    {
        $request->validate([
            'rangkuman' => 'required|string|max:10000',
        ]);

        $id_user = auth()->id();

        DB::table('hasil')->updateOrInsert(
            ['id_user' => $id_user],
            ['rangkuman' => $request->rangkuman, 'updated_at' => now()]
        );

        return redirect()->back()->with('success', 'Rangkuman berhasil dikirim!');
    }

    public function submitKinesthetic(Request $request, $id_materi)
    {
        $id_style = 4;

        $materi = DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->first();

        if (!$materi) {
            return response()->json(['status' => 'error', 'output' => 'Materi tidak ditemukan.']);
        }

        $code = $request->input('code');

        $response = Http::post('https://emkc.org/api/v2/piston/execute', [
            'language' => 'java',
            'version' => '15.0.2',
            'files' => [
                ['name' => 'Main.java', 'content' => $code],
            ],
        ]);

        if (!$response->ok()) {
            return response()->json(['status' => 'error', 'output' => 'Gagal memanggil API Piston']);
        }

        $result = $response->json();

        function normalizeOutput($text) {
            $text = str_replace(["\r\n", "\r"], "\n", $text);
            $text = preg_replace("/[ \t]+/", " ", $text);
            $text = preg_replace("/ +\n/", "\n", $text);
            $text = preg_replace('/[\x00-\x1F\x7F\xA0\xAD\x{200B}-\x{200D}\x{FEFF}]/u', '', $text);
            return trim($text);
        }

        $output = normalizeOutput($result['run']['stdout'] ?? '');
        $expected = normalizeOutput($materi->outputkode);

        $isCorrect = $output === $expected;

        return response()->json([
            'status' => $isCorrect ? 'correct' : 'incorrect',
            'output' => $output,
            'expected' => $expected,
        ]);
    }
}
