<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CheckQuestionnaire
{
    public function handle(Request $request, Closure $next)
    {
        $userId = Auth::id();

        if (!$userId) {
            // Jika belum login, redirect ke login
            return redirect()->route('login');
        }

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

        // Jika data hasil tidak ada, atau semua nilai VARK kosong/0
        if (
            !$hasil || 
            (
                ($hasil->visual ?? 0) == 0 &&
                ($hasil->auditory ?? 0) == 0 &&
                ($hasil->readwrite ?? 0) == 0 &&
                ($hasil->kinesthetic ?? 0) == 0
            )
        ) {
            // Redirect ke halaman cek kuesioner
            // return redirect()->route('user.questionnaire.check')->with('error', 'Silakan isi kuesioner terlebih dahulu.');
            return redirect()->route('materi.index')->with('error', 'Silakan isi kuesioner terlebih dahulu.');
        }

        return $next($request);
    }
}
