<?php

namespace App\Http\Middleware;

use App\Models\Reviewer;
use App\Models\ReviewerProposal;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class NilaiSeleksiInternal
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $id = $request->route('seleksi_internal');
        $biodata = Auth::user()->rBiodata;
        $noidentitas = $biodata->noidentitas;
        $proposal_id = decrypt($id);

        $status_nilai = DB::select("select ambil_data_reviewer_proposal('".$noidentitas."', '".$proposal_id."', '2')")[0]->ambil_data_reviewer_proposal;
        $status_administrasi = DB::select("select ambil_data_reviewer_proposal('".$noidentitas."', '".$proposal_id."', '3')")[0]->ambil_data_reviewer_proposal;

        $reviewerProposal = ReviewerProposal::query()
        ->where('proposal_id', $proposal_id)
        ->whereHas('reviewer', function($query) use ($noidentitas){
            return $query->wherehas('biodata', function($query) use ($noidentitas){
                return $query->where('noidentitas', $noidentitas);
            });
        })
        ->first();

        if($reviewerProposal->revisi_nilai == 1){
            return $next($request);
        }

        if($status_administrasi != 0)
            {
                if($status_nilai != 1)
                {
                    if($status_administrasi != '2')
                        return $next($request);
                }
            }

        return redirect()->back();
    }
}
