<?php

use App\Models\Master\MasterMenu;
use App\Models\Master\MasterAccessMenu;
use App\Models\Kuesioner;
use App\Models\KuesionerLog;
use App\Models\Master\FormKriteria;
use App\Models\Penilaian;
use App\Models\PenilaianFile;
use App\Models\ProfileSekolah;
use App\Models\User;
use App\Models\Master\Sekolah;
use App\Models\SK;
use App\Models\Master\MasterGroup;

if (!function_exists('tahunKuesioner')) {
    function tahunKuesioner($id){
        $kuesioner = Kuesioner::find($id);
        if($kuesioner->tahun >= '2026'){
            $tahun = '2026';
        }else{
            $tahun = '2025';
        }
        return $tahun;
    }
}

if (!function_exists('sekolah')) {
    function sekolah($id){
        $sekolah = Sekolah::find($id);
        return $sekolah;
    }
}

if (!function_exists('monthtString')) {

    /**
     * Date format based on active locale
     *
     * @param $date
     * @return string
     */
    function monthtString($val)
    {
        $result = $val;
        if (!empty($val)) {
            $month = [
                "Januari",
                "Februari",
                "Maret",
                "April",
                "Mei",
                "Juni",
                "Juli",
                "Agustus",
                "September",
                "Oktober",
                "November",
                "Desember",
                ];
            $result = $month[(int)$val - 1];
        }
        return ($result);
    }
}

if (!function_exists('listSekolah')) {
    function listSekolah($sekolah){


        $res = "Belum ada data";
            $res = [];
            $d = '';
            foreach (json_decode($sekolah) as $key => $value) {
                $d .= '<span class="badge bg-success-light text-success">'.@sekolah($value)->nama_sekolah.'</span><br>';
                
            }
            array_push($res, $d);

            $res = implode("", $res);

        return $res;
    }
}


if (!function_exists('getPenghargaanTerakhir')) {
    /**
     * @param $val
     *
     * @return string
     */
    function getPenghargaanTerakhir($sekolah_id)
    {

        $usulan = Kuesioner::where('ms_sekolah_id',$sekolah_id)->where('tahun',date('Y'))->first();

        if($usulan->level == 0){
            $usulanAwal = 'Belum Pernah';
        }elseif($usulan->level == 1){
            $usulanAwal = 'Adiwiyata Kab/Kota';
        }elseif($usulan->level == 2){
            $usulanAwal = 'Adiwiyata Provinsi';
        }elseif($usulan->level == 3){
            $usulanAwal = 'Adiwiyata Nasional';
        }elseif($usulan->level == 4){
            $usulanAwal = 'Adiwiyata Mandiri';
        }

        return $usulanAwal;
    }
}

if (!function_exists('getUsulan')) {
    /**
     * @param $val
     *
     * @return string
     */
    function getUsulan($sekolah_id)
    {

        $usulan = Kuesioner::where('ms_sekolah_id',$sekolah_id)->where('tahun',date('Y'))->first();

        if(($usulan->level+1) == 1){
            $jenis_usulan = 'Adiwiyata Kab/Kota';
        }elseif(($usulan->level+1) == 2){
            $jenis_usulan = 'Adiwiyata Provinsi';
        }elseif(($usulan->level+1) == 3){
            $jenis_usulan = 'Adiwiyata Nasional';
        }elseif(($usulan->level+1) == 4){
            $jenis_usulan = 'Adiwiyata Mandiri';
        }

        return $jenis_usulan;
    }
}

if (!function_exists('getNilaiAll')) {
    /**
     * @param $val
     *
     * @return string
     */
    function getNilaiAll($type,$sekolah_id,$kuesionerId = null)
    {
        $tahun = tahunKuesioner($kuesionerId);
        $kuesioner = Kuesioner::find($kuesionerId);
        // $countSoal = FormKriteria::select('page_number')->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->count();
        if($type == 'sekolah'){
            // III  = ((SUM(D246:D252)/11)*20)
            // II   = ((SUM(D35:D243)/89)*60)
            // I    = ((SUM(D9:D30)/19)*20)

            $kriteria1 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','I. Kebijakan')->pluck('page_number')->toArray();
            $nilai1  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria1)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',0) //inputan sekolah
            ->sum('skor');

            $kriteria2 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','II. Proses Pembelajaran')->pluck('page_number')->toArray();
            $nilai2  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria2)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',0) //inputan sekolah
            ->sum('skor');

            $kriteria3 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','III. Kegiatan Berbasis Partisipatif')->pluck('page_number')->toArray();
            $nilai3  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria3)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',0) //inputan sekolah
            ->sum('skor');

            $kriteria4 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','IV. Prasarana dan Sarana')->pluck('page_number')->toArray();
            $nilai4  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria4)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',0) //inputan sekolah
            ->sum('skor');

            // dd($kriteria4);

            $nilai = (round(($nilai4/34)*30))+(($nilai3/45)*30)+(($nilai2/16)*30)+(($nilai1/9)*10);

        }elseif($type == 'kota'){
            $kriteria1 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','I. Kebijakan')->pluck('page_number')->toArray();
            $nilai1  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria1)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',1) //inputan Kota
            ->sum('skor');

            $kriteria2 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','II. Proses Pembelajaran')->pluck('page_number')->toArray();
            $nilai2  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria2)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',1) //inputan Kota
            ->sum('skor');

            $kriteria3 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','III. Kegiatan Berbasis Partisipatif')->pluck('page_number')->toArray();
            $nilai3  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria3)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',1) //inputan Kota
            ->sum('skor');

            $kriteria4 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','IV. Prasarana dan Sarana')->pluck('page_number')->toArray();
            $nilai4  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria4)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',1) //inputan kota
            ->sum('skor');

            $nilai = (round(($nilai4/34)*30))+(($nilai3/45)*30)+(($nilai2/16)*30)+(($nilai1/9)*10);
        }elseif($type == 'provinsi'){
            $kriteria1 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','I. Kebijakan')->pluck('page_number')->toArray();
            $nilai1  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria1)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',2) //inputan provinsi
            ->sum('skor');

            $kriteria2 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','II. Proses Pembelajaran')->pluck('page_number')->toArray();
            $nilai2  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria2)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',2) //inputan provinsi
            ->sum('skor');

            $kriteria3 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','III. Kegiatan Berbasis Partisipatif')->pluck('page_number')->toArray();
            $nilai3  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria3)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',2) //inputan provinsi
            ->sum('skor');

            $kriteria4 = FormKriteria::select('page_number')->where('tahun',$tahun)->groupBy('page_number')->where('kategori','IV. Prasarana dan Sarana')->pluck('page_number')->toArray();
            $nilai4  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria4)
            ->where('skor','!=',0)
            ->where('tahun',$kuesioner->tahun)
            ->where('status',2) //inputan provinsi
            ->sum('skor');

            $nilai = (round(($nilai4/34)*30))+(($nilai3/45)*30)+(($nilai2/16)*30)+(($nilai1/9)*10);
        }

        return @$nilai ? round(@$nilai) : 0;
    }
}

if (!function_exists('getNilaiAll2025')) {
    /**
     * @param $val
     *
     * @return string
     */
    function getNilaiAll2025($type,$sekolah_id)
    {
        // $countSoal = FormKriteria::select('page_number')->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->count();
        if($type == 'sekolah'){
            // III  = ((SUM(D246:D252)/11)*20)
            // II   = ((SUM(D35:D243)/89)*60)
            // I    = ((SUM(D9:D30)/19)*20)

            $kriteria1 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','I.Perencanaan Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai1  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria1)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',0) //inputan sekolah
            ->sum('skor');

            $kriteria2 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','II.Pelaksanaan Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai2  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria2)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',0) //inputan sekolah
            ->sum('skor');

            $kriteria3 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','III.Pemantauan dan Evaluasi Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai3  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria3)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',0) //inputan sekolah
            ->sum('skor');

            $nilai = (($nilai3/11)*20)+(($nilai2/89)*60)+(($nilai1/19)*20);

        }elseif($type == 'kota'){
            $kriteria1 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','I.Perencanaan Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai1  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria1)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',1) //inputan Kota
            ->sum('skor');

            $kriteria2 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','II.Pelaksanaan Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai2  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria2)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',1) //inputan Kota
            ->sum('skor');

            $kriteria3 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','III.Pemantauan dan Evaluasi Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai3  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria3)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',1) //inputan Kota
            ->sum('skor');

            $nilai = (($nilai3/11)*20)+(($nilai2/89)*60)+(($nilai1/19)*20);
        }elseif($type == 'provinsi'){
            $kriteria1 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','I.Perencanaan Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai1  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria1)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',2) //inputan provinsi
            ->sum('skor');

            $kriteria2 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','II.Pelaksanaan Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai2  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria2)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',2) //inputan provinsi
            ->sum('skor');

            $kriteria3 = FormKriteria::select('page_number')->groupBy('page_number')->where('kategori','III.Pemantauan dan Evaluasi Gerakan PBLHS')->pluck('page_number')->toArray();
            $nilai3  = Penilaian::where('ms_sekolah_id',$sekolah_id)->whereIn('page_number',$kriteria3)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',2) //inputan provinsi
            ->sum('skor');

            $nilai = (($nilai3/11)*20)+(($nilai2/89)*60)+(($nilai1/19)*20);
        }

        return @$nilai ? round(@$nilai) : 0;
    }
}

if (!function_exists('getNilai')) {
    /**
     * @param $val
     *
     * @return string
     */
    function getNilai($type,$page_number,$sekolah_id)
    {
        if($type == 'sekolah'){
            $nilai  = Penilaian::where('ms_sekolah_id',$sekolah_id)
            ->where('page_number',$page_number)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',0) //inputan sekolah
            ->first();
        }elseif($type == 'kota'){
            $nilai  = Penilaian::where('ms_sekolah_id',$sekolah_id)
            ->where('page_number',$page_number)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',1) //inputan sekolah
            ->first();
        }elseif($type == 'provinsi'){
            $nilai  = Penilaian::where('ms_sekolah_id',$sekolah_id)
            ->where('page_number',$page_number)
            ->where('skor','!=',0)
            ->where('tahun',date('Y'))
            ->where('status',2) //inputan sekolah
            ->first();
        }

        return @$nilai ? @$nilai->skor : 0;
    }
}
if (!function_exists('kuesionerLogStatus')) {
    /**
     * @param $val
     *
     * @return string
     */
    function kuesionerLogStatus($KuesionerId,$plain = null)
    {
        $log  = KuesionerLog::where('kuesioner_id',$KuesionerId)->orderBy('KuesionerLogId','DESC')->first();
        if($plain == 'plain'){
            $progress = str_replace('_',' ',\Str::title($log->step));
        }else{
            if(@$log->status == 11){
                $progress = '<span class="badge bg-success text-white">Terbit SK</span>';
            }else{
                $progress = '<span class="badge bg-warning text-white">'.str_replace('_',' ',\Str::title($log->step)).'</span>';
            }
        }
        return $progress;
    }
}

if (!function_exists('StatusActivity')) {
    /**
     * @param $val
     *
     * @return string
     */
    function StatusActivity($sekolah)
    {
        $kuesioner  = Kuesioner::where('ms_sekolah_id',$sekolah)->first();
        if(!@$kuesioner){
            $text = '<span class="badge bg-primary text-white">Sekolah mendaftar Akun</span>';
        }else{
            $profile = ProfileSekolah::where('ms_sekolah_id',$sekolah)->first();
            if(@$profile){
                $text = '<span class="badge bg-primary text-white">Sekolah mengisi profil sekolah.</span>';    
            }
        }

        return $text;
    }
}

if (!function_exists('status_kuesioner')) {
    /**
     * @param $val
     *
     * @return string
     */
    function status_kuesioner()
    {
        //0 = Belum di Verifikasi Dinas
        //1 = Sudah Diusulkan Oleh Dinas atau Sudin
        //2 = Approve Dokumen
        //3 = Kirim Ke Penilai Kota ( Proses Penilaian )
        //4 = Selesai Penilaian Kota
        //5 = Dikembalikan Penilaian Kota ke Sekolah
        //6 = Selesai Penilaian Provinsi
        //7 = Dikembalikan Penilaian Provinsi ke Kota
        //8 = Selesai Penilaian Nasional
        //9 = Selesai Penilaian Mandiri
        //10 = Selesai Final
        //11 = Terbit SK
    }
}

if (!function_exists('group')) {
    /**
     * @param $val
     *
     * @return string
     */
    function group($id)
    {
        $user = User::find($id);
        $group = MasterGroup::where('MsGroupId',$user->ms_group_id)->first();
        return @$group;
    }
}

if (!function_exists('user')) {
    /**
     * @param $val
     *
     * @return string
     */
    function user($id)
    {
        $user = User::find($id);
        return @$user;
    }
}

if (!function_exists('checkCatatan')) {
    /**
     * @param $val
     *
     * @return string
     */
    function checkCatatan($page_number,$sekolah_id = null,$type = null,$kuesionerId = null)
    {
        if(@$sekolah_id){
            $idSekolah = @$sekolah_id;
        }else{
            $idSekolah = session('sekolah_id');
        }

        if(@$type == 'kota'){
            $penilaian = Penilaian::whereHas('page',function($query) use ($kuesionerId){
                $query->where('tahun',tahunKuesioner($kuesionerId));
            })->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',1)->first();
        }elseif(@$type == 'provinsi'){
            $penilaian = Penilaian::whereHas('page',function($query) use ($kuesionerId){
                $query->where('tahun',tahunKuesioner($kuesionerId));
            })->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',2)->first();
        }else{
            $penilaian = Penilaian::whereHas('page',function($query) use ($kuesionerId){
                $query->where('tahun',tahunKuesioner($kuesionerId));
            })->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',0)->first();
        }

        if($penilaian == true){
            $catatan = Penilaian::where('key','catatan')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->first();
            $valueCatatan = json_decode(@$catatan->value);
            if($valueCatatan != null){
                return '<i class="fal fa-info-circle"></i> ';
            }
        }else{
            return '';
        }

        // return @$penilaian ? true : false;
    }
}

if (!function_exists('checkPenilaian')) {
    /**
     * @param $val
     *
     * @return string
     */
    function checkPenilaian($page_number,$sekolah_id = null,$type = null,$kuesionerId = null)
    {
        if(@$sekolah_id){
            $idSekolah = @$sekolah_id;
        }else{
            $idSekolah = session('sekolah_id');
        }

        if(@$type == 'kota'){
            $penilaian = Penilaian::whereHas('page',function($query) use ($kuesionerId){
                $query->where('tahun',tahunKuesioner($kuesionerId));
            })->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',1)->first();
        }elseif(@$type == 'provinsi'){
            $penilaian = Penilaian::whereHas('page',function($query) use ($kuesionerId){
                $query->where('tahun',tahunKuesioner($kuesionerId));
            })->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',2)->first();
        }else{
            $penilaian = Penilaian::whereHas('page',function($query) use ($kuesionerId){
                $query->where('tahun',tahunKuesioner($kuesionerId));
            })->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',0)->first();
        }

        if($penilaian == true){
            // $catatan = Penilaian::where('key','catatan')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->first();
            // $valueCatatan = json_decode(@$catatan->value);
            return 'bg-success-light text-success border-success rounded';
        }else{
            return 'border-secondary rounded';
        }

        // return @$penilaian ? true : false;
    }
}
if (!function_exists('hitungSkor')) {
    /**
     * @param $val
     *
     * @return string
     */
    function hitungSkor($key,$val,$lainnya = [])
    {

        $skor = 0;
        $countLainnya = 0;
        if(@$lainnya){
            $countLainnya = count(array_filter($lainnya, function ($value) {
                return !is_null($value);
            }));
        }

        //BARU
        if($key == 'kebijakan_terkait_lingkungan'){

            $array1 = ['Visi, Misi dan Tujuan Sekolah Tidak Terkait Aspek Lingkungan'];
            $array2 = ["Visi"];
            $array3 = ["Visi", "Misi"];
            $array4 = ["Visi", "Misi", "Tujuan Sekolah"];

            if(!empty($val) && !is_array($val)){
                $val = array($val);
            }

            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            } elseif (!array_diff($array2, $val) && !array_diff($val, $array2)) {
                $skor = 1;
            } elseif (!array_diff($array3, $val) && !array_diff($val, $array3)) {
                $skor = 2;
            } elseif (!array_diff($array4, $val) && !array_diff($val, $array4)) {
                $skor = 3;
            }  else {
                $skor = 0;
            }
        }elseif($key == 'aspek_tata_terib'){
            $array1 = ["SK/Tatib Tidak Terkait Aspek Lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) <= 2){
                        $skor = 1;
                    }elseif(count($val) <= 4){
                        $skor = 2;
                    }else{
                        $skor = 3;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'aspek_diedukasikan'){
            $array1 = ["Bahan Informasi lingkungan di sekolah tidak terkait 5 aspek lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) <= 2){
                        $skor = 1;
                    }elseif(count($val) <= 4){
                        $skor = 2;
                    }else{
                        $skor = 3;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'aspek_jurnal_rpp'){
            $array1 = ["Jurnal Guru dan RPP Tidak Terkait Aspek Lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) <= 2){
                        $skor = 1;
                    }elseif(count($val) <= 4){
                        $skor = 2;
                    }else{
                        $skor = 3;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'jurnal_rpp'){
            if($val == 0){
                $skor = 0;
            }elseif(($val >= 1) && ($val <= 2)){
                $skor = 1;
            }elseif(($val >= 3) && ($val <= 4)){
                $skor = 2;
            }elseif(($val >= 5) && ($val <= 6)){
                $skor = 3;
            }elseif(($val >= 7) && ($val <= 8)){
                $skor = 4;
            }elseif(($val > 8)){
                $skor = 5;
            }else{
                $skor = 0;
            }
        }elseif($key == 'aspek_eskul'){
            $array1 = ["Jurnal Ekstrakurikuler Tidak Terkait Aspek Lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) <= 2){
                        $skor = 1;
                    }elseif(count($val) <= 4){
                        $skor = 2;
                    }else{
                        $skor = 3;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'aspek_karya_siswa'){
            $array1 = ["Tidak Ada Hasil Karya Siswa yang terkait Aspek Lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) == 1){
                        $skor = 1;
                    }elseif(count($val) == 2){
                        $skor = 2;
                    }elseif(count($val) == 3){
                        $skor = 3;
                    }elseif(count($val) == 4){
                        $skor = 4;
                    }elseif(count($val) == 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'aspek_lingkungan_rutin'){
            $array1 = ["Tidak Ada Aspek Rutin Terkait Aspek Lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) == 1){
                        $skor = 1;
                    }elseif(count($val) == 2){
                        $skor = 2;
                    }elseif(count($val) == 3){
                        $skor = 3;
                    }elseif(count($val) == 4){
                        $skor = 4;
                    }elseif(count($val) == 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'kegiatan_rutin'){
            $array1 = ["Tidak Ada Program Rutin"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if((count($val) >= 1) && (count($val) <= 2)){
                        $skor = 1;
                    }elseif((count($val) >= 3) && (count($val) <= 4)){
                        $skor = 2;
                    }elseif(count($val) == 5){
                        $skor = 3;
                    }elseif(count($val) == 6){
                        $skor = 4;
                    }elseif(count($val) > 6){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'aspek_lingkungan_nonrutin'){
            $array1 = ["Tidak Ada Aspek Lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) == 1){
                        $skor = 1;
                    }elseif(count($val) == 2){
                        $skor = 2;
                    }elseif(count($val) == 3){
                        $skor = 3;
                    }elseif(count($val) == 4){
                        $skor = 4;
                    }elseif(count($val) == 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'kegiatan_kampanye'){
            $array1 = ["Tidak Ada Kegiatan Kampanye/Publikasi"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                $jumlh = (count($val) + $countLainnya);
                if(is_array($val)){
                    if($jumlh == 1){
                        $skor = 1;
                    }elseif($jumlh == 2){
                        $skor = 2;
                    }elseif($jumlh == 3){
                        $skor = 3;
                    }elseif($jumlh == 4){
                        $skor = 4;
                    }elseif($jumlh >= 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'media_publikasi'){
            $array1 = ["Tidak Ada Media Publikasi"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                $jumlh = (count($val) + $countLainnya);
                if(is_array($val)){
                    if($jumlh == 1){
                        $skor = 1;
                    }elseif($jumlh == 2){
                        $skor = 2;
                    }elseif($jumlh == 3){
                        $skor = 3;
                    }elseif($jumlh == 4){
                        $skor = 4;
                    }elseif($jumlh >= 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'jumlah_kegiatan_adiwiyata'){
            $array1 = ["Tidak Ada Kegiatan Pemberdayaan Kader"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                $jumlh = (count($val) + $countLainnya);
                if(is_array($val)){
                    if($jumlh == 1){
                        $skor = 1;
                    }elseif($jumlh == 2){
                        $skor = 2;
                    }elseif($jumlh == 3){
                        $skor = 3;
                    }elseif($jumlh == 4){
                        $skor = 4;
                    }elseif($jumlh >= 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'kegiatan_sekolah'){
            $array1 = ["Tidak Ada Kegiatan Diinisiasi Sekolah"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                $jumlh = (count($val) + $countLainnya);
                if(is_array($val)){
                    if($jumlh == 1){
                        $skor = 1;
                    }elseif($jumlh == 2){
                        $skor = 2;
                    }elseif($jumlh == 3){
                        $skor = 3;
                    }elseif($jumlh == 4){
                        $skor = 4;
                    }elseif($jumlh >= 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'kerjasama'){
            $array1 = ["Tidak Ada Kerjasama dengan pihak lain terkait lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                $jumlh = (count($val) + $countLainnya);
                if(is_array($val)){
                    if($jumlh == 1){
                        $skor = 1;
                    }elseif($jumlh == 2){
                        $skor = 2;
                    }elseif($jumlh == 3){
                        $skor = 3;
                    }elseif($jumlh == 4){
                        $skor = 4;
                    }elseif($jumlh >= 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'sarpras_lingkungan'){
            $array1 = ["Prasarana dan Sarana yang dimanfaatkan menjadi media pembelajaran tidak terkait 5 aspek lingkungan"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) == 1){
                        $skor = 1;
                    }elseif(count($val) == 2){
                        $skor = 2;
                    }elseif(count($val) == 3){
                        $skor = 3;
                    }elseif(count($val) == 4){
                        $skor = 4;
                    }elseif(count($val) == 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'sarpras_sanitasi'){
            $array1 = ["Tidak ada prasarana dan sarana sanitasi"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) == 1){
                        $skor = 1;
                    }elseif(count($val) == 2){
                        $skor = 2;
                    }elseif(count($val) == 3){
                        $skor = 3;
                    }elseif(count($val) == 4){
                        $skor = 3;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'sarpras_sampah'){
            $array1 = ["Tidak ada prasarana dan sarana pengelolaan sampah dan limbah padat"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                $jumlh = (count($val) + $countLainnya);
                if(is_array($val)){
                    if($jumlh == 1){
                        $skor = 1;
                    }elseif($jumlh == 2){
                        $skor = 2;
                    }elseif($jumlh == 3){
                        $skor = 3;
                    }elseif($jumlh > 4){
                        $skor = 3;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'sarpras_kehati'){
            $array1 = ["Tidak Ada Prasarana dan Sarana Pembelajaran Keanekaraganan Hayati"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) == 1){
                        $skor = 1;
                    }elseif(count($val) == 2){
                        $skor = 2;
                    }elseif(count($val) == 3){
                        $skor = 3;
                    }elseif(count($val) == 4){
                        $skor = 4;
                    }elseif(count($val) == 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'sarpras_hemat_air'){
            $array1 = ["Tidak Ada Prasarana dan Sarana Terkait Hemat dan Konservasi Air"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) == 1){
                        $skor = 1;
                    }elseif(count($val) == 2){
                        $skor = 2;
                    }elseif(count($val) == 3){
                        $skor = 3;
                    }elseif(count($val) == 4){
                        $skor = 4;
                    }elseif(count($val) == 5){
                        $skor = 5;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }elseif($key == 'sarpras_hemat_energi'){
            $array1 = ["Tidak Ada Prasarana dan Sarana Terkait Hemat dan Konservasi Energi"];
            if (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 0;
            }else{
                if(is_array($val)){
                    if(count($val) == 1){
                        $skor = 1;
                    }elseif(count($val) == 2){
                        $skor = 2;
                    }elseif(count($val) == 3){
                        $skor = 3;
                    }else{
                        $skor = 0;
                    }
                }else{
                    $skor = 0;
                }
            }
        }
        
        return $skor;


    }
}

if (!function_exists('hitungSkor2025')) {
    /**
     * @param $val
     *
     * @return string
     */
    function hitungSkor2025($key,$val,$lainnya = [])
    {

        $skor = 0;
        $countLainnya = 0;
        if(@$lainnya){
            $countLainnya = count(array_filter($lainnya, function ($value) {
                return !is_null($value);
            }));
        }

        if($key == 'rencana_gerakan_pblhs'){
            if($val == "Sesuai dengan Laporan EDS dan hasil IPMLH."){
                $skor = 3;
            }elseif($val == "Sesuai dengan Laporan EDS atau hasil IPMLH."){
                $skor = 2;
            }elseif($val == "Tidak sesuai dengan Laporan EDS dan hasil IPMLH."){
                $skor = 1;
            }else{
                $skor = 0;
            }
        }elseif($key == 'pihak_terlibat_pblhs'){
            $array3 = ["Kepala Sekolah", "Dewan pendidik", "Komite sekolah", "Peserta Didik", "Masyarakat"];
            $array2 = ["Kepala Sekolah", "Dewan pendidik", "Komite sekolah", "Peserta Didik"];
            $array1 = ["Kepala Sekolah", "Dewan pendidik", "Komite sekolah"];
            if(!empty($val) && !is_array($val)){
                $val = array($val);
            }

            if (!array_diff($array3, $val) && !array_diff($val, $array3)) {
                $skor = 3;
            } elseif (!array_diff($array2, $val) && !array_diff($val, $array2)) {
                $skor = 2;
            } elseif (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 1;
            } else {
                $skor = 0;
            }

        }elseif($key == 'dokumen_ktsp'){

            $array3 = ["Visi", "Misi", "Tujuan", "Program pengembangan diri"];
            $array2 = ["Visi", "Misi", "Tujuan"];
            $array22 = ["Visi", "Misi", "Program pengembangan diri"];
            $array1 = ["Visi", "Misi","Tujuan", "Program pengembangan diri tidak memuat"];

            if(!empty($val) && !is_array($val)){
                $val = array($val);
            }

            if (!array_diff($array3, $val) && !array_diff($val, $array3)) {
                $skor = 3;
            } elseif ((!array_diff($array2, $val) && !array_diff($val, $array2)) || (!array_diff($array22, $val) && !array_diff($val, $array22))) {
                $skor = 2;
            } elseif (!array_diff($array1, $val) && !array_diff($val, $array1)) {
                $skor = 1;
            } else {
                $skor = 0;
            }
        }elseif($key == 'aspek_prlh'){
            if(is_array($val)){
                if(count($val) >= 5){
                    $skor = 5;
                }elseif(count($val) == 4){
                    $skor = 4;
                }elseif(count($val) == 3){
                    $skor = 3;
                }elseif(count($val) == 2){
                    $skor = 2;
                }elseif(count($val) == 1){
                    $skor = 1;
                }else{
                    $skor = 0;
                }
            }else{
                $skor = 1;
            }
            
        }elseif($key == 'unsur_warga_partisipasi'){

            // Unsur utama
            $unsur_utama = ["Kepala sekolah", "Tenaga Pendidik", "Tenaga Kependidikan", "Peserta Didik (termasuk kader adiwiyata)"];
            // Unsur tambahan
            $unsur_tambahan = ["Orang tua / wali murid", "Petugas kebersihan", "Petugas keamanan", "Petugas kantin"];

            if(!empty($val) && !is_array($val)){
                $val = array($val);
            }

            // Cek apakah semua unsur utama dipilih
            if (!array_diff($unsur_utama, $val)) {
                // Hitung unsur tambahan yang juga dipilih
                $tambahan_terpilih = array_intersect($unsur_tambahan, $val);
                $skor = 1 + count($tambahan_terpilih);
            } else {
                $skor = 0; // Jika unsur utama tidak lengkap, nilai = 0
            }
        }elseif($key == 'upaya_pemeliharaan'){
            if(is_array($val)){
                if(count($val) >= 7){
                    $skor = 5;
                }elseif(count($val) == 6){
                    $skor = 4;
                }elseif(count($val) == 5){
                    $skor = 3;
                }elseif(count($val) == 4){
                    $skor = 2;
                }elseif(count($val) <= 3){
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
            
        }elseif($key == 'pelihara_kebersihan'){

            $array3 = ["Sekolah bersih", "Sanitasi berfungsi", "Drainase berfungsi"];
            $array2 = ["Sekolah bersih", "Sanitasi berfungsi"];
            $array22 = ["Sekolah bersih", "Drainase berfungsi"];
            if(!empty($val) && !is_array($val)){
                $val = array($val);
            }
            if (!array_diff($array3, $val) && !array_diff($val, $array3)) {
                $skor = 3;
            } elseif ((!array_diff($array2, $val) && !array_diff($val, $array2)) || (!array_diff($array22, $val) && !array_diff($val, $array22))) {
                $skor = 2;
            } else {
                $skor = 1;
            }
        }elseif($key == 'upaya_pengurangan_timbulan'){
            if(is_array($val)){
                if(count($val) >= 7){
                    $skor = 5;
                }elseif(count($val) == 6){
                    $skor = 4;
                }elseif(count($val) == 5){
                    $skor = 3;
                }elseif(count($val) == 4){
                    $skor = 2;
                }elseif(count($val) <= 3){
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
            
        }elseif($key == 'upaya_daur_ulang_sampah'){
            if(is_array($val)){
                if(count($val) >= 3){
                    $skor = 3;
                }elseif(count($val) == 2){
                    $skor = 2;
                }elseif(count($val) == 1){
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
            
        }elseif($key == 'pihak_terlibat_pemindahan_sampah'){
            $array3 = ["Peserta didik", "Kader Adiwiyata", "Petugas kebersihan"];
            $array2 = ["Peserta didik", "Kader Adiwiyata"];
            $array1 = ["Petugas kebersihan"];
            if(!empty($val) && !is_array($val)){
                $val = array($val);
            }
            if (!array_diff($array3, $val) && !array_diff($val, $array3)) {
                $skor = 3;
            } elseif ((!array_diff($array2, $val) && !array_diff($val, $array2))) {
                $skor = 2;
            }elseif ((!array_diff($array1, $val) && !array_diff($val, $array1))) {
                $skor = 1;
            }
        }elseif($key == 'kegiatan_penghijauan'){
            $array3 = ["Penanaman", "Pemeliharaan", "Pembibitan"];
            $array2 = ["Penanaman", "Pemeliharaan"];
            $array1 = ["Penanaman"];
            if(!empty($val) && !is_array($val)){
                $val = array($val);
            }
            if (!array_diff($array3, $val) && !array_diff($val, $array3)) {
                $skor = 3;
            } elseif ((!array_diff($array2, $val) && !array_diff($val, $array2))) {
                $skor = 2;
            }elseif ((!array_diff($array1, $val) && !array_diff($val, $array1))) {
                $skor = 1;
            }
        }elseif($key == 'warga_sekolah'){
            if(is_array($val)){
                if(count($val) >= 5){
                    $skor = 5;
                }elseif(count($val) == 4){
                    $skor = 4;
                }elseif(count($val) == 3){
                    $skor = 3;
                }elseif(count($val) == 2){
                    $skor = 2;
                }elseif(count($val) <= 1){
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
            
        }elseif($key == 'upaya_konservasi_air'){
            if(is_array($val)){
                if(count($val) >= 7){
                    $skor = 5;
                }elseif(count($val) == 6){
                    $skor = 4;
                }elseif(count($val) == 5){
                    $skor = 3;
                }elseif(count($val) == 4){
                    $skor = 2;
                }elseif(count($val) <= 3){
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
        }elseif($key == 'upaya_konservasi_energi'){
            if(is_array($val)){
                if(count($val) >= 7){
                    $skor = 5;
                }elseif(count($val) == 6){
                    $skor = 4;
                }elseif(count($val) == 5){
                    $skor = 3;
                }elseif(count($val) == 4){
                    $skor = 2;
                }elseif(count($val) <= 3){
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
        }elseif($key == 'jumlah_karya_inovatif'){
            if(is_array($val)){
                if($val >= 5){
                    $skor = 3;
                }elseif(($val >= 3) || ($val <= 4)){
                    $skor = 2;
                }elseif(($val >= 1) || ($val <= 2)){
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
        }elseif($key == 'aksi_penerapan_prlh'){
            if(is_array($val)){
                if(count($val) >= 4){
                    $skor = 5;
                }elseif(count($val) == 3){
                    $skor = 4;
                }elseif(count($val) == 2){
                    $skor = 3;
                }elseif(count($val) == 1){
                    $skor = 2;
                }else{
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
        }elseif($key == 'pemilahan_sampah'){
            if($val == 'Sampah terpilah dan terkelola dengan baik'){
                $skor = 3;
            }elseif($val == 'Sampah terpilah namun tidak terkelola dengan baik'){
                $skor = 2;
            }else{
                $skor = 1;
            }
        }elseif($key == 'jejaring_kerja'){
            if(is_array($val)){
                if(count($val) >= 5){
                    $skor = 5;
                }elseif(count($val) == 4){
                    $skor = 4;
                }elseif(count($val) == 3){
                    $skor = 3;
                }elseif(count($val) == 2){
                    $skor = 2;
                }else{
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
        }elseif($key == 'kegiatan_kampanye'){
            if(is_array($val)){
                if(count($val) >= 5){
                    $skor = 5;
                }elseif(count($val) == 4){
                    $skor = 4;
                }elseif(count($val) == 3){
                    $skor = 3;
                }elseif(count($val) == 2){
                    $skor = 2;
                }elseif(count($val) == 1){
                    $skor = 1;
                }else{
                    $skor = 0;
                }
            }else{
                $skor = 1;
            }
            
        }elseif($key == 'media'){
            if(is_array($val)){
                if(count($val) >= 5){
                    $skor = 3;
                }elseif((count($val) >= 3) || (count($val) <= 4)){
                    $skor = 2;
                }elseif((count($val) >= 1) || (count($val) <= 2)){
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
        }elseif($key == 'kegiatan_kader_adiwiyata'){
            if(is_array($val)){
                if(count($val) >= 5){
                    $skor = 5;
                }elseif(count($val) == 4){
                    $skor = 4;
                }elseif(count($val) == 3){
                    $skor = 3;
                }elseif(count($val) == 2){
                    $skor = 2;
                }else{
                    $skor = 1;
                }
            }else{
                $skor = 1;
            }
        }elseif($key == 'frekuensi_pelaksanaan'){
            if($val == '3 kali dalam 1 tahun'){
                $skor = 3;
            }elseif($val == '2 kali dalam 1 tahun'){
                $skor = 2;
            }else{
                $skor = 1;
            }
        }elseif($key == 'unsur_pemantauan_evaluasi'){
            $array3 = ["Kepala sekolah", "Dewan Pendidik", "Komite sekolah","Peserta Didik","Masyarakat"];
            $array2 = ["Kepala sekolah", "Dewan Pendidik", "Komite sekolah","Peserta Didik"];
            $array1 = ["Kepala sekolah", "Dewan Pendidik", "Komite sekolah"];
            if(!empty($val) && !is_array($val)){
                $val = array($val);
            }
            if (!array_diff($array3, $val) && !array_diff($val, $array3)) {
                $skor = 3;
            } elseif ((!array_diff($array2, $val) && !array_diff($val, $array2))) {
                $skor = 2;
            }elseif ((!array_diff($array1, $val) && !array_diff($val, $array1))) {
                $skor = 1;
            }
        }
        // 


        return $skor;


    }
}

if (!function_exists('formKriteria')) {
    /**
     * @param $val
     *
     * @return string
     */
    function formKriteria($page_number,$sekolah_id = null,$type = null,$tahun = null)
    {
        //cek 
        

        $html = '';
        if(@$sekolah_id){
            $idSekolah = @$sekolah_id;
        }else{
            $idSekolah = session('sekolah_id');
        }

        $kuesioner = Kuesioner::where('ms_sekolah_id',$idSekolah)->orderBy('tahun','DESC')->first();
    
        $kriteria = FormKriteria::where('tahun',$tahun)->where('page_number',$page_number)->orderBy('MsFormKriteriaId','ASC')->get();

        if(session('group_alias') == 'sekolah'){
            $status = 0;
        }elseif(session('group_alias') == 'penilai_kota'){
            $status = 1;
        }elseif(session('group_alias') == 'penilai_provinsi'){
            $status = 2;
        }else{
            if(@$type == 'kota'){
                $status = 1;
            }elseif(@$type == 'provinsi'){
                $status = 2;
            }
        }

        foreach($kriteria as $keyKriteria => $data){

            if(@$type == 'kota'){
                $penilaian = Penilaian::where('tahun',$tahun)->where('key',$data->key)->where('ms_sekolah_id',$idSekolah)->where('status',$status)->first();
                $penilaianOld = Penilaian::where('tahun',$tahun)->where('key',$data->key)->where('ms_sekolah_id',$idSekolah)->where('status',($status-1))->first();
            }elseif(@$type == 'provinsi'){
                $penilaian = Penilaian::where('tahun',$tahun)->where('key',$data->key)->where('ms_sekolah_id',$idSekolah)->where('status',$status)->first();
                $penilaianOld = Penilaian::where('tahun',$tahun)->where('key',$data->key)->where('ms_sekolah_id',$idSekolah)->where('status',($status-1))->first();
            }else{
                $penilaian = Penilaian::where('tahun',$tahun)->where('key',$data->key)->where('ms_sekolah_id',$idSekolah)->where('status',$status)->first();
            }
            $class = '';
            $html .= '<div class="removeFormKriteria">';
                if($keyKriteria == 0){
                    $html .= '<div class="alert bg-primary-light text-primary mb-2 "> <i class="fal fa-info-circle"></i> Informasi <br>';
                    $html .= $kriteria[0]->keterangan;
                    $html .= '</div>';
                }
                $html .= '<div class="card mb-2">';
                $html .= '<div class="card-body">';
                    $html .= '<h6><b>'.$data->judul.'</b></h6>';
                    // $html .= '<input type="hidden" name="input_upload_files[]">';

                    //QUESTION
                    if($data->type == 'textarea'){
                        $value = json_decode(@$penilaian->value);
                        $valueOld = json_decode(@$penilaianOld->value);

                        if(@$value){
                            $nilai = @$value;
                        }else{
                            $nilai = @$valueOld;
                        }

                        $html .= '<div class="form-group m-2">';
                        $html .= '<textarea class="form-control is-required" name="input_'.$data->key.'">'.@$nilai.'</textarea>';
                        $html .= '</div>';

                    }elseif($data->type == 'freetext'){
                        $value = json_decode(@$penilaian->value);
                        $valueOld = json_decode(@$penilaianOld->value);

                        if(@$value){
                            $nilai = @$value;
                        }else{
                            $nilai = @$valueOld;
                        }

                        $html .= '<div class="form-group m-2">';
                            $html .= '<input type="text" class="form-control is-required" name="input_'.$data->key.'" value="'.@$nilai.'">';
                        $html .= '</div>';
                        
                    }elseif($data->type == 'checkbox'){

                        $option = json_decode($data->option);
                        $value = json_decode(@$penilaian->value);
                        $valueOld = json_decode(@$penilaianOld->value);

                        
                        
                        foreach($option as $keyOption => $dataOption){
                            if(($dataOption == 'Tidak Ada Prasarana dan Sarana Terkait Hemat dan Konservasi Energi') || ($dataOption == 'Tidak Ada Prasarana dan Sarana Terkait Hemat dan Konservasi Air') || ($dataOption == 'Tidak Ada Prasarana dan Sarana Pembelajaran Keanekaraganan Hayati') || ($dataOption == 'Tidak ada prasarana dan sarana pengelolaan sampah dan limbah padat') || ($dataOption == 'Tidak ada prasarana dan sarana sanitasi') || ($dataOption == 'Prasarana dan Sarana yang dimanfaatkan menjadi media pembelajaran tidak terkait 5 aspek lingkungan') || ($dataOption == 'Tidak Ada Kerjasama dengan pihak lain terkait lingkungan') || ($dataOption == 'Tidak Ada Kegiatan Diinisiasi Sekolah') || ($dataOption == 'Tidak Ada Kegiatan Pemberdayaan Kader') || ($dataOption == 'Tidak Ada Media Publikasi') || ($dataOption == 'Tidak Ada Kegiatan Kampanye/Publikasi') || ($dataOption == 'Tidak Ada Aspek Lingkungan') || ($dataOption == 'Tidak Ada Program Rutin') || ($dataOption == 'Tidak Ada Aspek Rutin Terkait Aspek Lingkungan') || ($dataOption == 'Tidak Ada Hasil Karya Siswa yang terkait Aspek Lingkungan') || ($dataOption == 'Jurnal Ekstrakurikuler Tidak Terkait Aspek Lingkungan') || ($dataOption == 'Jurnal Guru dan RPP Tidak Terkait Aspek Lingkungan') || ($dataOption == 'Bahan Informasi lingkungan di sekolah tidak terkait 5 aspek lingkungan') || ($dataOption == 'Visi, Misi dan Tujuan Sekolah Tidak Terkait Aspek Lingkungan') || ($dataOption == 'SK/Tatib Tidak Terkait Aspek Lingkungan')){
                                $class = 'uncheckall';
                            }else{
                                $class = 'checklistInput';
                            }

                            $checked = '';

                            $selectedValues = is_array($value) ? $value : (isset($value) ? [$value] : (is_array($valueOld) ? $valueOld : [$valueOld]));

                            if (in_array($dataOption, $selectedValues)) {
                                $checked = 'checked';
                            }

                            $key = 'number_'.$keyKriteria.'_'.$keyOption;

                            $html .= '<div class="custom-control custom-checkbox m-2">';
                                $html .= '<input type="checkbox" '.@$checked.' class="custom-control-input is-required '.$class.'" id="'.$key.'" data-value="'.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'" value="'.$dataOption.'" name="input_'.$data->key.'[]">';
                                $html .= '<label class="custom-control-label" for="'.$key.'">'.$dataOption.'</label>';
                            $html .= '</div>';
                        }
                        
                    }elseif($data->type == 'radio_button'){
                        $option = json_decode($data->option);
                        $value = json_decode(@$penilaian->value);
                        $valueOld = json_decode(@$penilaianOld->value);

                        foreach($option as $keyOption => $dataOption){

                            $key = 'number_'.$keyKriteria.'_'.$keyOption;

                            $html .= '<div class="custom-control custom-radio m-2">';
                                $html .= '<input '.(@$value == $dataOption ? 'checked' : (@$valueOld == $dataOption ? 'checked' : '') ).' type="radio" class="custom-control-input is-required checklistInput" data-value="'.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'" id="'.$key.'" value="'.$dataOption.'" name="input_'.$data->key.'">';
                                $html .= '<label class="custom-control-label" for="'.$key.'">'.$dataOption.'</label>';
                            $html .= '</div>';
                        }
                        
                    }elseif($data->type == 'number'){
                        $value = json_decode(@$penilaian->value);

                        $valueOld = json_decode(@$penilaianOld->value);

                        if(@$value){
                            $nilai = @$value;
                        }else{
                            $nilai = @$valueOld;
                        }

                        $html .= '<div class="form-group m-2">';
                            $html .= '<input type="text" class="form-control is-required numberInput" name="input_'.$data->key.'" value="'.@$nilai.'">';
                        $html .= '</div>';
                    }

                $html .= '</div>';
            $html .= '</div>';
            $html .= '</div>';

            if($data->active_lainnya == 1){
                if(session('group_alias') == 'sekolah'){
                    $lainnya = Penilaian::where('key','lainnya')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',0)->first();
                }elseif(session('group_alias') == 'penilai_kota'){

                    $lainnya = Penilaian::where('key','lainnya')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',1)->first();
                    $lainnyaOld = Penilaian::where('key','lainnya')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',0)->first();

                }elseif(session('group_alias') == 'penilai_provinsi'){ 
                    $lainnya = Penilaian::where('key','lainnya')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',2)->first();
                    $lainnyaOld = Penilaian::where('key','lainnya')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',1)->first();

                }else{
                    $lainnya = Penilaian::where('key','lainnya')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->first();
                }
                if(@$lainnya){
                    $valueLainnya = json_decode(@$lainnya->value);
                }else{
                    $valueLainnya = json_decode(@$lainnyaOld->value);
                }
                // dd($valueLainnya);

                $html .= '<div class="card mb-2 removeFormKriteria">';
                    $html .= '<div class="card-body">';
                        $html .= '<h6><b>'.$data->judul_lainnya.'</b></h6>';

                        for($i = 1; $i <= $data->number_answer_lainnya; $i++){
                            $html .= '<div class="form-group m-2">';
                                $html .= '<input type="text" value="'.@$valueLainnya[$i-1].'" class="form-control" placeholder="Jawaban" name="input_lainnya[]">';
                            $html .= '</div>';
                        }
                    $html .= '</div>';
                $html .= '</div>';
            }
        }

        $link = Penilaian::where('key','upload_files')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->first();
        $linkLabel = Penilaian::where('key','upload_files_label')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->first();
        // $valueLink = json_decode(@$link->value);
        // $valueLinkLabel = json_decode(@$linkLabel->value);

        // $valueLink = PenilaianFile::where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('tahun',$kuesioner->tahun)->orderBy('key_option','ASC')->get();

        $catatan = Penilaian::where('key','catatan')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->first();
        $valueCatatan = json_decode(@$catatan->value);

        $kriteriaFirst = FormKriteria::where('tahun',$tahun)->where('page_number',$page_number)->first();

        if(session('group_alias') == 'sekolah'){
            $html .= '<div class="card mb-2 removeFormKriteria">';
                $html .= '<input type="hidden" name="key" value="'.encode_id($page_number).'">';
                $html .= '<div class="card-body">';
                    $html .= '<div class="d-flex justify-content-between align-items-center mb-3">';
                        $html .= '<h6><b>Upload File Bukti</b></h6>';
                        $html .= '<i class="text-primary">Upload File Kembali Jika Ingin Merubah Data</i>';

                    $html .= '</div>';
                    $html .= '<div class="form-group">';

                        if(($kriteriaFirst->type == 'textarea') || ($kriteriaFirst->type == 'number')){
                            // $html .= '<div class="mb-3 file-item">';
                            //     $html .= '<input type="hidden" name="input_upload_files_label[]" value="">';
                            //     $html .= '<input type="file" name="input_upload_files[]" class="removeFormKriteria uploadedFiles is-required form-control">';
                            //     $html .= '<span><i>Ukuran Maksimal File : 10MB, Ekstension File : .pdf,.png,.jpeg,.jpg</i></span>';
                            // $html .= '</div>';
                            foreach($kriteria as $keyKriteria => $data){
                                $checkFile = PenilaianFile::where('page_number',$page_number)
                                        ->where('ms_sekolah_id',$idSekolah)
                                        ->where('tahun',$kuesioner->tahun)
                                        ->where('key',$data->key)
                                        ->first();

                                if(@$checkFile){
                                    $html .= '<div class="mb-3 file-item" id="file_'.@$data->key.'">
                                                <label class="fw-500">Upload Dokumen '.$data->judul.'</label>
                                                <input type="hidden" name="input_upload_files_label[]" value="'.@$data->key.'">
                                                <div class="input-group border-none">
                                                    <div class="input-group-prepend ">
                                                        <a target="_blank" class="input-group-text border-none bg-primary text-white" href="'.asset(@$checkFile->value).'"><i class="fal fa-download"></i></a>
                                                    </div>
                                                    <input type="file" accept=".pdf,.png,.jpeg,.jpg" name="input_upload_files[]" data-replace-index="0" class="removeFormKriteria form-control">
                                                </div>
                                                <span class="text-primary"><i>Ukuran Maksimal File : 10MB, Ekstension File : .pdf,.png,.jpeg,.jpg</i></span>
                                            </div>';
                                }else{
                                    $html .= '<div class="mb-3 file-item" id="file_'.@$data->key.'">
                                                <label class="fw-500">Upload Dokumen '.@$data->judul.'</label>
                                                <input type="hidden" name="input_upload_files_label[]" value="'.@$data->key.'">
                                                <div class="input-group border-none">
                                                    <input type="file" accept=".pdf,.png,.jpeg,.jpg" name="input_upload_files[]" data-replace-index="0" class="removeFormKriteria form-control is-required">
                                                </div>
                                                <span class="text-primary"><i>Ukuran Maksimal File : 10MB, Ekstension File : .pdf,.png,.jpeg,.jpg</i></span>
                                            </div>';
                                }
                            }

                        }else{
                            foreach($kriteria as $keyKriteria => $data){
                                $option = json_decode($data->option);
                                foreach($option as $keyOption => $dataOption){
                                    if(($dataOption == 'Tidak Ada Prasarana dan Sarana Terkait Hemat dan Konservasi Energi') || ($dataOption == 'Tidak Ada Prasarana dan Sarana Terkait Hemat dan Konservasi Air') || ($dataOption == 'Tidak Ada Prasarana dan Sarana Pembelajaran Keanekaraganan Hayati') || ($dataOption == 'Tidak ada prasarana dan sarana pengelolaan sampah dan limbah padat') || ($dataOption == 'Tidak ada prasarana dan sarana sanitasi') || ($dataOption == 'Prasarana dan Sarana yang dimanfaatkan menjadi media pembelajaran tidak terkait 5 aspek lingkungan') || ($dataOption == 'Tidak Ada Kerjasama dengan pihak lain terkait lingkungan') || ($dataOption == 'Tidak Ada Kegiatan Diinisiasi Sekolah') || ($dataOption == 'Tidak Ada Kegiatan Pemberdayaan Kader') || ($dataOption == 'Tidak Ada Media Publikasi') || ($dataOption == 'Tidak Ada Kegiatan Kampanye/Publikasi') || ($dataOption == 'Tidak Ada Aspek Lingkungan') || ($dataOption == 'Tidak Ada Program Rutin') || ($dataOption == 'Tidak Ada Aspek Rutin Terkait Aspek Lingkungan') || ($dataOption == 'Tidak Ada Hasil Karya Siswa yang terkait Aspek Lingkungan') || ($dataOption == 'Jurnal Ekstrakurikuler Tidak Terkait Aspek Lingkungan') || ($dataOption == 'Jurnal Guru dan RPP Tidak Terkait Aspek Lingkungan') || ($dataOption == 'Bahan Informasi lingkungan di sekolah tidak terkait 5 aspek lingkungan') || ($dataOption == 'Visi, Misi dan Tujuan Sekolah Tidak Terkait Aspek Lingkungan') || ($dataOption == 'SK/Tatib Tidak Terkait Aspek Lingkungan')){
                                    }else{
                                        $checkFile = PenilaianFile::where('page_number',$page_number)
                                        ->where('ms_sekolah_id',$idSekolah)
                                        ->where('tahun',$kuesioner->tahun)
                                        ->where('key',preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)))
                                        ->first();

                                        if(@$checkFile){
                                            $html .= '<div class="mb-3 file-item '.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'" id="file_'.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'">
                                                        <label class="fw-500">Upload Dokumen '.$dataOption.'</label>
                                                        <input type="hidden" name="input_upload_files_label[]" value="'.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'">
                                                        <div class="input-group border-none">
                                                            <div class="input-group-prepend ">
                                                                <a target="_blank" class="text-white input-group-text border-none bg-primary" href="'.asset($checkFile->value).'"><i class="fal fa-download"></i></a>
                                                                <a data-href="'.url('usulan/adiwiyata/kriteria/deleteFile/'.encode_id($checkFile->PenilaianFileId)).'/'.encode_id($page_number).'" class="text-white input-group-text border-none bg-danger d-none btnDeletFile" href="#"><i class="fal fa-trash"></i></a>
                                                            </div>
                                                            <input type="file" accept=".pdf,.png,.jpeg,.jpg" name="input_upload_files[]" data-replace-index="'.$keyOption.'" class="removeFormKriteria '.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'Class form-control">
                                                        </div>
                                                        <span class="text-primary"><i>Ukuran Maksimal File : 10MB, Ekstension File : .pdf,.png,.jpeg,.jpg</i></span>
                                                    </div>';
                                        }else{
                                            $html .='<div class="mb-3 file-item d-none '.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'" id="file_'.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'">
                                                <label class="fw-500">Upload Dokumen '.$dataOption.'</label>
                                                <input type="hidden" name="input_upload_files_label[]" value="'.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'">
                                                <input type="file" accept=".pdf,.png,.jpeg,.jpg" name="input_upload_files[]" class="removeFormKriteria '.preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)).'Class form-control file-itemInput">
                                                <span class="text-primary"><i>Ukuran Maksimal File : 10MB, Ekstension File : .pdf,.png,.jpeg,.jpg</i></span> 
                                            </div>';
                                        }
                                        
                                    }
                                }
                            }
                        }


                    $html .= '</div>';
                $html .= '</div>';
            $html .= '</div>';

            if($kuesioner->status == 5){
                $catatan = Penilaian::where('key','catatan')->where('page_number',$page_number)->where('ms_sekolah_id',$idSekolah)->where('status',1)->first();
                $html .= '<div class="card mb-2 removeFormKriteria">';
                    // $html .= '<input type="hidden" name="key" value="'.encode_id($page_number).'">';
                    $html .= '<div class="card-body">';
                        $html .= '<h6><b>Catatan</b></h6>';
                        $html .= '<p>'.json_decode($catatan->value).'</p>';
                    $html .= '</div>';
                $html .= '</div>';
            }
        }else{

            $html .= '<div class="card mb-2 removeFormKriteria">';
                $html .= '<div class="card-body">';
                    $html .= '<h6><b>Bukti File</b></h6>';
                    $html .= '<hr>';
                    $html .= '<div class="form-group">';
                    if(($kriteriaFirst->type == 'textarea') || ($kriteriaFirst->type == 'number')){
                        foreach($kriteria as $keyKriteria => $data){
                                $checkFile = PenilaianFile::where('page_number',$page_number)
                                        ->where('ms_sekolah_id',$idSekolah)
                                        ->where('tahun',$kuesioner->tahun)
                                        ->where('key',$data->key)
                                        ->first();
                                $extension = explode('.',@$checkFile->value);

                                if(@$checkFile){
                                    $html .= '<div class="mb-3 file-item d-flex justify-content-between align-items-center">
                                                    <label class="fw-500">Dokumen '.$data->judul.'</label>
                                                    <a class="text-white btn btn-sm bg-primary clickModal" data-toggle="modal" data-title="'.$data->judul.'" data-target="#modal" data-type="'.$extension[1].'" data-url="'.asset($checkFile->value).'" href="#"><i class="fal fa-eye"></i>&nbsp; Preview</a>
                                                </div>
                                                <hr>';
                                }
                            }
                    }else{
                        foreach($kriteria as $keyKriteria => $data){
                            $option = json_decode($data->option);
                            foreach($option as $keyOption => $dataOption){
                                if(($dataOption == 'Tidak Ada Prasarana dan Sarana Terkait Hemat dan Konservasi Energi') || ($dataOption == 'Tidak Ada Prasarana dan Sarana Terkait Hemat dan Konservasi Air') || ($dataOption == 'Tidak Ada Prasarana dan Sarana Pembelajaran Keanekaraganan Hayati') || ($dataOption == 'Tidak ada prasarana dan sarana pengelolaan sampah dan limbah padat') || ($dataOption == 'Tidak ada prasarana dan sarana sanitasi') || ($dataOption == 'Prasarana dan Sarana yang dimanfaatkan menjadi media pembelajaran tidak terkait 5 aspek lingkungan') || ($dataOption == 'Tidak Ada Kerjasama dengan pihak lain terkait lingkungan') || ($dataOption == 'Tidak Ada Kegiatan Diinisiasi Sekolah') || ($dataOption == 'Tidak Ada Kegiatan Pemberdayaan Kader') || ($dataOption == 'Tidak Ada Media Publikasi') || ($dataOption == 'Tidak Ada Kegiatan Kampanye/Publikasi') || ($dataOption == 'Tidak Ada Aspek Lingkungan') || ($dataOption == 'Tidak Ada Program Rutin') || ($dataOption == 'Tidak Ada Aspek Rutin Terkait Aspek Lingkungan') || ($dataOption == 'Tidak Ada Hasil Karya Siswa yang terkait Aspek Lingkungan') || ($dataOption == 'Jurnal Ekstrakurikuler Tidak Terkait Aspek Lingkungan') || ($dataOption == 'Jurnal Guru dan RPP Tidak Terkait Aspek Lingkungan') || ($dataOption == 'Bahan Informasi lingkungan di sekolah tidak terkait 5 aspek lingkungan') || ($dataOption == 'Visi, Misi dan Tujuan Sekolah Tidak Terkait Aspek Lingkungan') || ($dataOption == 'SK/Tatib Tidak Terkait Aspek Lingkungan')){
                                }else{
                                    $checkFile = PenilaianFile::where('page_number',$page_number)
                                    ->where('ms_sekolah_id',$idSekolah)
                                    ->where('tahun',$kuesioner->tahun)
                                    ->where('key',preg_replace('/[^a-z0-9]+/', '_', strtolower($dataOption)))
                                    ->first();

                                    $extension = explode('.',@$checkFile->value);

                                    if(@$checkFile){
                                        $html .= '<div class="mb-3 file-item d-flex justify-content-between align-items-center">
                                                    <label class="fw-500">Dokumen '.$dataOption.'</label>
                                                    <a class="text-white btn btn-sm bg-primary clickModal" data-toggle="modal" data-title="'.$dataOption.'" data-target="#modal" data-type="'.$extension[1].'" data-url="'.asset($checkFile->value).'" href="#"><i class="fal fa-eye"></i>&nbsp; Preview</a>
                                                </div>
                                                <hr>';
                                    }   
                                }
                            }
                        }
                    }
                    $html .= '</div>';
                $html .= '</div>';
            $html .= '</div>';

            $html .= '<div class="card mb-2 removeFormKriteria">';
                $html .= '<input type="hidden" name="key" value="'.encode_id($page_number).'">';
                $html .= '<div class="card-body">';
                    $html .= '<h6><b>Catatan</b></h6>';
                    $html .= '<div class="form-group">';
                        $html .= '<textarea class="form-control" name="input_catatan" placeholder="Catatan">'.@$valueCatatan.'</textarea>';
                    $html .= '</div>';
                $html .= '</div>';
            $html .= '</div>';
        }

        return $html;
    }
}

if (!function_exists('levelAdiwiyata')) {
    /**
     * @param $val
     *
     * @return string
     */
    function levelAdiwiyata($npsn)
    {
        $kuesioner     = Kuesioner::where('npsn',$npsn)->where('tahun',date('Y'))->first();
        $sekolah       = Sekolah::where('npsn',$npsn)->first();
        $sk            = SK::where('tahun',date('Y'))->where('sekolah','like','%'.$sekolah->MsSekolahId.'%')->first();
        $data = null;
        if(@$kuesioner){
            $data = $kuesioner;
        }else{
            $kuesioner = Kuesioner::where('npsn',$npsn)->where('tahun',(date('Y')-1))->first();
            $data = $kuesioner;
        }
        $level = '';
        
        if(@$data->level == 0){
            if((@$data->level == 0) && (@$data->tim_adiwiyata == 2) && (@$data->info_pblhs == 2) ){
                if(@$sk->jenis_usulan == 1){
                    $level = '3';
                }else{
                    $level = '2';
                }
            }elseif((@$data->level == 0) && (@$data->tim_adiwiyata == 2)){
                if(@$sk->jenis_usulan == 1){
                    $level = '3';
                }else{
                    $level = '1';
                }
            }else{
                if(@$sk->jenis_usulan == 1){
                    $level = '3';
                }else{
                    $level = '0';
                }
            }
        }elseif(@$data->level == 1){

            if(@$sk->jenis_usulan == 2){
                $level = '4';
            }else{
                $level = '3';
            }
        }elseif(@$data->level == 2){
            if(@$sk->jenis_usulan == 3){
                $level = '5';
            }else{
                $level = '4';
            }
        }else{
            if(@$sk->jenis_usulan == 1){
                $level = '3';
            }else{
                $level = '0';
            }
        }

        return $level;
    }
}

if (!function_exists('taskLabel')) {
    /**
     * @param $val
     *
     * @return string
     */
    function taskLabel($val)
    {
        if ($val == 'store') {
            $task = 'save';
        } elseif ($val == 'save_permission') {
            $task = 'save group access';
        } elseif ($val == 'destroy') {
            $task = 'delete';
        } elseif ($val == 'batch') {
            $task = 'delete';
        } else {
            $task = $val;
        }

        return $task;
    }
}


if (!function_exists('logActivity')) {
    /**
     * @param $request
     * @param $note
     */
    function logActivity($request, $note)
    {
        $repository = app(\App\Models\Log::class);
        $data = [
            'module' => $request->route()->getAction('prefix'),
            'task' => taskLabel($request->route()->getActionMethod()),
            'user_id' => session('uid'),
            'ipaddress' => $request->getClientIp(),
            'useragent' => $request->header('User-Agent'),
            'note' => $note,
            'created_at' => \Carbon\Carbon::now()
        ];

        if (session('superuser') == false)
            $repository->create($data);
    }
}


if (!function_exists('trimId')) {
    /**
     * @param $val
     * @return array
     */
    function trimId($val)
    {
        $string = explode('+', $val);
        return $string;
    }
}


if (!function_exists('dateTime')) {
    /**
     * make secure id
     *
     * @param string|null $val
     *
     * @return string
     */
    function dateTime($date)
    {
        return date('d-m-Y H:i:s',strtotime(@$date));
    }
}

if (!function_exists('encode_id')) {
    /**
     * make secure id
     *
     * @param string|null $val
     *
     * @return string
     */
    function encode_id(?string $val = ''): string
    {
        $params = ['val' => $val];
        return rtrim(base64_encode(serialize($params)), "=");
    }
}

if (!function_exists('decode_id')) {
    /**
     * @param string|null $val
     * ${STATIC}
     *
     * @return      mixed|null
     * @author      alex.gz <amqit.consultant@gmail.com>
     * @created     02/12/2023 4:28
     *
     */
    function decode_id(?string $val = ''): mixed
    {
        $secure = unserialize(base64_decode($val));
        return $secure ? $secure['val'] : null;
    }
}

if (!function_exists('permission')) {
    /**
     * @param        $access
     * @param        $key
     * @param string $method
     * @param bool   $view
     *
     * @return mixed
     */
    function permission($access, $key, string $method = 'menu', bool $view = false): mixed
    {   
        if (@session('group_id') != 1) {
            if ($method == 'module') {
                if (is_array($access)) {
                    $model = MasterAccessMenu::where('module', 'LIKE', "{$key}%")->where('ms_group_id', session('group_id'))->first();
                    $query = count(array_intersect((array)$access, (array)$model->access));
                } else {
                    $query = MasterAccessMenu::where($access, true)->where('module', 'LIKE', $key.'%')->where('ms_group_id', session('group_id'))->count();
                    if ($query > 0) {
                        return true;
                    } else {
                        return abort('401');
                    }
                }
            } else {
                $query = MasterAccessMenu::where($access, true)->where('ms_menu_id', $key)->where('ms_group_id', session('group_id'))->count();
            }

            if ($query > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }

    }
}

if (!function_exists('access')) {
    /**
     * @param $access
     * @param $key
     *
     * @return bool
     */
    function access($access, $key)
    {
        if (session('group_alias') != 'administrator') {
            $query = MasterAccessMenu::where($access, 1)->where('module', $key)->where('ms_group_id', session('group_id'))->count();
            if ($query > 0) {
                return true;
            } else if (session('group_alias') == 'administrator') {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
}

if (!function_exists('activeMenuClass')) {
    /**
     * Helper to grab the application version.
     *
     * @return mixed
     */
    function activeMenuClass($route){
        // dd(request()->route()->getName());
        // if(request()->route()->getName() == $route){
        //     return true;
        // }else{
        //     return false;
        // }

        if (\Str::is($route, request()->route()->getName())) {
            return true;
        } else {
            return false;
        }
    }
    
}

if (!function_exists('renderMenu')) {
    
    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function renderMenu()
    {
        
        $parent = MasterMenu::where('status',true)->where('menu_type','sidebar')->where('parent_id',0)->orderBy('ordering','ASC')->get();
        $html = '';
        foreach ($parent as $p1) {
            // echo $p1->MsMenuId.'<br>';
            $child2 = MasterMenu::where('status',true)->where('menu_type','sidebar')->where('parent_id',$p1->MsMenuId)->get();
            $access1 = permission('is_read', $p1->MsMenuId, 'menu', true);

            $ch1 = count($child2) > 0 ? '' : '';
            $link1 = count($child2) > 0 ? '' : 'menu-link';
            $active = activeMenuClass($p1->module) ? 'active' : '';
            // dd($p1->route);

            if ($access1) {
                $active1 = activeMenuClass($p1->module) ? 'active' : '';

                $html .= '<li class="' . $ch1 . $active1 . '"><a class="' . $link1 . '" href="' . url($p1->url) . '"><i class="' . $p1->menu_icons . '"></i> <span class="nav-link-text" data-i18n="nav.application_intel">' . @$p1->title.'</span>';
                if (count($child2) > 0) {
                    $html .= '</a>';
                    $html .= '<ul class="menu-subs">';
                    foreach ($child2 as $p2) {
                        $child3 = MasterMenu::where('status',true)->where('menu_type','sidebar')->where('parent_id',$p2->MsMenuId)->get();
                        $access2 = permission('is_read', $p2->MsMenuId, 'menu', true);
                        $ch2 = count($child3) > 0 ? '' : '';
                        $link2 = count($child3) > 0 ? '' : 'menu-link';
                        if ($access2) {
                            $active2 = activeMenuClass($p2->module) ? 'active' : '';
                            $html .= '<li class="' . $ch2 .$active2. '"><a class="' . $link2 . '" href="' . url($p2->url) . '"> <i class="' . $p2->menu_icons . '"></i> <span class="nav-link-text" data-i18n="nav.application_intel">' . @$p2->title.'<span>';
                            if (count($child3) > 0) {
                                $html .= '</a>';
                                $html .= '<ul>';
                                foreach ($child3 as $p3) {
                                    $child4 = MasterMenu::where('status',true)->where('menu_type','sidebar')->where('parent_id',$p3->MsMenuId)->get();
                                    $access3 = permission('is_read', $p3->MsMenuId, 'menu', true);
                                    $ch3 = count($child4) > 0 ? '' : '';
                                    $link3 = count($child4) > 0 ? '' : 'menu-link';
                                    if ($access3) {
                                        $active3 = activeMenuClass($p3->module) ? 'active' : '';
                                        // $active3 = $active ? ' ' . null : null;
                                        $html .= '<li class="' . $ch3 . $active3.'"><a class="' . $link3 . '" href="' . url($p3->url) . '"> <span class="nav-link-text" data-i18n="nav.application_intel">' . @$p3->title.'</span>';
                                        if (count($child4) > 0) {
                                            $html .= '</a>';
                                            $html .= '<ul class="menu-subs">';
                                            foreach ($child4 as $p4) {
                                                $html .= '<li class=" ' . null . '"><a class="menu-link" href="' . url($p4->url) . '"> <span class="nav-link-text" data-i18n="nav.application_intel">' . @$p4->title.'<span>';
                                            }
                                            $html .= '</ul>';
                                        } else {
                                            $html .= '</a>';
                                        }
                                        $html .= '</li>';
                                    }
                                }
                                $html .= '</ul>';
                            } else {
                                $html .= '</a>';
                            }
                            $html .= '</li>';
                        }
                    }
                    $html .= '</ul>';
                } else {
                    $html .= '</a>';
                }
                $html .= '</li>';
            }
        }
        return $html;
    }
}

if (!function_exists('include_route_files')) {
    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function include_route_files($folder)
    {
        include_files_in_folder($folder);
    }
}

if (!function_exists('include_files_in_folder')) {
    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function include_files_in_folder($folder)
    {
        try {
            $rdi = new RecursiveDirectoryIterator($folder);
            $it = new RecursiveIteratorIterator($rdi);

            while ($it->valid()) {
                if (!$it->isDot() && $it->isFile() && $it->isReadable() && $it->current()->getExtension() === 'php') {
                    require $it->key();
                }

                $it->next();
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}