<?php

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

use URL;

use Auth;
use Uuid;
use Alert;
use Crypt;
use GuzzleHttp\Client;

use App\Models\Periode;
use App\Models\Reviewer;
use App\Models\JenisMonev;
use Illuminate\Http\Request;
use App\Models\ReviewerMonev;
use App\Models\DaftarProposal;
use App\Models\JadwalKegiatan;
use App\Models\ProposalLuaran;
use Illuminate\Support\Carbon;
use App\Models\ReviewerProposal;
use App\Models\ReviewerMonevDetil;
use App\Models\DaftarProposalMonev;
use App\Models\JenisPenilaianMonev;
use App\Http\Controllers\Controller;
use App\Models\ReviewerProposalDetil;

class DaftarMonevController extends Controller
{
    private const periode_id          = '9857a29d-521f-413a-b811-94cda7b45897';

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

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

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

    public function index($id)
    {
        $periode    = Periode::where('status', 1)->first();
        $reqPeriodeId = $periode->periode_id;

        $jenis_monev = JenisMonev::select('nama')->where('jenis_monev_id', Crypt::decrypt($id))->first();
        $jadwal   = JadwalKegiatan::where('periode_id', $reqPeriodeId)->where('nama',$jenis_monev->nama)->first();
        $data = [
            'id'=> $id,
            'jadwal'=> $jadwal,
        ];
        return view('backend.reviewer.monev.index', compact('data'))->withTitle($jenis_monev->nama);
    }

    /* AJAX request */
    public function getData(Request $request){

        ## 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
        $statementGlobal = " 1=1 AND (NIDN_REVIEWER_ID_1 = '".$this->rBiodata->noidentitas."' OR NIDN_REVIEWER_ID_2 = '".$this->rBiodata->noidentitas."')";
        $totalRecords = DaftarProposalMonev::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $statement = " AND (UPPER(JUDUL) LIKE '%".$searchValue."%') ";

        $totalRecordswithFilter =   DaftarProposalMonev::select('count(1) as allcount')
                                    ->whereRaw($statementGlobal.$statement)->count();

        // Fetch records
        $records = DaftarProposalMonev::orderBy($columnName,$columnSortOrder)
            ->whereRaw($statementGlobal.$statement)
            ->select('*')
            ->skip($start)
            ->take($rowperpage)
            ->get();

        $data_arr = array();

        foreach($records as $record){
            $monev_internal_id = $record->monev_internal_id;
            $proposal_id = $record->proposal_id;
            $jenis_id = $record->jenis_id;
            $kode = $record->kode;
            $jenis_pkm = $record->jenis_pkm;
            $judul = $record->judul;
            $nilai_1= $record->nilai_1;
            $nilai_2 = $record->nilai_2;
            $folder= $record->folder;
            $upload_dokumen = $record->upload_dokumen;
            $upload_logbook = $record->upload_logbook;
            $identitas_ketua = str_replace('###', '<br>', $record->identitas_ketua);
            $identitas_dospem = str_replace('###', '<br>', $record->identitas_dospem);

            $url_logbook = "https://statik.unesa.ac.id/simpkm/monev/".$folder."/logbook"."/".$upload_logbook;
            $url_kemajuan = "https://statik.unesa.ac.id/simpkm/monev/".$folder."/kemajuan"."/".$upload_dokumen;

            $url_luaran = URL::to("reviewer/monev-internal-luaran/".Crypt::encrypt($proposal_id));

            $logbook = $laporan_kemajuan = '<span class="badge bg-danger">Belum Diunggah.</span>';
            if(isset($upload_logbook))
                $logbook = '<a href="#" target="_blank" class="btn btn-primary btn-sm waves-effect waves-light" role="button">Lihat <i class="fas fa-search"></i></a>';

            if(isset($upload_dokumen))
                $laporan_kemajuan = '<a href="'.$url_kemajuan.'" target="_blank" class="btn btn-primary btn-sm waves-effect waves-light" role="button">Lihat <i class="fas fa-search"></i></a>';
            $laporan_luaran = '<a href="'.$url_luaran.'" class="btn btn-primary btn-sm waves-effect waves-light" role="button">Lihat <i class="fas fa-search"></i></a>';

            $urut = DB::select("select ambil_data_reviewer_monev('".$this->rBiodata->noidentitas."', '".$monev_internal_id."', '1')")[0]->ambil_data_reviewer_monev;

            $status_nilai = DB::select("select ambil_data_reviewer_monev('".$this->rBiodata->noidentitas."', '".$monev_internal_id."', '2')")[0]->ambil_data_reviewer_monev;

            $status_administrasi = DB::select("select ambil_data_reviewer_monev('".$this->rBiodata->noidentitas."', '".$monev_internal_id."', '3')")[0]->ambil_data_reviewer_monev;

            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($monev_internal_id)."', '1')";
                $tidak_lolos = "confirmFinal('".Crypt::encrypt($monev_internal_id)."', '2')";
                $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/monev-internal/".Crypt::encrypt($monev_internal_id)."/edit");

            if($status_nilai > 0)
            {
                if($urut == '1')
                    $aksi = '<h4>'.$nilai_1.'</h4>';
                elseif($urut == '2')
                    $aksi = '<h4>'.$nilai_2.'</h5>';
            }
            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>';
            }

            $data_arr[] = array(
                "monev_internal_id" => $monev_internal_id,
                "kode" => $kode,
                "identitas_ketua" => $identitas_ketua,
                "identitas_dospem" => $identitas_dospem,
                "jenis_pkm" => $jenis_pkm,
                "judul" => $judul,
                "status" => $status,
                "logbook" => $logbook,
                "laporan_kemajuan" => $laporan_kemajuan,
                "laporan_luaran" => $laporan_luaran,
                "aksi" => $aksi
            );
        }

        $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_monev_id');
        $jenis_monev_id = $request->input('jenis_monev_id');
        $data['komentar'] = $request->input('komentar');

        $reviewer_monev = ReviewerMonev::findOrFail($id);
        $reviewer_monev->update($data);

        $delete = ReviewerMonevDetil::where('reviewer_monev_id', $id)->delete($id);

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

            ReviewerMonevDetil::create($data);
        }

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

        return redirect()->action([DaftarMonevController::class, 'index'], ['id' => Crypt::encrypt($jenis_monev_id)]);
    }

    public function show($id)
    {
        $reqId = decrypt($id);

        $luaran = ProposalLuaran::where('proposal_id', $reqId)->get();
        $proposal = DaftarProposal::where('proposal_id', $reqId)->first();

        $data = [
            'luaran'=> $luaran,
            'proposal'=> $proposal,
        ];
        return view('backend.reviewer.monev.luaran', compact('data'))->withTitle('Data Luaran');
    }

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

        $monev = DaftarProposalMonev::where('monev_internal_id', decrypt($id))->first();
        $title      = 'Penilaian '.$monev->jenis_monev_desc;
        $reviewer_monev = ReviewerMonev::with('rReviewerDetil')->where('monev_internal_id', decrypt($id))->where('urut', $urut)->first();
        $komponen = JenisPenilaianMonev::where('jenis_id', $monev->jenis_id)->get();

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

        $data = [
            'title'     => $title,
            'monev'  => $monev,
            'komponen' => $komponen,
            'reviewer_monev' => $reviewer_monev,
            'detil' => $detil
        ];

        return view('backend.reviewer.monev.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.",
            ]);
        }
    }
}
