<?php

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

use URL;

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

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\SeleksiBelmawa;
use Illuminate\Support\Carbon;
use App\Models\ReviewerMonevDetil;
use App\Models\DaftarProposalMonev;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\DaftarProposalBelmawa;
use App\Exports\DaftarProposalMonevExport;

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

    public function index($id)
    {
        $jenis_monev = JenisMonev::select('nama')->where('jenis_monev_id', Crypt::decrypt($id))->first();
        $data = [
            'id'=> $id
        ];
        $periode    = Periode::query()->get();
        $jenis    = Jenis::query()->where('status_hapus', '0')->get();
        return view('backend.operator.daftar_proposal.monev', compact('data', 'periode', 'jenis'))->withTitle('Daftar Proposal '.$jenis_monev->nama);
    }

    /* AJAX request */
    public function getData(Request $request){
        $periode    = Periode::where('status', 1)->first();
        $reqPeriodeId = $periode->periode_id;

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

        $jenis_monev_id = Crypt::decrypt($request->get('jenis_monev_id'));

        ## 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 ";

        if($jenis != "0")
        {
            $statementGlobal .= " AND JENIS_ID = '".$jenis."'";
        }

        if($status != "0")
        {
            if($status == '1')
                $statementGlobal .= " AND NILAI_1 != 0 AND NILAI_2 != 0";
            else
                $statementGlobal .= " AND NILAI_1 = 0 AND NILAI_2 = 0";
        }

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

        $totalRecords = DaftarProposalMonev::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $statement = " AND (UPPER(JUDUL) LIKE '%".$searchValue."%') ";
        $statement .= " AND JENIS_MONEV_ID = '".$jenis_monev_id."'";

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

        // Fetch records
        $records = DaftarProposalMonev::orderBy($columnName,$columnSortOrder)
            ->whereRaw($statementGlobal.$statement)
            ->select('daftar_proposal_monev.*')
            ->selectRaw("ROUND((nilai_1 + nilai_2) / 2, 0) as rata")
            ->skip($start)
            ->take($rowperpage)
            ->get();

        $data_arr = array();
        foreach($records as $record){
            $proposal_id = $record->proposal_id;
            $monev_internal_id = $record->monev_internal_id;
            $jenis_id = $record->jenis_id;
            $kode = $record->kode;
            $jenis_pkm = $record->jenis_pkm;
            $judul = $record->judul;
            $dospem = "(".str_replace("###",") ",$record->identitas_dospem);
            $status_administrasi_1 = $record->status_administrasi_1;
            $status_administrasi_2 = $record->status_administrasi_2;
            $nilai_1 = $record->nilai_1;
            $nilai_2 = $record->nilai_2;
            $reviewer_id_1 = $record->reviewer_id_1;
            $reviewer_id_2 = $record->reviewer_id_2;
            $status_final = $record->status_final;
            $rata = $record->rata;

            // $rata = ($nilai_1 + $nilai_2) / 2;

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

            $reviewer = Reviewer::where('jenis_monev_id', $jenis_monev_id)
                                ->where("status_hapus", '0')
                                ->get();

            $opt1=$opt2 = "<option value=''>Pilih Reviewer</option>";

            foreach ($reviewer as $key => $value) {
                $selected1 = "";
                $selected2 = "";

                if($value->reviewer_id == $reviewer_id_1)
                    $selected1 = 'selected';

                if($value->reviewer_id == $reviewer_id_2)
                    $selected2 = 'selected';

                $opt1 .= '<option value="'.Crypt::encrypt($monev_internal_id.'###'.$value->reviewer_id).'" '.$selected1.'>'.$value->nama.'</option>';
                $opt2 .= '<option value="'.Crypt::encrypt($monev_internal_id.'###'.$value->reviewer_id).'" '.$selected2.'>'.$value->nama.'</option>';
            }

            $lolos = "confirmFinal('".Crypt::encrypt($monev_internal_id)."', '1')";
            $tidak_lolos = "confirmFinal('".Crypt::encrypt($monev_internal_id)."', '2')";

            $disable_1 = $disable_2 = '';

            if($nilai_1 > '0')
            {
                $disable_1 = "disabled='true'";
            }

            if($nilai_2 > '0')
            {
                $disable_2 = "disabled='true'";
            }

            $pilihan_1 = '<td class="table-action">
                            <select class="form-control select2 reviewer" data-urut="1" '.$disable_1.'>
                            '.$opt1.'
                            </select>
                        </td>';

            $pilihan_2 = '<td class="table-action">
                            <select class="form-control select2 reviewer" data-urut="2" '.$disable_2.'>
                            '.$opt2.'
                            </select>
                        </td>';

            if($status_final == '1')
            {
                $aksi = '<span class="badge bg-success">Lolos</span>';
            }
            elseif($status_final == '2')
            {
                $aksi = '<span class="badge bg-danger">Tidak Lolos</span>';
            }
            else
            {
                $aksi = '<td class="table-action">
                        <a href="#!" class="btn btn-icon-sm btn-success" onclick="'.$lolos.'"><i class="fas fa-check"></i></a>
                        <a href="#!" class="btn btn-icon-sm btn-danger" onclick="'.$tidak_lolos.'"><i class="fas fa-ban"></i></a>
                    </td>';
            }

            $data_arr[] = array(
                "monev_internal_id" => $monev_internal_id,
                "kode" => $kode,
                "jenis_pkm" => $jenis_pkm,
                "judul" => $judul,
                "dospem" => $dospem,
                "reviewer_1" => $pilihan_1,
                "reviewer_2" => $pilihan_2,
                "nilai_1" => $nilai_1,
                "nilai_2" => $nilai_2,
                "rata" => $rata,
                "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)
    {
        $uuid = Uuid::generate();
        $reqUrut = $request->input('urut');
        $isi = Crypt::decrypt($request->input('data'));
        $arrData = explode('###', $isi);

        $reqMonevInternalId = $arrData[0]?:'';
        $reqReviewerId = $arrData[1]?:'';


        if($request->input('reqId') != null)
        {
            $reqId = $request->input('reqId');

            // update status hapus jadi 1

            $delete = ReviewerMonev::where('reviewer_monev_id', $reqId)->update(['status_hapus'=>'1', 'deleted_at' => Carbon::now()]);
            // $delete_detil = ReviewerMonevDetil::where('reviewer_monev_id', $reqId)->delete();

            // $delete = ReviewerMonev::where('reviewer_monev_id', $reqId)->delete();

            if ($delete == 1) {
                // ketika sudah di delete kemudian data yang baru di insert
                $data['reviewer_monev_id'] = $uuid;
                $data['monev_internal_id'] = $reqMonevInternalId;
                $data['reviewer_id'] = $reqReviewerId;
                $data['urut'] = $reqUrut;
                // BACKUP NVN
                // $data['created_user'] = Auth::user()->name;

                if(ReviewerMonev::create($data))
                {
                    return response()->json([
                        'status' => 'success',
                        'message' => 'Data reviewer sebelumnya telah berhasil dihapus dan data reviewer yang baru telah berhasil ditambahkan.',
                    ]);
                }
                else
                {
                    return response()->json([
                        'status' => 'error',
                        'message' => 'Data gagal dihapus.',
                    ]);
                }
            }
        }


        $ada_data = ReviewerMonev::where([
            ['monev_internal_id', '=', $reqMonevInternalId],
            ['reviewer_id', '=', $reqReviewerId],
            ['urut', '!=', $reqUrut],
        ])->count();

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

        $ada_data_detil = ReviewerMonev::join('reviewer_monev_detil as b', 'reviewer_monev.reviewer_monev_id', '=', 'b.reviewer_monev_id')->where([
            ['monev_internal_id', '=', $reqMonevInternalId],
            ['urut', '=', $reqUrut],
            ['status_hapus', '=', '0'],
        ])->first();

        if(isset($ada_data_detil))
        {
            return response()->json([
                'id' => $ada_data_detil->reviewer_monev_id,
                'status' => 'info',
                'message' => 'Reviewer sudah menilai proposal, apakah anda yakin akan merubah reviewer?',
            ]);
        }


        $data['reviewer_monev_id'] = $uuid;
        $data['monev_internal_id'] = $reqMonevInternalId;
        $data['urut'] = $reqUrut;
        $data['reviewer_id'] = $reqReviewerId;
        // BACKUP NVN
        // $data['created_user'] = Auth::user()->name;

        $reviewer_monev = ReviewerMonev::updateOrCreate([
            'monev_internal_id' => $reqMonevInternalId,
            'urut' => $reqUrut
        ], $data);

        if($reviewer_monev)
        {
            return response()->json([
                'status' => 'success',
                'message' => 'Data berhasil diubah.',
            ]);
        }
        else
        {
            return response()->json([
                'status' => 'error',
                'message' => 'Data gagal diubah.',
            ]);
        }
    }

    public function edit($id)
    {

    }

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

    }

    public function destroy($id)
    {

    }

    public function approval($id, $status)
    {
        try {
            $delete = ReviewerMonev::where('proposal_id', Crypt::decrypt($id))->update(['status_final'=>$status]);

            if ($delete) {
                if($status == '1')
                {
                    $status = 'success';
                    $message = "Proposal Seleksi Internal Lolos.";
                }
                elseif($status == '2')
                {
                    $status = 'success';
                    $message = "Proposal Seleksi Internal Tidak Lolos.";
                }
            }
            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.",
            ]);
        }
    }

    public function approval_belmawa($id, $status)
    {
        try {
            $delete = SeleksiBelmawa::where('seleksi_belmawa_id', Crypt::decrypt($id))->update(['status'=>$status]);

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

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

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

    public function cetak_daftar_monev_internal(Request $request)
    {
        ini_set('max_execution_time', 0);
        $id = $request->id;
        $jenis = $request->jenis;
        $status = $request->status;
        $tahun= $request->tahun;

        return Excel::download(new DaftarProposalMonevExport($jenis, $status, $tahun), 'seleksi_monev_export.xlsx');
    }

    public function cetak_daftar_monev_internal_new(Request $request)
    {
        $id = $request->id;
        $reqId = Crypt::decrypt($id);
        $jenis = $request->jenis;
        $status = $request->status;
        $tahun= $request->tahun;

        ini_set('memory_limit', '-1');
        $statement = " STATUS_HAPUS = '0' AND JENIS_MONEV_ID = '".$reqId."' ";

        if($jenis != "0")
        {
            $statement .= " AND jenis_id = '".$jenis."'";
        }

        if($status != "0")
        {
            // dikurang 1 karena di view mulai dari 0 sedangkan 0 itu menunggu persetujuan
            $status = $status - 1;
            $statement .= " AND STATUS_FINAL = '".$status."'";
        }

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

        $data = DaftarProposalMonev::with('rKelompokDetil')
        ->select("*")
        ->selectRaw(" round((ambil_jumlah_penilaian_monev(reviewer_monev_id_1, '".$reqId."') + ambil_jumlah_penilaian_monev(reviewer_monev_id_2, '".$reqId."')) / 2, 2) as rata ")->whereRaw($statement)->get();

        $result = [];

        $x =0;
        $dospem = '';
        foreach ($data as $key => $value) {
            // $dospem = "(".str_replace("###",") ",$value->identitas_dospem);
            $data_dospem = explode('###', $value->identitas_dospem);
            $data_ketua = explode('###', $value->identitas_ketua);
            $dospem = "(".$data_dospem[0].") ".$data_dospem[1];
            $url = "https://statik.unesa.ac.id/simpkm/monev/".$value->periode."/".$value->upload_dokumen;

            if($value->status_final == '1')
                $status_final = "Lolos";
            elseif($value->status_final == '2')
                $status_final = "Tidak Lolos";
            else
                $status_final = "Menunggu Persetujuan";

            $urut = 1;
            $det = array();
            $no = 0;
            foreach ($value->rKelompokDetil as $keys => $detil) {

                if($detil->status_ketua == '1')
                {
                    $keanggotaan = "Ketua";
                }
                else
                {
                    $keanggotaan = "Anggota ".$urut;
                    $urut++;
                }

                $det[$no]['fak'] = $detil->fakultas;
                $det[$no]['nama'] = $detil->nama;
                $det[$no]['nim']= $detil->nim;
                $det[$no]['keanggotaan'] = $keanggotaan;

                $no++;
            }

            $result[$x]['rowspan'] = count($value->rKelompokDetil);
            $result[$x]['kode'] = $value->kode;
            $result[$x]['jenis'] = $value->jenis_pkm;
            $result[$x]['detil'] = $det;
            $result[$x]['judul'] = $value->judul;
            $result[$x]['dospem'] = $dospem;
            $result[$x]['link'] = $url;
            $result[$x]['status'] = $status_final;
            $result[$x]['rata'] = $value->rata;
            $result[$x]['email_dospem'] = end($data_dospem);
            $result[$x]['email_ketua'] = end($data_ketua);

            $x++;
        }

        $datas['list_proposal'] = $result;
        $datas['jenis_monev'] = 'Seleksi Internal';

        return view('backend.operator.daftar_proposal.monev_excel_new', $datas);
    }
}
