<?php

namespace App\Http\Controllers\Reviewer;
use DB;

use URL;

use Auth;
use Uuid;
use Alert;
use Crypt;
use App\Models\JenisPenilaianMonev;

use GuzzleHttp\Client;
use App\Models\Periode;
use App\Models\Reviewer;
use Illuminate\Http\Request;
use App\Models\DaftarProposal;
use App\Models\SeleksiBelmawa;
use Illuminate\Support\Carbon;
use App\Models\ReviewerProposal;
use App\Http\Controllers\Controller;
use App\Models\DaftarProposalBelmawa;
use App\Models\ReviewerProposalDetil;

class DaftarSeleksiController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware(function ($request, $next) {
            $this->rBiodata = Auth::user()->rBiodata;

            return $next($request);
        });
    }

    public function index()
    {
        $periode    = Periode::query()->get();
        return view('backend.reviewer.seleksi.index', compact('periode'))->withTitle('Daftar Proposal Seleksi Internal');
    }

    /* AJAX request */
    public function getData(Request $request){
        $noidentitas = $this->rBiodata->noidentitas;

        // parameter
        $administrasi = $request->get('administrasi');
        $status = $request->get('status');
        $tahun= $request->get('tahun');

        if($tahun == '0')
            $tahun = date('Y');

        ## Read value
        $draw = $request->get('draw');
        $start = $request->get("start");
        $rowperpage = $request->get("length"); // Rows display per page

        $columnIndex_arr = $request->get('order');
        $columnName_arr = $request->get('columns');
        $order_arr = $request->get('order');
        $search_arr = $request->get('search');

        $columnIndex = $columnIndex_arr[0]['column']; // Column index
        $columnName = $columnName_arr[$columnIndex]['data']; // Column name
        $columnSortOrder = $order_arr[0]['dir']; // asc or desc
        $searchValue = strtoupper($search_arr['value']); // Search value

        // Total records
        $statement = " AND (UPPER(JUDUL) LIKE ''%".$searchValue."%'') ";
        // $statementGlobal = " 1=1 AND (NIDN_REVIEWER_ID_1 = '".$noidentitas."' OR NIDN_REVIEWER_ID_2 = '".$noidentitas."')";
        $statementGlobal = " ";

        if($administrasi != "0")
        {
            // dikurang 1 karena di view mulai dari 0 sedangkan 0 itu menunggu persetujuan
            $administrasi = $administrasi - 1;
            $statementGlobal .= " AND (ambil_data_reviewer_proposal ( ''".$noidentitas."'', proposal_id, ''3'' ) = ''".$administrasi."'')";
        }

        if($status != "0")
        {
            // dikurang 1 karena di view mulai dari 0 sedangkan 0 itu menunggu persetujuan
            $status = $status - 1;
            $statementGlobal .= " AND (ambil_data_reviewer_proposal ( ''".$noidentitas."'', proposal_id, ''2'' ) = ''".$status."'')";
        }

        if($tahun != "0")
        {
            $statementGlobal .= " AND PERIODE = ''".$tahun."''";
        }

        // $totalRecords = DaftarProposal::select('count(1) as allcount')->whereRaw($statementGlobal)->count();

        $totalRecords = collect(DB::select("select 1 as allcount from vw_daftar_proposal('".$statementGlobal."', '".$noidentitas."') "))->count();

        // $totalRecordswithFilter =   DaftarProposal::select('count(1) as allcount')->whereRaw($statementGlobal.$statement)->count();
        $totalRecordswithFilter =   collect(DB::select("select 1 as allcount from vw_daftar_proposal('".$statementGlobal.$statement."', '".$noidentitas."') "))->count();
        // echo "select 1 as allcount from vw_daftar_proposal('".$statementGlobal.$statement."', '".$noidentitas."')"; exit;
        // Fetch records
        // $records = DaftarProposal::orderBy($columnName,$columnSortOrder)
        //     ->whereRaw($statementGlobal.$statement)
        //     ->select('daftar_proposal.*')
        //     ->skip($start)
        //     ->take($rowperpage)
        //     ->get();
        $records = collect(DB::select("select * from vw_daftar_proposal('".$statementGlobal.$statement."', '".$noidentitas."') ORDER BY ".$columnName." ".$columnSortOrder))
        ->skip($start)
        ->take($rowperpage);

        $data_arr = array();
        $hitung = 1;
        foreach($records as $record){
            $proposal_id = $record->proposal_id;
            $jenis_id = $record->jenis_id;
            $kode = $record->kode;
            $jenis_pkm = $record->jenis_pkm;
            $judul = $record->judul;

            $nilai_1= DB::select("select ambil_jumlah_penilaian_seleksi('".$record->reviewer_proposal_id_1."')")[0]->ambil_jumlah_penilaian_seleksi;

            $nilai_2= DB::select("select ambil_jumlah_penilaian_seleksi('".$record->reviewer_proposal_id_2."')")[0]->ambil_jumlah_penilaian_seleksi;

            $url = "https://statik.unesa.ac.id/simpkm/proposal/".$record->periode."/".$record->upload_dokumen;

            $urut = DB::select("select ambil_data_reviewer_proposal('".$noidentitas."', '".$proposal_id."', '1')")[0]->ambil_data_reviewer_proposal;

            $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;

            $proposal = '<a href="'.$url.'" target="_blank" class="btn btn-primary btn-sm waves-effect waves-light" role="button"><i class="fas fa-search"></i></a>';
            if($status_nilai > 0 || $status_administrasi == '2')
                $status = '<span class="badge bg-success">Sudah dinilai</span>';
            else
                $status = '<span class="badge bg-danger">Belum dinilai</span>';

            $aksi = '';

            if($status_administrasi == '1')
                $administrasi = '<span class="badge bg-success">Lolos</span>';
            elseif($status_administrasi == '2')
                $administrasi = '<span class="badge bg-danger">Tidak Lolos</span>';
            else
            {
                $lolos = "confirmFinal('".Crypt::encrypt($proposal_id)."', '1', '".$hitung."')";
                $tidak_lolos = "confirmFinal('".Crypt::encrypt($proposal_id)."', '2', '".$hitung."')";
                $administrasi = '<td class="table-action">
                                    <a href="#!" class="btn btn-icon-sm btn-success btn-sm" onclick="'.$lolos.'">Lolos ?</a>
                                    <a href="#!" class="btn btn-icon-sm btn-danger btn-sm" onclick="'.$tidak_lolos.'">Tidak ?</a>
                                </td>';
            }
            $nilai = URL::to("reviewer/seleksi-internal/".Crypt::encrypt($proposal_id)."/edit");

            if($status_administrasi != 0)
            {
                if($status_nilai == 1)
                {
                    if($urut == '1')
                        $aksi = '<h4>'.$nilai_1.'</h4>';
                    elseif($urut == '2')
                        $aksi = '<h4>'.$nilai_2.'</h5>';
                }
                else
                {
                    if($status_administrasi == '2')
                        $aksi = '<h4>0</h4>';
                    else
                        $aksi = '<a href="'.$nilai.'" class="btn btn-icon-sm btn-warning btn-sm">Beri nilai<i class="fas fa-arrow-alt-circle-right"></i></a>';
                }
            }
            else
                $aksi = '<span class="badge bg-info">Administrasi belum dipilih</span>';

            $data_arr[] = array(
                "DT_RowId" => 'row_'.$hitung,
                "proposal_id" => $proposal_id,
                "kode" => $kode,
                "jenis_pkm" => $jenis_pkm,
                "judul" => $judul,
                "status" => $status,
                "proposal" => $proposal,
                "administrasi" => $administrasi,
                "aksi" => $aksi
            );
            $hitung++;
        }

        $response = array(
            "draw" => intval($draw),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalRecordswithFilter,
            "aaData" => $data_arr
        );

        echo json_encode($response);
        exit;
    }

    public function create()
    {
    }

    public function store(Request $request)
    {
        $id = $request->input('reviewer_proposal_id');
        $data['komentar'] = $request->input('komentar');

        $reviewer_proposal = ReviewerProposal::findOrFail($id);
        $reviewer_proposal->update($data);

        $delete = ReviewerProposalDetil::where('reviewer_proposal_id', $id)->delete($id);

        for($i=0; $i<count($request->jenis_penilaian_id); $i++)
        {
            $uuid = Uuid::generate();
            $data['reviewer_proposal_detil_id'] = $uuid;
            $data['reviewer_proposal_id'] = $id;
            $data['jenis_penilaian_monev_id'] = $request->jenis_penilaian_id[$i];
            $data['skor'] = $request->skor[$i];

            ReviewerProposalDetil::create($data);
        }

        Alert::success('Data berhasil disimpan.')->persistent('Ok');

        return redirect()->route('reviewer.seleksi-internal.index');
    }

    public function show($id)
    {

    }

    public function edit($id)
    {
        $urut = DB::select("select ambil_data_reviewer_proposal('".$this->rBiodata->noidentitas."', '".decrypt($id)."', '1')")[0]->ambil_data_reviewer_proposal;

        $title      = 'Penilaian Proposal Seleksi Internal';
        $proposal = DaftarProposal::where('proposal_id', decrypt($id))->first();
        $reviewer_proposal = ReviewerProposal::with('rReviewerProposalDetil')->where('proposal_id', decrypt($id))->where('urut', $urut)->first();
        $komponen = JenisPenilaianMonev::where('jenis_id', $proposal->jenis_id)->get();

        $detil = array();
        foreach($reviewer_proposal->rReviewerProposalDetil as $res => $val)
        {
            $detil[$val->jenis_penilaian_monev_id] = $val->skor;
        }

        $data = [
            'title'     => $title,
            'proposal'  => $proposal,
            'komponen' => $komponen,
            'reviewer_proposal' => $reviewer_proposal,
            'detil' => $detil
        ];

        return view('backend.reviewer.seleksi.nilai', $data);
    }

    public function update(Request $request, $id)
    {

    }

    public function destroy($id)
    {

    }

    public function approval($id, $status)
    {
        try {
            $urut = DB::select("select ambil_data_reviewer_proposal('".$this->rBiodata->noidentitas."', '".decrypt($id)."', '1')")[0]->ambil_data_reviewer_proposal;

            $delete = ReviewerProposal::where('proposal_id', Crypt::decrypt($id))->where('urut', $urut)->update(['status_administrasi'=>$status]);

            if ($delete) {
                if($status == '1')
                {
                    $status = 'success';
                    $message = "Proposal Seleksi Internal Lolos Administrasi.";
                }
                elseif($status == '2')
                {
                    $status = 'success';
                    $message = "Proposal Seleksi Internal Tidak Lolos Administrasi.";
                }
            }
            else{
                $status = 'error';
                $message = "Proposal Seleksi Internal tidak ada.";
            }

            return response()->json([
                'status' => $status,
                'message' => $message,
            ]);

        } catch (\Exception $id) {
            return response()->json([
                'status' => 'error',
                'message' => "Data gagal diproses.",
            ]);
        }
    }
}
