<?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;
use App\Models\BuktiAnggaran;
use App\Models\JenisSatuanBarang;
use App\Models\MonevInternal;
use App\Models\Proposal;
use Illuminate\Support\Facades\Log;

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', 'jenis_monev'))->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();

        $path = [
            '07cda89b-94ca-42a3-a197-8fc1260ebcfb' => 'monev/I',
            '21a49a70-33bb-49f1-9fd9-ebe52fa4336c' => 'monev/II'
        ];

        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;
            $upload_dokumen = $record->upload_dokumen;
            $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;
            $rata = $record->rata;
            $logbook = is_null($record->logbook_file) ? '<span class="badge bg-danger">File logbook belum diunggah</span>' : '<a href="https://statik.unesa.ac.id/simpmw/'.$path[$record->jenis_monev_id].'/logbook/'.$record->logbook_file.'" class="btn btn-primary btn-sm waves-effect waves-light" role="button" target="_blank">Review <i class="fas fa-search"></i></a>';
            $laporan_kemajuan = is_null($record->kemajuan_file) ? '<span class="badge bg-danger">File laporan kemajuan belum diunggah</span>' : '<a href="https://statik.unesa.ac.id/simpmw/'.$path[$record->jenis_monev_id].'/kemajuan/'.$record->kemajuan_file.'" class="btn btn-primary btn-sm waves-effect waves-light" role="button" target="_blank">Review <i class="fas fa-search"></i></a>';
            $laporan_akhir = is_null($record->akhir_file) ? '<span class="badge bg-danger">File laporan akhir belum diunggah</span>' : '<a href="https://statik.unesa.ac.id/simpmw/'.$path[$record->jenis_monev_id].'/akhir/'.$record->akhir_file.'" class="btn btn-primary btn-sm waves-effect waves-light" role="button" target="_blank">Review <i class="fas fa-search"></i></a>';
            $laporan_luaran = '<a href="' . route('reviewer.luaran-reviewer', encrypt($record->proposal_id)) . '" class="btn btn-primary btn-sm waves-effect waves-light" role="button" target="_blank">Review <i class="fas fa-search"></i></a>';
            $laporan_anggaran = '<a href="' . route('operator.laporan-anggaran', encrypt($record->monev_internal_id)) . '" class="btn btn-primary btn-sm waves-effect waves-light" role="button" target="_blank">Review <i class="fas fa-search"></i></a>';
            $produk_akhir = is_null($record->produk_akhir) ? '<span class="badge bg-danger>Produk Akhir belum diunggah</span>' : '<a href="' . $record->produk_akhir . '" class="btn btn-primary btn-sm waves-effect waves-light" role="button" target="_blank">Review <i class="fas fa-search"></i></a>';
            $video = DaftarProposalMonev::where('proposal_id', $proposal_id)
                    ->where('monev_internal_id', $monev_internal_id)
                    ->pluck('url');

            // $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><br/>
                        <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 . '-' . $monev_internal_id . '"><i class="fas fa-search"></i></a>';
            }
            elseif($status_final == '2')
            {
                $aksi = '<span class="badge bg-danger">Tidak Lolos</span><br/>
                        <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 . '-' . $monev_internal_id . '"><i class="fas fa-search"></i></a>';
            }
            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>
                        <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 . '-' . $monev_internal_id . '"><i class="fas fa-search"></i></a>
                    </td>';
            }
            $url = 'https://statik.unesa.ac.id/simpmw/proposal/'. $record->periode .'/'. $record->upload_dokumen;
            $aksi .= '
                    <div class="modal fade" id="proposalModal' . $proposal_id . '-' . $monev_internal_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>
                                                <tr>
                                                    <th>Logbook</th>
                                                    <td>' . $logbook . '</td>
                                                </tr>
                                                <tr>
                                                    <th>Laporan Kemajuan</th>
                                                    <td>' . $laporan_kemajuan . '</td>
                                                </tr>';

                                        if ($record->jenis_monev_id !== '07cda89b-94ca-42a3-a197-8fc1260ebcfb') {
                                            $aksi .= '
                                                <tr>
                                                    <th>Laporan Akhir</th>
                                                    <td>' . $laporan_akhir . '</td>
                                                </tr>
                                                <tr>
                                                    <th>Laporan Anggaran</th>
                                                    <td>' . $laporan_anggaran . '</td>
                                                </tr>';
                                        }

                                        $aksi .= '
                                                <tr>
                                                    <th>Laporan Lainnya</th>
                                                    <td>' . $laporan_luaran . '</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 . "-" . $monev_internal_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>
                    ";

            $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 {
            Log::debug(Crypt::decrypt($id));
            $delete = ReviewerMonev::where('monev_internal_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) {
            Log::error($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 reviewAnggaran($id)
    {
        $monev_id = decrypt($id);
        $title    = 'Laporan Anggaran Mahasiswa';
        $anggaran = BuktiAnggaran::with(['rProposal', 'rMonev'])
                    ->where('monev_id', $monev_id)
                    ->get();

        $monev = MonevInternal::with(['rProposal', 'rBuktiAnggaran' => function($query) {
                    $query->orderByRaw('CASE WHEN tgl_pembelian IS NULL THEN 0 ELSE 1 END ASC, tgl_pembelian ASC');
                }])
                ->where('id', $monev_id)
                ->first();

        $jenis_satuan = JenisSatuanBarang::select('jenis_satuan')
            ->get();

        $kelompok = DaftarProposalMonev::with(['rKelompokDetil'])
                    ->where('monev_internal_id', $monev_id)
                    ->first();

        $data = [
            'title'         => $title,
            'monev'         => $monev,
            'anggaran'      => $anggaran,
            'kelompok'      => $kelompok,
            'jenis_satuan'  => $jenis_satuan
        ];

        return view('backend.operator.anggaran.index', $data);
    }

    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;
        $monev = $request->monev;

        $filename = sprintf(
            'seleksi_monev_internal_%s_export.xlsx',
            $monev == 'Monev Internal I' ? 'i' : 'ii'
        );

        return Excel::download(new DaftarProposalMonevExport($jenis, $status, $tahun, $monev), $filename);

        // $data = new DaftarProposalMonevExport($jenis, $status, $tahun, $monev);
        // return $data->view();
    }
}
