<?php

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

use URL;

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

use GuzzleHttp\Client;
use App\Models\Periode;
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\JenisMonev;
use App\Models\MonevInternal;
use App\Models\ReviewerProposalDetil;
use Illuminate\Support\Facades\Log;
use Exception;

class DaftarSeleksiController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('nilai.seleksi-internal', ['only' => ['edit', 'update']]);
        $this->middleware(function ($request, $next) {
            $this->rBiodata = Auth::user()->rBiodata;

            return $next($request);
        });
    }

    public function index()
    {
        $periode    = Periode::query()->get();
        return view('backend.reviewer.seleksi.index', compact('periode'))->withTitle('Daftar Proposal Seleksi Internal');
    }

    /* AJAX request */
    public function getData(Request $request){
        $noidentitas = $this->rBiodata->noidentitas;

        // parameter
        $administrasi = $request->get('administrasi');
        $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
        $statement = " AND (UPPER(JUDUL) LIKE ''%".$searchValue."%'') ";
        // $statementGlobal = " 1=1 AND (NIDN_REVIEWER_ID_1 = '".$noidentitas."' OR NIDN_REVIEWER_ID_2 = '".$noidentitas."')";
        $statementGlobal = " ";

        if($administrasi != "0")
        {
            // dikurang 1 karena di view mulai dari 0 sedangkan 0 itu menunggu persetujuan
            $administrasi = $administrasi - 1;
            $statementGlobal .= " AND (ambil_data_reviewer_proposal ( ''".$noidentitas."'', proposal_id, ''3'' ) = ''".$administrasi."'')";
        }

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

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

        // $totalRecords = DaftarProposal::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $totalRecords = collect(DB::select("select 1 as allcount from vw_daftar_proposal('".$statementGlobal."', '".$noidentitas."') "))->count();

        // $totalRecordswithFilter =   DaftarProposal::select('count(1) as allcount')->whereRaw($statementGlobal.$statement)->count();
        $totalRecordswithFilter =   collect(DB::select("select 1 as allcount from vw_daftar_proposal('".$statementGlobal.$statement."', '".$noidentitas."') "))->count();

        // echo "select 1 as allcount from vw_daftar_proposal('".$statementGlobal.$statement."', '".$noidentitas."')"; exit;
        // Fetch records
        // $records = DaftarProposal::orderBy($columnName,$columnSortOrder)
        //     ->whereRaw($statementGlobal.$statement)
        //     ->select('*')
        //     ->skip($start)
        //     ->take($rowperpage)
        //     ->get();
        $records = collect(DB::select("select * from vw_daftar_proposal('".$statementGlobal.$statement."', '".$noidentitas."') ORDER BY ".$columnName." ".$columnSortOrder))
                    ->skip($start)
                    ->take($rowperpage);

        $reviewer = Reviewer::query()->where('id_sdm', $noidentitas)->first();
        // $reviewerProposal = ReviewerProposal::query()->whereIn('proposal_id', $records->pluck('proposal_id'))->where('reviewer_id', $reviewer->reviewer_id)->get()->keyBy('proposal_id');
        $reviewerProposal = ReviewerProposal::query()
        ->whereIn('proposal_id', $records->pluck('proposal_id'))
        ->whereHas('reviewer', function($query) use ($noidentitas){
            return $query->wherehas('biodata', function($query) use ($noidentitas){
                return $query->where('noidentitas', $noidentitas);
            });
        })
        ->get()
        ->keyBy('proposal_id');

        $data_arr = array();
        $hitung = 1;

        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;

            $nilai_1 = 0;
            if ($record->reviewer_proposal_id_1 != NULL) {
                $nilai_1 = DB::select("select ambil_jumlah_penilaian_seleksi('".$record->reviewer_proposal_id_1."')")[0]->ambil_jumlah_penilaian_seleksi;
            }
            $nilai_2 = 0;
            if ($record->reviewer_proposal_id_2 != NULL) {
                $nilai_2 = DB::select("select ambil_jumlah_penilaian_seleksi('".$record->reviewer_proposal_id_2."')")[0]->ambil_jumlah_penilaian_seleksi;
            }

            $url = "https://statik.unesa.ac.id/simpmw/proposal/".$record->periode."/".$record->upload_dokumen;

            $video = DaftarProposal::where('proposal_id', $proposal_id)->pluck('url');

            $urut = DB::select("select ambil_data_reviewer_proposal('".$noidentitas."', '".$proposal_id."', '1')")[0]->ambil_data_reviewer_proposal;

            $status_nilai = DB::select("select ambil_data_reviewer_proposal('".$noidentitas."', '".$proposal_id."', '2')")[0]->ambil_data_reviewer_proposal;

            $status_administrasi = DB::select("select ambil_data_reviewer_proposal('".$noidentitas."', '".$proposal_id."', '3')")[0]->ambil_data_reviewer_proposal;

            // $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>';
            $proposal = '
                        <a href="#" align="center" class="btn btn-primary btn-sm waves-effect waves-light" role="button" data-toggle="tooltip" data-placement="bottom" title="Lihat Proposal" data-bs-toggle="modal" data-bs-target="#proposalModal' . $proposal_id . '">
                            <i class="fas fa-search"></i>
                        </a>';

                    $proposal .= '
                    <div class="modal fade" id="proposalModal' . $proposal_id . '" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                        <div class="modal-dialog 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) {
                                                    $proposal .= '<a href="' . $url . '" target="_blank" class="btn btn-success btn-sm">
                                                                <i class="far fa-eye"></i> Lihat Proposal
                                                            </a>';
                                                } else {
                                                    $proposal .= '<div class="alert alert-danger alert-dismissible fade show mb-0" role="alert">
                                                                <strong>Informasi!</strong> File tidak ditemukan.
                                                            </div>';
                                                }
                                    $proposal .= '</td>
                                            </tr>
                                            <tr>
                                                <th>Video Produk</th>
                                                <td>';
                                                foreach ($video as $item) {
                                                    if ($item) {
                                                        $proposal .= '<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 {
                                                        $proposal .= '<div class="alert alert-danger alert-dismissible fade show mb-0" role="alert">
                                                                    <strong>Informasi!</strong> File tidak ditemukan.
                                                                </div>';
                                                    }
                                                }
                                    $proposal .= '</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
                    $proposal .= "
                    <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>
                    ";

            if($status_nilai > 0 || $status_administrasi == '2')
                $status = '<span class="badge bg-success">Sudah dinilai</span>';
            else
                $status = '<span class="badge bg-danger">Belum dinilai</span>';

            $aksi = '';

            if($status_administrasi == '1')
                $administrasi = '<span class="badge bg-success">Lolos</span>';
            elseif($status_administrasi == '2')
                $administrasi = '<span class="badge bg-danger">Tidak Lolos</span>';
            else
            {
                $lolos = "confirmFinal('".Crypt::encrypt($proposal_id)."', '1', '".$hitung."')";
                $tidak_lolos = "confirmFinal('".Crypt::encrypt($proposal_id)."', '2', '".$hitung."')";
                $administrasi = '<td class="table-action">
                                    <a href="#!" class="btn btn-icon-sm btn-success btn-sm" onclick="'.$lolos.'">Lolos ?</a>
                                    <a href="#!" class="btn btn-icon-sm btn-danger btn-sm" onclick="'.$tidak_lolos.'">Tidak ?</a>
                                </td>';
            }
            $nilai = URL::to("reviewer/seleksi-internal/".Crypt::encrypt($proposal_id)."/edit");

            if($status_administrasi != '0')
            {
                if($status_nilai == '1')
                {
                    if($urut == '1')
                        $aksi = '<h4>'.$nilai_1.'</h4>';
                    elseif($urut == '2')
                        $aksi = '<h4>'.$nilai_2.'</h5>';

                    if($reviewerProposal[$proposal_id]->revisi_nilai == 1){
                        $aksi .= '<a href="'.$nilai.'" class="btn btn-icon-sm btn-warning btn-sm">Beri nilai<i class="fas fa-arrow-alt-circle-right"></i></a>';
                    }
                }
                else
                {
                    if($status_administrasi == '2')
                        $aksi = '<h4>0</h4>';
                    else
                        $aksi = '<a href="'.$nilai.'" class="btn btn-icon-sm btn-warning btn-sm">Beri nilai<i class="fas fa-arrow-alt-circle-right"></i></a>';
                }
            }
            else
                $aksi = '<span class="badge bg-info">Administrasi belum dipilih</span>';

            $data_arr[] = array(
                "DT_RowId" => 'row_'.$hitung,
                "proposal_id" => $proposal_id,
                "kode" => $kode,
                "jenis_pkm" => $jenis_pkm,
                "judul" => $judul,
                "status" => $status,
                "proposal" => $proposal,
                "administrasi" => $administrasi,
                "aksi" => $aksi
            );
            $hitung++;
        }

        $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)
    {
        $id = $request->input('reviewer_proposal_id');
        $data['komentar'] = $request->input('komentar');
        $data['revisi_nilai'] = 0;

        $reviewer_proposal = ReviewerProposal::findOrFail($id);
        $reviewer_proposal->update($data);

        $delete = ReviewerProposalDetil::where('reviewer_proposal_id', $id)->delete($id);

        for($i=0; $i<count($request->jenis_penilaian_id); $i++)
        {
            $uuid = Uuid::generate();
            $data['reviewer_proposal_detil_id'] = $uuid;
            $data['reviewer_proposal_id'] = $id;
            $data['jenis_penilaian_monev_id'] = $request->jenis_penilaian_id[$i];
            $data['skor'] = $request->skor[$i];

            ReviewerProposalDetil::create($data);
        }

        Alert::success('Data berhasil disimpan.')->persistent('Ok');

        return redirect()->route('reviewer.seleksi-internal.index');
    }

    public function show($id)
    {

    }

    public function edit($id)
    {
        $urut = DB::select("select ambil_data_reviewer_proposal('".$this->rBiodata->noidentitas."', '".decrypt($id)."', '1')")[0]->ambil_data_reviewer_proposal;

        $title      = 'Penilaian Proposal Seleksi Internal';
        $proposal = DaftarProposal::query()->with('proposalUrl')->where('proposal_id', decrypt($id))->first();
        $reviewer_proposal = ReviewerProposal::with('rReviewerProposalDetil')->where('proposal_id', decrypt($id))->where('urut', $urut)->first();
        $komponen = JenisPenilaianMonev::where('jenis_id', $proposal->jenis_id)->get();

        $detil = array();
        foreach($reviewer_proposal->rReviewerProposalDetil as $res => $val)
        {
            $detil[$val->jenis_penilaian_monev_id] = $val->skor;
        }

        $data = [
            'title'     => $title,
            'proposal'  => $proposal,
            'komponen' => $komponen,
            'reviewer_proposal' => $reviewer_proposal,
            'detil' => $detil
        ];

        return view('backend.reviewer.seleksi.nilai', $data);
    }

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

    }

    public function destroy($id)
    {

    }

    public function approval($id, $status)
    {
        try {
            $urut = DB::select("select ambil_data_reviewer_proposal('".$this->rBiodata->noidentitas."', '".decrypt($id)."', '1')")[0]->ambil_data_reviewer_proposal;
            $delete = ReviewerProposal::where('proposal_id', Crypt::decrypt($id))->where('urut', $urut)->update(['status_administrasi'=>$status]);

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