<?php

namespace App\Http\Controllers\Operator;

use DB;
use URL;

use Auth;
use Uuid;
use Alert;
use Crypt;
use App\Models\User;
use GuzzleHttp\Client;

use App\Models\Periode;
use App\Models\Reviewer;
use App\Traits\LoginTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Authentication\LoginController;

class ReviewerController extends Controller
{
    use LoginTrait;
    public function index()
    {
        $periode    = Periode::query()->get();
        return view('backend.operator.reviewer.index', compact('periode'))->withTitle('Reviewer Seleksi Internal');
    }

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

        $jenis_monev_id = 'ba11c2b5-d65d-4360-9717-98e4fa9b9188';
        $tahun= $request->get('tahun');

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

        ## 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 = " STATUS_HAPUS = '0' ";
        $totalRecords = Reviewer::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $statement = " AND (UPPER(NAMA) LIKE '%".$searchValue."%') ";

        $statement .= " AND JENIS_MONEV_ID = '".$jenis_monev_id."'";

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

        // Fetch records
        $records = Reviewer::orderBy($columnName,$columnSortOrder)
            ->whereRaw($statementGlobal.$statement)
            ->select('reviewer.*')
            ->selectRaw("ambil_jumlah_reviewer_info_review(reviewer.reviewer_id, '1', '".$jenis_monev_id."', '0', '".$tahun."') jumlah_harus_review, ambil_jumlah_reviewer_info_review(reviewer.reviewer_id, '1', '".$jenis_monev_id."', '1', '".$tahun."') jumlah_sudah_review")
            ->skip($start)
            ->take($rowperpage)
            ->get();

        $data_arr = array();
        foreach($records as $record){
            $reviewer_id = $record->reviewer_id;
            $nama = $record->nama;
            $nidn = $record->nidn;
            $fakultas = $record->fakultas;
            $jumlah_harus_review = $record->jumlah_harus_review;
            $jumlah_sudah_review = $record->jumlah_sudah_review;

            $delete = "confirmDelete('".Crypt::encrypt($reviewer_id)."')";

            $data_arr[] = array(
                "reviewer_id" => $reviewer_id,
                "nama" => $nama,
                "nidn" => $nidn,
                "fakultas" => $fakultas,
                "jumlah_harus_review" => $jumlah_harus_review,
                "jumlah_sudah_review" => $jumlah_sudah_review,
                "aksi" => '<td class="table-action">
                                <a href="#!" class="btn btn-icon-sm btn-danger" onclick="'.$delete.'"><i class="fas fa-trash"></i></a>
                            </td>'
            );
        }

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

        echo json_encode($response);
        exit;
    }

    public function create()
    {
        return view('backend.operator.reviewer.create')->withTitle('Tambah Reviewer');
    }

    public function store(Request $request)
    {
        $periode    = Periode::where('status', 1)->first();

        $reqPeriodeId = $periode->periode_id;
        $reqJenisMonevId = 'ba11c2b5-d65d-4360-9717-98e4fa9b9188';

        $result = $this->login_reviewer($request->input('nidn'));

        $ada_data = Reviewer::where([
                            ['id_sdm', '=', $request->input('id_sdm')],
                            ['periode_id', '=', $reqPeriodeId],
                            ['jenis_monev_id', '=', $reqJenisMonevId],
                            ['status_hapus', '=', '0'],
                        ])->count();

        if($ada_data > 0)
        {
            return response()->json([
                'status' => 'error',
                'message' => 'Data reviewer sudah ada.',
            ]);
        }

        $uuid = Uuid::generate();
        $data['reviewer_id'] = $uuid;
        $data['periode_id'] = $reqPeriodeId;
        $data['jenis_monev_id'] = $reqJenisMonevId;
        $data['id_sdm'] = $request->input('id_sdm');
        $data['nama'] = $request->input('nama');
        $data['nidn'] = $request->input('nidn');
        $data['fakultas'] = $request->input('fakultas');
        $data['prodi'] = $request->input('prodi');
        // BACKUP NVN
        // $data['created_user'] = Auth::user()->name;

        if(Reviewer::create($data))
        {
            return response()->json([
                'status' => 'success',
                'message' => 'Data berhasil ditambahkan.',
            ]);
        }
        else
        {
            return response()->json([
                'status' => 'error',
                'message' => 'Data gagal ditambahkan.',
            ]);
        }
    }

    public function edit($id)
    {

    }

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

    }

    public function destroy($id)
    {
        try {
            $delete = Reviewer::where('reviewer_id', Crypt::decrypt($id))->update(['status_hapus'=>'1']);

            if ($delete == 1) {
                $info = 'Deleted!';
                $status = 'success';
                $message = "Reviewer berhasil dihapus.";
            }
            else{
                $info = 'Error!';
                $status = 'error';
                $message = "Reviewer tidak ada.";
            }

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

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

    public function getDosen(Request $request)
    {

        $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

        $tipe = $request->get('tipe');
        $i = 0;

        if($start == 0)
            $page = 1;
        else
            $page = ($start/10)+1;

        if($tipe == '1' || $tipe == '' || $tipe == null)
        {
            $client = new Client();
            $response = $client->request('GET', 'https://i-sdm.unesa.ac.id/api/detil-data-dosen?per_page='.$rowperpage.'&page='.$page.'&keyword='.$searchValue.'');
            $data = json_decode($response->getBody(), true);
            $total = $data['count'];

            $result = [];
            foreach ($data['data'] as $key => $value) {
                $jenjang = substr($value['namasatker'],-2);

                $x = array("D3", "D4", "S1", "S2", "S3");

                if (in_array($jenjang, $x))
                {
                    $xyz = $jenjang.' '.trim(substr($value['namasatker'],0,-2));
                }

                $result[$i]['nm_sdm'] = $value['namalengkap'];
                $result[$i]['nidn'] = $value['nidn'];
                $result[$i]['fakultas'] = $value['namaparentsatker'];
                $result[$i]['prodi'] = $xyz;
                $result[$i]['tipe'] = 'Internal';
                $result[$i]['id_sdm'] = $value['nidn'];

                $i++;
            }
        }

        if($tipe == '2' || $tipe == '' || $tipe == null)
        {
            $users = User::with(['rBiodata','rolesCustom'])->whereHas('rolesCustom',function ($q){
                $q->whereIn('name', ['reviewer']);
            })->where('status', '2')->get();
            $total += count($users);
            $j = $i?:0;
            foreach ($users as $key => $value) {
                $result[$j]['nm_sdm'] = $value->name;
                $result[$j]['nidn'] = $value->rBiodata->noidentitas;
                $result[$j]['fakultas'] = $value->rBiodata->fakultas;
                $result[$j]['prodi'] = $value->rBiodata->prodi;
                $result[$j]['tipe'] = 'External';
                $result[$j]['id_sdm'] = $value->rBiodata->noidentitas;

                $j++;
            }
        }

        $hasil['kode'] = "200";
        $hasil['pesan'] = "sukses";
        $hasil['data'] = $result;


        $response = array(
            "draw" => $draw,
            "iTotalRecords" => $total,
            "iTotalDisplayRecords" => $total,
            "aaData" => $result
        );

        return $response;

        // $client = new Client(['base_uri' => 'https://siakadu.unesa.ac.id/']);

        // $response = $client->request('POST', '/api/dashboard',
        // ['form_params' => [
        //     'kondisi' => 'dosen_aktif'
        // ],
        // 'http_errors' => false]);

        // return json_decode($response->getBody(), true);
    }
}
