<?php

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

use URL;

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

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 DaftarProposalController extends Controller
{
    private const periode_id          = '9857a29d-521f-413a-b811-94cda7b45897';

    public function index()
    {
        return view('backend.operator.daftar_proposal.index')->withTitle('Daftar Proposal Seleksi Internal');
    }

    /* 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 ";
        $totalRecords = DaftarProposal::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $statement = " AND (UPPER(JUDUL) LIKE '%".$searchValue."%') ";

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

        // Fetch records
        $records = DaftarProposal::orderBy($columnName,$columnSortOrder)
            ->whereRaw($statementGlobal.$statement)
            ->select('daftar_proposal.*')
            ->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;
            $jenis_id = $record->jenis_id;
            $kode = $record->kode;
            $jenis_pkm = $record->jenis_pkm;
            $judul = $record->judul;
            $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('periode_id', DaftarProposalController::periode_id)
                                ->where('jenis_monev_id', 'ba11c2b5-d65d-4360-9717-98e4fa9b9188')
                                ->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($proposal_id.'###'.$value->reviewer_id).'" '.$selected1.'>'.$value->nama.'</option>';
                $opt2 .= '<option value="'.Crypt::encrypt($proposal_id.'###'.$value->reviewer_id).'" '.$selected2.'>'.$value->nama.'</option>';
            }

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

            $disable_1 = $disable_2 = '';

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

            if($nilai_2 > '0' || $status_administrasi_2 == '2')
            {
                $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(
                "proposal_id" => $proposal_id,
                "kode" => $kode,
                "jenis_pkm" => $jenis_pkm,
                "judul" => $judul,
                "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 index_belmawa()
    {
        return view('backend.operator.daftar_proposal.belmawa')->withTitle('Daftar Proposal Seleksi Belmawa');
    }

    /* AJAX request */
    public function getDataBelmawa(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 ";
        $totalRecords = DaftarProposalBelmawa::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $statement = " AND (UPPER(JUDUL) LIKE '%".$searchValue."%') ";

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

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

        $data_arr = array();
        foreach($records as $record){
            $seleksi_belmawa_id = $record->seleksi_belmawa_id;
            $kode_kelompok = $record->kode_kelompok;
            $jenis_pkm = $record->jenis_pkm;
            $judul = $record->judul;
            $nama_dosen = $record->nama_dosen;
            $upload_dokumen = $record->upload_dokumen;
            $status = $record->status;
            $status_desc = $record->status_desc;

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

            if($upload_dokumen == '' || $upload_dokumen == null)
                $proposal = '<span class="badge bg-warning">Dokumen belum diunggah.</span>';
            else
            {
                $url = "https://statik.unesa.ac.id/simpkm/proposal/revisi/".$record->periode."/".$record->upload_dokumen;

                $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 == '1')
            {
                $aksi = '<span class="badge bg-success">Lolos</span>';
            }
            elseif($status == '2')
            {
                $aksi = '<span class="badge bg-danger">Tidak Lolos</span>';
            }
            else
            {
                if($upload_dokumen == '' || $upload_dokumen == null)
                {
                    $aksi = '<span class="badge bg-warning">Dokumen belum diunggah.</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(
                "seleksi_belmawa_id" => $seleksi_belmawa_id,
                "kode_kelompok" => $kode_kelompok,
                "jenis_pkm" => $jenis_pkm,
                "judul" => $judul,
                "nama_dosen" => $nama_dosen,
                "upload_dokumen" => $proposal,
                "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);

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


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

            // update status hapus jadi 1

            $delete = ReviewerProposal::where('reviewer_proposal_id', $reqId)->update(['status_hapus'=>'1', 'deleted_at' => Carbon::now()]);
            // $delete_detil = ReviewerProposalDetil::where('reviewer_proposal_id', $reqId)->delete();

            // $delete = ReviewerProposal::where('reviewer_proposal_id', $reqId)->delete();

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

                if(ReviewerProposal::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 = ReviewerProposal::where([
            ['proposal_id', '=', $reqProposalId],
            ['reviewer_id', '=', $reqReviewerId],
            ['urut', '!=', $reqUrut],
        ])->count();

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

        $ada_data_detil = ReviewerProposal::join('reviewer_proposal_detil as b', 'reviewer_proposal.reviewer_proposal_id', '=', 'b.reviewer_proposal_id')->where([
            ['proposal_id', '=', $reqProposalId],
            ['urut', '=', $reqUrut],
            ['status_hapus', '=', '0'],
        ])->first();

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


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

        $reviewer_proposal = ReviewerProposal::updateOrCreate([
            'proposal_id' => $reqProposalId,
            'urut' => $reqUrut
        ], $data);

        if($reviewer_proposal)
        {
            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 = ReviewerProposal::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.",
            ]);
        }
    }
}
