<?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\Proposal;
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 Maatwebsite\Excel\Facades\Excel;
use App\Exports\DaftarProposalExport;
use App\Models\DaftarProposalBelmawa;
use App\Models\ReviewerProposalDetil;
use App\Exports\DaftarProposalMonevExport;
use App\Exports\DaftarProposalBelmawaExport;
use App\Models\JenisMonev;
use App\Models\MonevInternal;
use Exception;
use Illuminate\Support\Facades\Log;

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

    public function index()
    {
        $periode    = Periode::query()->get();
        $jenis    = Jenis::query()->where('status_hapus', '0')->get();
        return view('backend.operator.daftar_proposal.index', compact('periode', 'jenis'))->withTitle('Daftar Proposal Seleksi Internal');
    }

    /* 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');

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

        ## 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 ";
        // $statementGlobal = " ";

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

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

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

        $daftarProposalQry = DaftarProposal::query()
        ->with(['reviewerProposal1', 'reviewerProposal2'])
        ->select(DB::raw('*, ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_1) nilai_1, ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_2) nilai_2, round((ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_1) + ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_2 )) / 2, 2) as rata'))
        ->when($tahun != "0", function($query) use ($tahun){
            return $query->where('periode', $tahun);
        })
        ->when($status != "0", function($query) use ($status){
            return $query->where('status', $status);
        })
        ->when($jenis != "0", function($query) use ($jenis){
            return $query->where('jenis_id', $jenis);
        });

        $totalRecords = $daftarProposalQry->count();
        // $totalRecords = collect(DB::select("select 1 as allcount from vw_daftar_proposal('".$statementGlobal."') "))->count();
        $statement = " AND (UPPER(JUDUL) LIKE ''%".$searchValue."%'' OR UPPER(IDENTITAS_DOSPEM) LIKE ''%".$searchValue."%'') ";

        $totalRecordswithFilter =   $daftarProposalQry
        ->when($searchValue != '', function($query) use ($searchValue){
            return $query->where('judul', 'ILIKE', '%'.$searchValue.'%')
            ->orWhere('identitas_dospem', 'ILIKE', '%'.$searchValue.'%');
        })->count();

        $records = $daftarProposalQry
        ->when($searchValue, function($query, $searchValue){
            return $query->where('judul', 'ILIKE', '%'.$searchValue.'%')
            ->orWhere('identitas_dospem', 'ILIKE', '%'.$searchValue.'%');
        })
        //  collect(DB::select("select *, ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_1) nilai_1, ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_2) nilai_2, round((ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_1) + ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_2 )) / 2, 2) as rata from vw_daftar_proposal('".$statementGlobal.$statement."') ORDER BY ".$columnName." ".$columnSortOrder))
        ->skip($start)
        ->limit($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;
            $upload_dokumen = $record->upload_dokumen;
            $dospem = "(".str_replace("###",") ",$record->identitas_dospem);
            $status_administrasi_1 = $record->status_administrasi;
            $status_administrasi_2 = $record->status_administrasi_2;
            $reviewer_id_1 = $record->reviewer_id_1;
            $reviewer_id_2 = $record->reviewer_id_2;
            $status_final = $record->status_final;
            $nilai_1 = $record->nilai_1;
            $nilai_2 = $record->nilai_2;
            $rata = $record->rata;
            $url = "https://statik.unesa.ac.id/simpmw/proposal/".$record->periode."/".$record->upload_dokumen;
            $video = DaftarProposal::where('proposal_id', $proposal_id)->pluck('url');

            // $nilai_1= DB::select("select ambil_jumlah_penilaian_seleksi('".$reviewer_proposal_id_1."', '".$record->jenis_id."')")[0]->ambil_jumlah_penilaian_seleksi;

            // $nilai_2= DB::select("select ambil_jumlah_penilaian_seleksi('".$reviewer_proposal_id_2."', '".$record->jenis_id."')")[0]->ambil_jumlah_penilaian_seleksi;

            // $rata = number_format((float) (($nilai_1 + $nilai_2) / 2), 0, '.', '');

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

            $reviewer = Reviewer::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')";

            // $batalkanNilai1 =

            $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'";
            }

            $revisi1 = '';
            if($record->reviewerProposal1) {
                if($record->reviewerProposal1->revisi_nilai != 1) {
                    $revisi1 = '
                        <div align="center">
                            <button class="btn btn-warning btn-sm" onclick="revisi(\''.encrypt($record->reviewerProposal1->reviewer_proposal_id).'\')">Revisi</button>
                        </div>
                    ';
                }
                else{
                    $revisi1 = '
                        <br>
                        <p style="font-style: italic; text-align: center">On review</p>
                    ';
                }
            }

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

                        $revisi1 = '';
                        
            $revisi2 = '';
            if($record->reviewerProposal2){
                if($record->reviewerProposal2->revisi_nilai != 1) {
                    $revisi2 = '
                        <div align="center">
                            <button class="btn btn-warning btn-sm" onclick="revisi(\''.encrypt($record->reviewerProposal2->reviewer_proposal_id).'\')">Revisi</button>
                        </div>
                    ';
                }
                else{
                    $revisi2 = '
                        <br>
                        <p style="font-style: italic; text-align: center">On review</p>
                    ';
                }
            }

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

            $jenis = Jenis::where("status_hapus", '0')
            ->get();

            $opt = '';
            foreach ($jenis as $key => $value) {
                $selected = "";

                if($value->jenis_id == $jenis_id)
                    $selected = 'selected';

                $opt .= '<option value="'.Crypt::encrypt($proposal_id.'###'.$value->jenis_id).'" '.$selected.'>'.$value->nama.'</option>';
            }

            $pil_jenis_pkm = '<td class="table-action" width="100%">
                <select class="form-control select2 jenis">
                '.$opt.'
                </select>
            </td>';

            if($status_final == '1')
            {
                $aksi = '<div align="center"><span class="badge bg-success" style="font-size: 12pt;">Lolos</span></div>';
            }
            elseif($status_final == '2')
            {
                $aksi = '<div align="center"><span class="badge bg-danger style="font-size: 12pt;"">Tidak Lolos</span></div>';
            }
            else
            {
                $aksi = '<td class="table-action">
                        <div align="center">
                            <a href="#!" data-toggle="tooltip" data-placement="top" title="Lolos" 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" data-toggle="tooltip" data-placement="top" title="Tidak Lolos" onclick="'.$tidak_lolos.'"><i class="fas fa-ban"></i></a>
                            <a href="#" class="btn btn-icon-sm btn-primary" data-toggle="tooltip" data-placement="top" title="Lihat Detail" data-bs-toggle="modal" data-bs-target="#proposalModal' . $proposal_id . '"><i class="fas fa-search"></i></a>
                        </div>
                    </td>';
            }

            $aksi .= '
                    <div class="modal fade" id="proposalModal' . $proposal_id . '" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="exampleModalLabel">Proposal</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="table-responsive">
                                        <table class="table mb-0">
                                            <tr>
                                                <th>Judul Proposal</th>
                                                <td>' . $judul . '</td>
                                            </tr>
                                            <tr>
                                                <th>Kategori PMW</th>
                                                <td>' . $jenis_pkm . '</td>
                                            </tr>
                                            <tr>
                                                <th>Proposal</th>
                                                <td>';
                                                if ($upload_dokumen) {
                                                    $aksi .= '<a href="' . $url . '" target="_blank" class="btn btn-success btn-sm">
                                                                <i class="far fa-eye"></i> Lihat Proposal
                                                            </a>';
                                                } else {
                                                    $aksi .= '<div class="alert alert-danger alert-dismissible fade show mb-0" role="alert">
                                                                <strong>Informasi!</strong> File tidak ditemukan.
                                                            </div>';
                                                }
                                    $aksi .= '</td>
                                            </tr>
                                            <tr>
                                                <th>Video Produk</th>
                                                <td>';
                                                foreach ($video as $item) {
                                                    if ($item&& preg_match('/(http|https|www.|\.com|\.co.id|\.org)/i', $item)) {
                                                        $aksi .= '<button id="preview-video' . $proposal_id . '" class="btn btn-success btn-sm" data-video="' . $item . '">
                                                                    <i class="far fa-eye"></i> Lihat Video
                                                                </button>';
                                                    } else {
                                                        $aksi .= '<div class="alert alert-danger alert-dismissible fade show mb-0" role="alert">
                                                                    <strong>Informasi!</strong> File tidak ditemukan.
                                                                </div>';
                                                    }
                                                }
                                    $aksi .= '</td>
                                            </tr>
                                        </table>
                                    </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                    </div>
                                    </div>
                                    </div>
                                    </div>';

                    // JavaScript untuk membuka video dalam Magnific Popup
                    $aksi .= "
                    <script>
                    $(document).ready(function() {
                        $('#preview-video" . $proposal_id . "').on('click', function() {
                            var videoUrl = $(this).attr('data-video');
                            if (videoUrl) {
                                if (videoUrl.includes('youtu.be')) {
                                    videoUrl = videoUrl.replace('youtu.be/', 'youtube.com/watch?v=');
                                }

                                if (videoUrl.includes('youtu.be')) {
                                    videoUrl = videoUrl.split('?')[0];
                                } else if (videoUrl.includes('youtube.com/watch?v=')) {
                                    videoUrl = videoUrl.split('&')[0];
                                }
                                if (isValidYouTubeUrl(videoUrl)) {
                                    var currentModal = $('#proposalModal" . $proposal_id . "');
                                    $.magnificPopup.open({
                                        items: {
                                            src: videoUrl
                                        },
                                        type: 'iframe',
                                        iframe: {
                                            markup: '<div class=\"mfp-iframe-scaler\">'+
                                                        '<div class=\"mfp-close\"></div>'+
                                                        '<iframe class=\"mfp-iframe\" frameborder=\"0\" allowfullscreen allow=\"autoplay\"></iframe>'+
                                                    '</div>'
                                        },
                                        callbacks: {
                                            open: function() {
                                                currentModal.modal('hide');
                                                var iframe = this.content.find('iframe');
                                                if (iframe.length > 0) {
                                                    var videoSrc = iframe.attr('src');
                                                    iframe.attr('src', videoSrc + '&autoplay=1');
                                                }
                                            },
                                            close: function() {
                                                currentModal.modal('show');
                                                var iframe = this.content.find('iframe');
                                                if (iframe.length > 0) {
                                                    var videoSrc = iframe.attr('src');
                                                    iframe.attr('src', videoSrc.replace('&autoplay=1', ''));
                                                }
                                            }
                                        }
                                    });
                                } else {
                                    window.open(videoUrl, '_blank');
                                }
                            } else {
                                console.error('URL video tidak valid:', videoUrl);
                            }
                        });
                        function isValidYouTubeUrl(url) {
                            return /^(http(s)?:\\/\\/)?((w){3}.)?youtu(be|.be)?(\\.com)?\\/.+/gm.test(url);
                        }
                    });
                    </script>
                    ";

            $pendanaan = '
                <td>
                    Usulan Dana: Rp'.number_format($record->usulan_dana, 0, ",", ",").'
                    <br>
                    <br>
                    Diberikan: Rp'.number_format($record->pendanaan, 0, ",", ",").'
                </td>
            ';

            $data_arr[] = array(
                "proposal_id" => $proposal_id,
                "kode" => $kode,
                "jenis_pkm" => $pil_jenis_pkm,
                "judul" => $judul,
                "dospem" => $dospem,
                "reviewer_1" => $pilihan_1,
                "reviewer_2" => $pilihan_2,
                "pendanaan" => $pendanaan,
                "rata" => $rata,
                "aksi" => $aksi
            );
        }

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

        echo json_encode($response);
        exit;
    }

    public function bukaPenilaian(Request $request)
    {
        try{
            $id = decrypt($request->id);

            $reviewerProposal = ReviewerProposal::query()->find($id);
            $reviewerProposal->revisi_nilai = 1;
            $reviewerProposal->save();

            return response([
                'message' => 'success',
                'status' => 200
            ], 200);
        }
        catch(Exception $ex){
            dd($ex);
            return response([
                'message' => 'error',
                'status' => 500
            ], 500);
        }
    }

    public function index_belmawa()
    {
        $periode    = Periode::query()->get();
        $jenis    = Jenis::query()->where('status_hapus', '0')->get();
        return view('backend.operator.daftar_proposal.belmawa', compact('periode', 'jenis'))->withTitle('Daftar Proposal Seleksi Belmawa');
    }

    /* AJAX request */
    public function getDataBelmawa(Request $request){
        // parameter
        $jenis= $request->get('jenis');
        $status = $request->get('status');
        $tahun= $request->get('tahun');

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

        ## 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")
        {
            // dikurang 1 karena di view mulai dari 0 sedangkan 0 itu menunggu persetujuan
            $status = $status - 1;
            $statementGlobal .= " AND STATUS = '".$status."'";
        }

        if($tahun != "0")
        {
            $statementGlobal .= " AND PERIODE = '".$tahun."'";
        }
        $totalRecords = DaftarProposalBelmawa::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $statement = " AND (UPPER(JUDUL) LIKE '%".$searchValue."%' OR UPPER(NAMA_DOSEN) 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/simpmw/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(Request $request)
    {
        try {
            $id = $request->id;
            $status = $request->status;

            // if($request->status == 1){

            //     $count = ReviewerProposal::where('proposal_id', Crypt::decrypt($id))->where('status_administrasi', 1)->count();;

            //     if($count < 2){

            //         return response()->json([
            //             'status' => 'error',
            //             'message' => "Terdapat reviewer yang belum memberikan penilaian.",
            //         ]);
            //     }
            // }

            $delete = ReviewerProposal::where('proposal_id', Crypt::decrypt($id))
            ->update([
                'status_final'=>$status
            ]);

            if ($delete) {
                if($status == '1')
                {
                    $status = 'success';
                    $message = "Proposal Seleksi Internal Lolos.";

                    $proposal = Proposal::query()->find(Crypt::decrypt($id))->update([
                        'pendanaan' => $request->dana
                    ]);

                    $this->createMonevInternal(Crypt::decrypt($id));
                }
                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 $ex) {
            Log::error($ex);
            return response()->json([
                'status' => 'error',
                'message' => "Data gagal diproses.",
            ]);
        }
    }

    private function createMonevInternal($proposalId)
    {
        $reviewerProposal = ReviewerProposal::where('proposal_id', $proposalId)->whereIn('urut', [1, 2]);
        $count = $reviewerProposal->where('status_administrasi', 1)->count();
        $monevInternal = MonevInternal::query()->where('proposal_id', $proposalId)->get();

        // if($count == 2){
            for ($i = 3; $i < 5; $i++) {
                $jenis = JenisMonev::query()->where('urut', $i)->first();
                $monevInternal->where('jenis_monev_id', $jenis->jenis_monev_id);

                if($monevInternal->count() == 0){
                    Log::debug('create monev');
                    MonevInternal::query()->create([
                        'proposal_id' => $proposalId,
                        'jenis_monev_id' => $jenis->jenis_monev_id,
                        'created_user' => 'SYSTEM',
                    ]);
                }

            }
        // }
    }

    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 change_jenis(Request $request)
    {
        try {
            $isi = Crypt::decrypt($request->input('data'));
            $arrData = explode('###', $isi);

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

            $delete = Proposal::where('proposal_id', $reqProposalId)->update(['jenis_id'=>$reqJenisId]);

            if ($delete) {
                $status = 'success';
                $message = "Berhasil ubah Kategori PMW.";
            }
            else{
                $status = 'error';
                $message = "Data gagal diproses.";
            }

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

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

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

        // dd($jenis, $tahun, $status);

        return Excel::download(new DaftarProposalExport($jenis, $status, $tahun), 'daftar_seleksi_internal_'.$tahun.'-export_pmw.xlsx');
        // $daftarProposalExport = new DaftarProposalExport($jenis, $status, $tahun);
        // $data = $daftarProposalExport->view(); // Mendapatkan koleksi data
    
        // return $data;
    }

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

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

    public function cetak_daftar_proposal_new(Request $request)
    {
        $jenis = $request->jenis;
        $status = $request->status;
        $tahun= $request->tahun;

        ini_set('memory_limit', '-1');
        $statement = " STATUS_HAPUS = '0' ";

        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 = DaftarProposal::with('rKelompokDetil')
                ->select("*")
                ->selectRaw(" round((ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_1) + ambil_jumlah_penilaian_seleksi(reviewer_proposal_id_2 )) / 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/simpmw/proposal/".$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.excel_new', $datas);
    }
}
