<?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;

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();
        $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/simpkm/proposal/".$record->periode."/".$record->upload_dokumen;

                if($status == '1')
                {
                    $keterangan = '<span class="badge bg-success">Disetujui Dosen</span>';
                    $aksi = '<a class="btn btn-warning btn-sm waves-effect waves-light aksi" role="button" 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 class="btn btn-success btn-sm waves-effect waves-light aksi" role="button" 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-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"><i class="fas fa-search"></i></a>';

            $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;

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

    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.',
        ]);
    }
}
