<?php

namespace App\Http\Controllers\Operator;

use DB;
use URL;

use Auth;
use Uuid;
use Alert;
use App\Helpers\InseoHelper;
use Crypt;
use GuzzleHttp\Client;
use App\Models\Periode;

use App\Models\Reviewer;
use App\Models\JenisMonev;
use App\Traits\LoginTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ReviewerMonevController extends Controller
{
    use LoginTrait;
    public function index($id)
    {
        $periode    = Periode::query()->get();
        $jenis_monev = JenisMonev::select('nama')->where('jenis_monev_id', Crypt::decrypt($id))->first();
        $data = [
            'id'=> $id,
            'periode'=> $periode
        ];
        return view('backend.operator.reviewer.monev', compact('data'))->withTitle('Reviewer '.$jenis_monev->nama);
    }

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

        $jenis_monev_id = Crypt::decrypt($request->get('jenis_monev_id'));
        $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

        $statement = " AND (UPPER(NAMA) LIKE '%".$searchValue."%' OR NIDN LIKE '%".$searchValue."%') ";

        if($jenis_monev_id != "0")
        {
            $statement .= " AND JENIS_MONEV_ID = '".$jenis_monev_id."'";
        }

        // Total records
        $statementGlobal = " STATUS_HAPUS = '0' ";
        $totalRecords = Reviewer::select('count(1) as allcount')->whereRaw($statementGlobal.$statement)->count();

        $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, '2', '".$jenis_monev_id."', '0', '".$tahun."') jumlah_harus_review, ambil_jumlah_reviewer_info_review(reviewer.reviewer_id, '2', '".$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 = Crypt::decrypt($request->input('jenis_monev_id'));

        $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');
        $fakInput = $request->input('fakultas');
        $fakMap = InseoHelper::singkatan_fakultas();
        $fakKey = strtolower(trim((string) $fakInput));
        if ($fakKey !== '' && array_key_exists($fakKey, $fakMap)) {
            $data['fakultas'] = $fakMap[$fakKey];
        } else {
            $data['fakultas'] = $fakInput;
        }
        $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)
    {
        $client = new Client();
        $response = $client->request('GET', 'https://i-sdm.unesa.ac.id/api/data-dosen');
        $data = json_decode($response->getBody(), true);

        $result = [];
        $i = 0;
        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'] ?? $value['nuptk'];
            $result[$i]['fakultas'] = $value['namaparentsatker'];
            $result[$i]['prodi'] = $xyz;
            $result[$i]['id_sdm'] = $value['nidn'] ?? $value['nuptk'];

            $i++;
        }

        // $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($result, true);
    }
}
