<?php

namespace App\Http\Controllers\Operator;

use DB;
use URL;

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

use App\Models\Periode;
use App\Models\Proposal;
use Illuminate\Http\Request;
use App\Models\DaftarProposal;
use App\Exports\ProposalExport;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Log;

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

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

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

        ## Read value
        $year = !is_null($request->year) ? $request->year : now()->year;
        $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 = " STATUS_HAPUS = '0' ";

        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 = DaftarProposal::select('count(1) as allcount')->whereRaw($statementGlobal)->count();
        $totalRecords = DaftarProposal::query()->whereRaw($statementGlobal)->count();

        $statement = " AND (UPPER(JUDUL) LIKE '%".$searchValue."%' OR UPPER(IDENTITAS_KETUA) LIKE '%".$searchValue."%' OR UPPER(IDENTITAS_DOSPEM) LIKE '%".$searchValue."%') ";


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

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

        $data_arr = array();
        foreach($records as $record){
            $proposal_id = $record->proposal_id;
            $kode = $record->kode;
            $identitas_ketua = str_replace('###', '<br>', $record->identitas_ketua);
            $identitas_dospem = str_replace('###', '<br>', $record->identitas_dospem);
            $jenis_pkm = $record->jenis_pkm;
            $judul = $record->judul;
            $status = $record->status;
            $upload_dokumen = $record->upload_dokumen;
            $date_upload = Carbon::parse($record->date_upload)->format('d-m-Y H:i')?:'';
            $date_approval = Carbon::parse($record->date_approval)->format('d-m-Y H:i')?:'';

            if($upload_dokumen == null || $upload_dokumen == '')
            {
                $keterangan = '<span class="badge bg-danger">Belum Upload Proposal</span>';
            }
            else
            {
                $url = "https://statik.unesa.ac.id/simpmw/proposal/".$record->periode."/".$record->upload_dokumen;

                if($status == '1')
                {
                    $keterangan = '<span class="badge bg-success">Disetujui Dosen</span>';
                    $aksi = '<a style="margin-right: 5px;" class="btn btn-warning btn-sm waves-effect waves-light aksi" role="button" data-toggle="tooltip" data-placement="bottom" title="Batalkan Status" data-ket="Proposal Kelompok yang dibatalkan status diterima akan otomatis menjadi status ditolak agar dapat menunggah ulang Proposal." data-id="'.Crypt::encrypt($proposal_id.'#2').'"><i class="fas fa-undo"></i></a>';
                }
                elseif($status == '2')
                {
                    $keterangan = '<span class="badge bg-danger">Ditolak Dosen</span>';
                    $aksi = '';
                }
                else
                {
                    $keterangan = '<span class="badge bg-warning">Menunggu Persetujuan Dosen</span>';
                    $aksi = '<a style="margin-right: 5px;" class="btn btn-success btn-sm waves-effect waves-light aksi" role="button" data-toggle="tooltip" data-placement="bottom" title="Setujui Proposal" data-ket="Proposal Kelompok disetujui" data-id="'.Crypt::encrypt($proposal_id.'#1').'"><i class="fas fa-check"></i></a> <a class="btn btn-danger btn-sm waves-effect waves-light aksi" role="button" data-toggle="tooltip" data-placement="bottom" title="Tolak Proposal" data-ket="Proposal Kelompok ditolak" data-id="'.Crypt::encrypt($proposal_id.'#2').'"><i class="fas fa-times"></i></a>';
                }
            }

            // $aksi .= ' <a href="'.$url.'" target="_blank" class="btn btn-primary btn-sm waves-effect waves-light" role="button"data-toggle="tooltip" data-placement="bottom" title="Lihat Proposal"><i class="fas fa-search"></i></a>';

            $aksi .= '
                    <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' . $record->id . '">
                        <i class="fas fa-search"></i>
                    </a>';

                // Modal lihat proposal
                $aksi .= '
                    <div class="modal fade" id="proposalModal' . $record->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>Status</th>
                                                <td>' . $keterangan . '</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>';
                                                if ($record->url) {
                                                    $aksi .= '<button id="preview-video' . $record->id . '" class="btn btn-success btn-sm" data-video="' . $record->url . '">
                                                                <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" . $record->id . "').on('click', function() {
                        var videoUrl = $(this).attr('data-video');
                        if (videoUrl) {
                            if (videoUrl.includes('youtu.be')) {
                                videoUrl = videoUrl.split('?')[0];
                            } else if (videoUrl.includes('youtube.com')) {
                                videoUrl = videoUrl.split('&')[0];
                            }
                            if (isValidYouTubeUrl(videoUrl)) {
                                var currentModal = $('#proposalModal" . $record->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>
                ";


            $keterangan .= "<br><span class='badge bg-info'>Upload Proposal Pada : ".$date_upload." WIB</span>";
            $keterangan .= "<br><span class='badge bg-info'>Disetujui Dosen Pada : ".$date_approval." WIB</span>";


            $data_arr[] = array(
                "proposal_id" => $proposal_id,
                "kode" => $kode,
                "identitas_ketua" => $identitas_ketua,
                "identitas_dospem" => $identitas_dospem,
                "jenis_pkm" => $jenis_pkm,
                "judul" => $judul,
                "keterangan" => $keterangan,
                "aksi" => $aksi
            );
        }

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

        echo json_encode($response);
        exit;
    }

    public function getDetil(Request $request)
    {
        $reqKelompokId = Crypt::decrypt($request->kelompok_id);
        $kelompok_detil = KelompokDetail::where('kelompok_id', $reqKelompokId)->get();

        $data = '';
        $no = 1;
        foreach ($kelompok_detil as $key => $value) {
            if($value->status_ketua == 1)
                $keterangan = "Ketua";
            else
                $keterangan = "Anggota ".$no-1;
            $data .= "
                            <tr>
                                <td>".$no."</td>
                                <td>".$value->nama."</td>
                                <td>".$value->nim."</td>
                                <td>".$value->fakultas."</td>
                                <td>".$value->prodi."</td>
                                <td>".$keterangan."</td>
                            </tr>
                    ";
            $no++;
        }
        $response['html'] = $data;
        echo json_encode($response);
    }

    public function create()
    {

    }

    public function store(Request $request)
    {

    }

    public function edit($id)
    {

    }

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

    }

    public function destroy($id)
    {

    }

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

        // $export = new ProposalExport($jenis, $status, $tahun);

        // return Excel::download(new ProposalExport($jenis, $status, $tahun), 'proposal_export.xlsx');
        // return $export->view();
        // Mulai pencatatan waktu
        $startTime = microtime(true);

        // Ekspor ke Excel
        $response = Excel::download(new ProposalExport($jenis, $status, $tahun), 'daftar-proposal-pmw-'.$tahun.'_export.xlsx');

        // Akhir pencatatan waktu
        $endTime = microtime(true);

        // Hitung waktu yang dibutuhkan dalam detik
        $executionTime = $endTime - $startTime;

        // Log waktu yang dibutuhkan
        Log::info('Waktu yang dibutuhkan untuk proses ekspor: ' . $executionTime . ' detik');

        return $response;
    }

    public function prosesProposal(Request $request)
    {
        $kel = $request->except('_token');

        $arrKel = explode('#', decrypt($kel['proposalId']));
        $reqProposalId = $arrKel['0'];
        $reqStatus = $arrKel['1'];

        $proposal = Proposal::query()->find($reqProposalId);

        $proposal->status = $reqStatus;
        $proposal->date_approval = now();
        $proposal->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Data Berhasil diubah.',
        ]);
    }
}
