<?php

namespace App\Http\Controllers\Modules\Usulan;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use App\Models\Kuesioner;
use App\Models\Master\FormKriteria;
use App\Models\Master\Sekolah;
use App\Models\Penilaian;
use App\Models\PenilaianFile;
use App\Models\KuesionerLog;
use App\Models\DokumenAdministrasi;

class KriteriaController extends Controller
{
    protected $title = 'Pemenuhan Kriteria';
    protected $template = 'modules.usulan.kriteria';
    protected $route = 'modules.usulan_adiwiyata.kriteria';

    public function index()
    {
        permission('is_read', $this->route, 'module',true);

        if(Kuesioner::where('ms_sekolah_id',session('sekolah_id'))->where('tahun',date('Y'))->count() == 0){
            return redirect('kuesioner/update/'.encode_id(session('sekolah_id')))->with([
                    'message' => 'Maaf anda belum melakukan isi kuesioner, silahkan isi terlebih dahulu',
                    'type'    => 'error',
                ]);
        }

        $kuesioner = Kuesioner::where('ms_sekolah_id',session('sekolah_id'))->where('tahun',date('Y'))->first();
        $dok = DokumenAdministrasi::where('kuesioner_id',$kuesioner->KuesionerId)->first();

        if($kuesioner->status == 0){
            if(@$dok->status == 0){
                return redirect('kuesioner/update/'.encode_id(session('sekolah_id')))->with([
                    'message' => 'Maaf menunggu verifikasi dokumen oleh Dinas/Sudin',
                    'type'    => 'error',
                ]);
            }elseif(@$dok->status == 2){
                return redirect('kuesioner/update/'.encode_id(session('sekolah_id')))->with([
                    'message' => 'Dokumen ditolak oleh Dinas/Sudin, silahkan upload ulang',
                    'type'    => 'error',
                ]);
            }
        }
        if(@$kuesioner){
            if(@$kuesioner->status == 1){
                // $dok = DokumenAdministrasi::where('kuesioner_id',$kuesioner->KuesionerId)->first();
                if(@$dok->status == 0){
                    return redirect('kuesioner/update/'.encode_id(session('sekolah_id')))->with([
                        'message' => 'Maaf menunggu verifikasi dokumen oleh Dinas/Sudin',
                        'type'    => 'error',
                    ]);
                }elseif(@$dok->status == 2){
                    return redirect('kuesioner/update/'.encode_id(session('sekolah_id')))->with([
                        'message' => 'Dokumen ditolak oleh Dinas/Sudin, silahkan upload ulang',
                        'type'    => 'error',
                    ]);
                }
            }
        }

        $data['title'] = $this->title;
        $data['route'] = $this->route;   
        $data['kuesioner'] = $kuesioner;
        $data['page']  = FormKriteria::select('page_number')->groupBy('page_number')->where('tahun',tahunKuesioner($kuesioner->KuesionerId))->orderBy('page_number','ASC')->pluck('page_number')->toArray(); 

        return view($this->template.'.form',$data);
    }
    public function resume()
    {
        // permission('is_read', $this->route, 'module',true);

        $data['title'] = $this->title;
        $data['route'] = $this->route;   
        $data['page']  = FormKriteria::select('page_number')->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->toArray(); 

        return view($this->template.'.resume',$data);
    }

    public function progress($id)
    {
        $keyId = decode_id($id);
        // permission('is_read', $this->route, 'module',true);

        $data['title']          = $this->title;
        $data['route']          = $this->route;   
        $data['secure_id']          = $id;   
        $data['kuesioner']      = Kuesioner::where('ms_sekolah_id',$keyId)->where('tahun',date('Y'))->first();
        $data['page']           = FormKriteria::select('page_number')->where('tahun',tahunKuesioner($data['kuesioner']->KuesionerId))->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->toArray(); 
        $data['log']            = KuesionerLog::where('ms_sekolah_id',$keyId)->orderBy('created_at','ASC')->get();
        
        $data['dok']            = DokumenAdministrasi::where('ms_sekolah_id',$keyId)->where('tahun',$data['kuesioner']->tahun)->first();
        $data['penilaian']      = Penilaian::where('ms_sekolah_id',$keyId)->where('tahun',$data['kuesioner']->tahun)->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->toArray();

        return view($this->template.'.progress',$data);
    }
    public function store2026(Request $request)
    {
        // dd($request->all());
        $data = $request->all();
        $_value = [];

        $kuesioner = decode_id($data['secure_id']);

        foreach ($data as $key => $value) {
            if (strpos($key, 'input_') === 0) {
                $_value[$key] = $value;

                if($key == 'input_jumlah_kader'){
                    $kader               = $data['input_jumlah_kader'];
                    $peserta_didik       = $data['input_jumlah_peserta_didik'];

                    $persen = ($kader/$peserta_didik)*100;
                    // dd($persen);
                    if($persen == 0){
                        $skor = 0;
                    }elseif((round($persen) >= 1) && (round($persen) <= 5)){
                        $skor = 1;
                    }elseif((round($persen) >= 6) && (round($persen) <= 10)){
                        $skor = 2;
                    }elseif((round($persen) >= 11) && (round($persen) <= 15)){
                        $skor = 3;
                    }elseif((round($persen) >= 16) && (round($persen) <= 20)){
                        $skor = 4;
                    }else{
                        $skor = 5;
                    }

                }elseif($key == 'input_jml_sampah_tahun_berjalan'){
                    $tahun_berjalan   = $data['input_jml_sampah_tahun_berjalan'];
                    $tahun_sebelumnya = $data['input_jml_sampah_tahun_sebelumnya'];

                    $persen = (($tahun_sebelumnya-$tahun_berjalan)/$tahun_sebelumnya)*100;

                    if($persen <= 10){
                        $skor = 0;
                    }elseif((round($persen) > 10) && (round($persen) <= 20)){
                        $skor = 1;
                    }elseif((round($persen) >= 21) && (round($persen) <= 30)){
                        $skor = 2;
                    }elseif((round($persen) >= 31) && (round($persen) <= 40)){
                        $skor = 3;
                    }elseif((round($persen) >= 41) && (round($persen) <= 50)){
                        $skor = 4;
                    }else{
                        $skor = 5;
                    }

                }elseif($key == 'input_jumlah_pohon'){
                    $jumlah_pohon         = $data['input_jumlah_pohon'];
                    $jumlah_warga = $data['input_jumlah_warga'];

                    $persen = ($jumlah_pohon/$jumlah_warga)*100;
                    // dd($persen);
                    if($persen == 0){
                        $skor = 0;
                    }elseif((round($persen) >= 1) && (round($persen) <= 20)){
                        $skor = 1;
                    }elseif((round($persen) >= 21) && (round($persen) <= 40)){
                        $skor = 2;
                    }elseif((round($persen) >= 41) && (round($persen) <= 60)){
                        $skor = 3;
                    }elseif((round($persen) >= 61) && (round($persen) <= 80)){
                        $skor = 4;
                    }else{
                        $skor = 5;
                    }

                }else{
                    $skor = hitungSkor(str_replace('input_','',$key),$value,@$data['input_lainnya']);
                }

                if(session('group_alias') == 'sekolah'){
                    $status = 0;
                }elseif(session('group_alias') == 'penilai_kota'){
                    $status = 1;
                }elseif(session('group_alias') == 'penilai_provinsi'){
                    $status = 2;
                }

                if(@$request['sekolah']){
                    $idSekolah = decode_id(@$request['sekolah']);
                    $sekolah = Sekolah::find($idSekolah);
                }else{
                    $idSekolah = session('sekolah_id');
                    $sekolah = Sekolah::find($idSekolah);
                }

                // dd(request()->input_upload_files,request()->all());

                if($key == 'input_upload_files'){

                    $filePaths = [];
                    
                    if(is_array($value)){
                        $old = Penilaian::where('key','upload_files')->where('page_number',decode_id($data['key']))->where('ms_sekolah_id',$idSekolah)->first();
                        $oldFiles = json_decode($old->value ?? '[]', true);
                        if (!is_array($oldFiles)) {
                            $oldFiles = [];
                        }
                        foreach ($value as $k => $file) {

                            $destinationPath = public_path('uploads/kriteria/' . date('Y').'/'.$idSekolah . '/' .decode_id($data['key']) );
                            $path = $destinationPath;
                            $fileName = $file->getClientOriginalName();
                            $fileMime = $file->getClientMimeType();
                            $fileExtension = $file->getClientOriginalExtension();
                            $fileSize = $file->getSize();

                            $newFilename = $idSekolah.'_'.session('uid').'_'.uniqid('file_') . '.' . $fileExtension;

                            if (!File::exists($path)) {
                                File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                            }

                            $newPath = 'uploads/kriteria/'.date('Y').'/'.$idSekolah.'/'.decode_id($data['key']).'/' . $newFilename;
                            $uploaded = $file->move($path, $newFilename);
                            $filePaths[] = $newPath;

                            $insertFile[$k] = PenilaianFile::updateOrCreate([
                                'kuesioner_id'  => $kuesioner,
                                'ms_sekolah_id' => $idSekolah,
                                'key'           => $data['input_upload_files_label'][$k],
                                'key_option'    => $k,
                                'page_number'   => decode_id($data['key']),
                                'tahun'         => date('Y'),
                            ],[
                                'kuesioner_id'  => $kuesioner,
                                'ms_sekolah_id' => $idSekolah,
                                'key'           => $data['input_upload_files_label'][$k],
                                'key_option'    => $k,
                                'page_number'   => decode_id($data['key']),
                                'value'         => $newPath,
                                'created_by'    => auth()->user()->id,
                                'tahun'         => date('Y'),
                            ]);
                            
                            // $tempPath = storage_path('app/tmp_uploads/' . $file);
                            // // dd($tempPath);

                            // if (file_exists($tempPath)) {
                            //     $path = public_path('uploads/kriteria/' . date('Y').'/'.$idSekolah . '/' .decode_id($data['key']) );
                            //     if (!File::exists($path)) {
                            //         File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                            //     }

                            //     $newPath = 'uploads/kriteria/'.date('Y').'/'.$idSekolah.'/'.decode_id($data['key']).'/'.$file;
                            //     copy($tempPath, public_path($newPath));
                            //     $filePaths[] = $newPath;
                            // }
                        }

                        // $value = array_values(array_unique(
                        //     array_merge($oldFiles, $filePaths)
                        // ));
                    }else{

                            $destinationPath = public_path('uploads/kriteria/' . date('Y').'/'.$idSekolah . '/' .decode_id($data['key']) );
                            $path = $destinationPath;
                            $fileName = $value->getClientOriginalName();
                            $fileMime = $value->getClientMimeType();
                            $fileExtension = $value->getClientOriginalExtension();
                            $fileSize = $value->getSize();

                            $newFilename = $idSekolah.'_'.session('uid').'_'.uniqid('file_') . '.' . $fileExtension;

                            if (!File::exists($path)) {
                                File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                            }

                            $newPath = 'uploads/kriteria/'.date('Y').'/'.$idSekolah.'/'.decode_id($data['key']).'/' . $newFilename;
                            $uploaded = $value->move($path, $newFilename);
                            $filePaths[] = $newPath;
                            // dd($data['input_upload_files_label']);

                            $insertFile = PenilaianFile::updateOrCreate([
                                'kuesioner_id'  => $kuesioner,
                                'ms_sekolah_id' => $idSekolah,
                                'key'           => $data['input_upload_files_label'][0],
                                'key_option'    => 0,
                                'page_number'   => decode_id($data['key']),
                                'tahun'         => date('Y'),
                            ],[
                                'kuesioner_id'  => $kuesioner,
                                'ms_sekolah_id' => $idSekolah,
                                'key'           => $data['input_upload_files_label'][0],
                                'key_option'    => 0,
                                'page_number'   => decode_id($data['key']),
                                'value'         => $newPath,
                                'created_by'    => auth()->user()->id,
                                'tahun'         => date('Y'),
                            ]);

                        // $tempPath = storage_path('app/tmp_uploads/' . $value);

                        // if (file_exists($tempPath)) {
                        //     $path = public_path('uploads/kriteria/' . date('Y').'/'.$idSekolah . '/' .decode_id($data['key']) );
                        //     if (!File::exists($path)) {
                        //         File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                        //     }

                        //     $newPath = 'uploads/kriteria/'.date('Y').'/'.$idSekolah.'/'.decode_id($data['key']).'/'.$value;
                        //     copy($tempPath, public_path($newPath));
                        //     $filePaths[] = $newPath;
                        // }

                        // $value = $filePaths;
                    }

                        
                        

                        // dd($value);
                }

                

                

                $nilai_kota  = Penilaian::where('ms_sekolah_id',$idSekolah)
                ->where('page_number',decode_id($data['key']))
                ->where('skor','!=',0)
                ->where('tahun',date('Y'))
                ->where('status',1) //inputan kota
                ->first();

                $nilai_prov  = Penilaian::where('ms_sekolah_id',$idSekolah)
                ->where('page_number',decode_id($data['key']))
                ->where('skor','!=',0)
                ->where('tahun',date('Y'))
                ->where('status',2) //inputan kota
                ->first();

                $penilaian[$key] = Penilaian::updateOrCreate([
                    'kuesioner_id'  => $kuesioner,
                    'tahun'         => date('Y'),
                    'ms_sekolah_id' => $sekolah->MsSekolahId,
                    'npsn'          => $sekolah->npsn,
                    'page_number'   => decode_id($data['key']),
                    'key'           => str_replace('input_','',$key),
                    'status'        => $status,
                ],[
                    'kuesioner_id'  => $kuesioner,
                    'ms_sekolah_id' => $sekolah->MsSekolahId,
                    'npsn'          => $sekolah->npsn,
                    'page_number'   => decode_id($data['key']),
                    'key'           => str_replace('input_','',$key),
                    'value'         => json_encode($value),
                    'skor'          => $skor,
                    'tahun'         => date('Y'),
                    'created_by'    => auth()->user()->id,
                ]);
            }
        }

        return response()->json(['status' => true,'data' => $_value,'message' => 'Berhasil Update Data','page' => $data['key'],'page_number' => decode_id($data['key']),'nilai_kota'    => @$nilai_kota ? @$nilai_kota->skor : 0,
                'nilai_prov'    => @$nilai_prov ? @$nilai_prov->skor : 0]);
        
        
    }

    public function store2025(Request $request)
    {
        // dd($request);
        $data = $request->all();
        $_value = [];

        $kuesioner = decode_id($data['secure_id']);

        foreach ($data as $key => $value) {
            if (strpos($key, 'input_') === 0) {
                $_value[$key] = $value;

                if($key == 'input_unsur_warga_partisipasi'){
                    $skor = hitungSkor(str_replace('input_','','input_unsur_warga_partisipasi'),$value,$data['input_lainnya']);
                }elseif($key == 'input_jumlah_timbulan'){
                    $sebelum        = $data['input_jumlah_timbulan'];
                    $sekarang       = $data['input_ratarata_jumlah_timbulan'];
                    $pengurangan    = $sebelum - $sekarang;
                    $persentase     = ($pengurangan / $sebelum) * 100;
                    if($persentase > 80){
                        $skor = 5;
                    }elseif(($persentase > 60) || ($persentase <= 80)){
                        $skor = 4;
                    }elseif(($persentase > 40) || ($persentase <= 60)){
                        $skor = 3;
                    }elseif(($persentase > 20) || ($persentase <= 40)){
                        $skor = 2;
                    }else{
                        $skor = 1;
                    }
                }elseif($key == 'input_jumlah_rpp'){

                    $rpp     = $data['input_jumlah_rpp'];
                    $sekolah = $data['input_tingkat_pendidikan'];

                    //SMP dan SMA
                    if(($sekolah == 'SMP/sederajat') || ($sekolah == 'SMA/sederajat')){
                        if($rpp  == 1){
                            $skor = 1;
                        }elseif($rpp  == 2){
                            $skor = 2;
                        }elseif($rpp  == 3){
                            $skor = 3;
                        }elseif($rpp  == 4){
                            $skor = 3;
                        }elseif($rpp  == 5){
                            $skor = 4;
                        }elseif($rpp  == 6){
                            $skor = 4;
                        }elseif($rpp  >= 7){
                            $skor = 5;
                        }else{
                            $skor = 0;
                        }
                    }else{ //SD
                        if($rpp  == 1){
                            $skor = 1;
                        }elseif($rpp  == 2){
                            $skor = 2;
                        }elseif($rpp  == 3){
                            $skor = 3;
                        }elseif($rpp  == 4){
                            $skor = 4;
                        }elseif($rpp  >= 5){
                            $skor = 5;
                        }else{
                            $skor = 0;
                        }
                    }
                    
                }elseif($key == 'input_jumlah_pohon'){
                    $pohon          = $data['input_jumlah_pohon'];
                    $warga          = $data['input_jumlah_warga_sekolah'];
                    $persentase     = ($pohon / $warga) * 100;

                    if($persentase > 80){
                        $skor = 5;
                    }elseif(($persentase > 60) || ($persentase <= 80)){
                        $skor = 4;
                    }elseif(($persentase > 40) || ($persentase <= 60)){
                        $skor = 3;
                    }elseif(($persentase > 20) || ($persentase <= 40)){
                        $skor = 2;
                    }else{
                        $skor = 1;
                    }

                }elseif($key == 'input_jumlah_kader'){
                    $kader          = $data['input_jumlah_kader'];
                    $pesertadidik   = $data['input_jumlah_peserta_didik'];
                    $persentase     = ($kader / $pesertadidik) * 100;
                    // dd($persentase);

                    if($persentase > 20){
                        $skor = 5;
                    }elseif($persentase > 15){
                        $skor = 4;
                    }elseif($persentase > 10){
                        $skor = 3;
                    }elseif($persentase > 5){
                        $skor = 2;
                    }else{
                        $skor = 1;
                    }
                }elseif($key == 'input_rencana_kegiatan_pblhs'){

                    $rencana          = $data['input_rencana_kegiatan_pblhs'];
                    $jumlahKegiatan   = $data['input_jumlah_rencana_kegiatan_pblhs'];
                    $persentase       = ($rencana / $jumlahKegiatan) * 100;

                    if($persentase > 80){
                        $skor = 5;
                    }elseif($persentase > 60){
                        $skor = 4;
                    }elseif($persentase > 40){
                        $skor = 3;
                    }elseif($persentase > 20){
                        $skor = 2;
                    }else{
                        $skor = 1;
                    }
                }elseif($key == 'input_kondisi_kebersihan'){
                    $kebersihan = $data['input_kondisi_kebersihan'];
                    $drainase   = $data['input_kondisi_drainase'];

                    if ($kebersihan == "Bersih" && $drainase == "Bersih") {
                        $skor = 3; // Lingkungan bersih dan drainase berfungsi
                    } elseif (($kebersihan == "Bersih" && $drainase == "Kurang Bersih") || ($kebersihan == "Kurang Bersih" && $drainase == "Bersih")) {
                        $skor = 2; // Salah satu kondisi kurang baik
                    } else {
                        $skor = 1; // Lingkungan kurang bersih dan drainase tidak berfungsi
                    }
                }else{
                    $skor = hitungSkor(str_replace('input_','',$key),$value);
                }

                if(session('group_alias') == 'sekolah'){
                    $status = 0;
                }elseif(session('group_alias') == 'penilai_kota'){
                    $status = 1;
                }elseif(session('group_alias') == 'penilai_provinsi'){
                    $status = 2;
                }

                if(@$request['sekolah']){
                    $idSekolah = decode_id(@$request['sekolah']);
                    $sekolah = Sekolah::find($idSekolah);
                }else{
                    $idSekolah = session('sekolah_id');
                    $sekolah = Sekolah::find($idSekolah);
                }

                // dd(request()->input_upload_files,request()->all());

                if($key == 'input_upload_files'){

                    $filePaths = [];
                    
                    if(is_array($value)){
                        $old = Penilaian::where('key','upload_files')->where('page_number',decode_id($data['key']))->where('ms_sekolah_id',$idSekolah)->first();
                        $oldFiles = json_decode($old->value ?? '[]', true);
                        if (!is_array($oldFiles)) {
                            $oldFiles = [];
                        }
                        foreach ($value as $k => $file) {

                            $destinationPath = public_path('uploads/kriteria/' . date('Y').'/'.$idSekolah . '/' .decode_id($data['key']) );
                            $path = $destinationPath;
                            $fileName = $file->getClientOriginalName();
                            $fileMime = $file->getClientMimeType();
                            $fileExtension = $file->getClientOriginalExtension();
                            $fileSize = $file->getSize();

                            $newFilename = $idSekolah.'_'.session('uid').'_'.uniqid('file_') . '.' . $fileExtension;

                            if (!File::exists($path)) {
                                File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                            }

                            $newPath = 'uploads/kriteria/'.date('Y').'/'.$idSekolah.'/'.decode_id($data['key']).'/' . $newFilename;
                            $uploaded = $file->move($path, $newFilename);
                            $filePaths[] = $newPath;

                            $insertFile[$k] = PenilaianFile::updateOrCreate([
                                'kuesioner_id'  => $kuesioner,
                                'ms_sekolah_id' => $idSekolah,
                                'key'           => $data['input_upload_files_label'][$k],
                                'key_option'    => $k,
                                'page_number'   => decode_id($data['key']),
                                'tahun'         => date('Y'),
                            ],[
                                'kuesioner_id'  => $kuesioner,
                                'ms_sekolah_id' => $idSekolah,
                                'key'           => $data['input_upload_files_label'][$k],
                                'key_option'    => $k,
                                'page_number'   => decode_id($data['key']),
                                'value'         => $newPath,
                                'created_by'    => auth()->user()->id,
                                'tahun'         => date('Y'),
                            ]);
                            
                            // $tempPath = storage_path('app/tmp_uploads/' . $file);
                            // // dd($tempPath);

                            // if (file_exists($tempPath)) {
                            //     $path = public_path('uploads/kriteria/' . date('Y').'/'.$idSekolah . '/' .decode_id($data['key']) );
                            //     if (!File::exists($path)) {
                            //         File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                            //     }

                            //     $newPath = 'uploads/kriteria/'.date('Y').'/'.$idSekolah.'/'.decode_id($data['key']).'/'.$file;
                            //     copy($tempPath, public_path($newPath));
                            //     $filePaths[] = $newPath;
                            // }
                        }

                        // $value = array_values(array_unique(
                        //     array_merge($oldFiles, $filePaths)
                        // ));
                    }else{

                            $destinationPath = public_path('uploads/kriteria/' . date('Y').'/'.$idSekolah . '/' .decode_id($data['key']) );
                            $path = $destinationPath;
                            $fileName = $value->getClientOriginalName();
                            $fileMime = $value->getClientMimeType();
                            $fileExtension = $value->getClientOriginalExtension();
                            $fileSize = $value->getSize();

                            $newFilename = $idSekolah.'_'.session('uid').'_'.uniqid('file_') . '.' . $fileExtension;

                            if (!File::exists($path)) {
                                File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                            }

                            $newPath = 'uploads/kriteria/'.date('Y').'/'.$idSekolah.'/'.decode_id($data['key']).'/' . $newFilename;
                            $uploaded = $value->move($path, $newFilename);
                            $filePaths[] = $newPath;
                            // dd($data['input_upload_files_label']);

                            $insertFile = PenilaianFile::updateOrCreate([
                                'kuesioner_id'  => $kuesioner,
                                'ms_sekolah_id' => $idSekolah,
                                'key'           => $data['input_upload_files_label'][0],
                                'key_option'    => 0,
                                'page_number'   => decode_id($data['key']),
                                'tahun'         => date('Y'),
                            ],[
                                'kuesioner_id'  => $kuesioner,
                                'ms_sekolah_id' => $idSekolah,
                                'key'           => $data['input_upload_files_label'][0],
                                'key_option'    => 0,
                                'page_number'   => decode_id($data['key']),
                                'value'         => $newPath,
                                'created_by'    => auth()->user()->id,
                                'tahun'         => date('Y'),
                            ]);

                        // $tempPath = storage_path('app/tmp_uploads/' . $value);

                        // if (file_exists($tempPath)) {
                        //     $path = public_path('uploads/kriteria/' . date('Y').'/'.$idSekolah . '/' .decode_id($data['key']) );
                        //     if (!File::exists($path)) {
                        //         File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                        //     }

                        //     $newPath = 'uploads/kriteria/'.date('Y').'/'.$idSekolah.'/'.decode_id($data['key']).'/'.$value;
                        //     copy($tempPath, public_path($newPath));
                        //     $filePaths[] = $newPath;
                        // }

                        // $value = $filePaths;
                    }

                        
                        

                        // dd($value);
                }

                

                

                $nilai_kota  = Penilaian::where('ms_sekolah_id',$idSekolah)
                ->where('page_number',decode_id($data['key']))
                ->where('skor','!=',0)
                ->where('tahun',date('Y'))
                ->where('status',1) //inputan kota
                ->first();

                $nilai_prov  = Penilaian::where('ms_sekolah_id',$idSekolah)
                ->where('page_number',decode_id($data['key']))
                ->where('skor','!=',0)
                ->where('tahun',date('Y'))
                ->where('status',2) //inputan kota
                ->first();

                $penilaian[$key] = Penilaian::updateOrCreate([
                    'kuesioner_id'  => $kuesioner,
                    'tahun'         => date('Y'),
                    'ms_sekolah_id' => $sekolah->MsSekolahId,
                    'npsn'          => $sekolah->npsn,
                    'page_number'   => decode_id($data['key']),
                    'key'           => str_replace('input_','',$key),
                    'status'        => $status,
                ],[
                    'kuesioner_id'  => $kuesioner,
                    'ms_sekolah_id' => $sekolah->MsSekolahId,
                    'npsn'          => $sekolah->npsn,
                    'page_number'   => decode_id($data['key']),
                    'key'           => str_replace('input_','',$key),
                    'value'         => json_encode($value),
                    'skor'          => $skor,
                    'tahun'         => date('Y'),
                    'created_by'    => auth()->user()->id,
                ]);
            }
        }

        return response()->json(['status' => true,'data' => $_value,'message' => 'Berhasil Update Data','page' => $data['key'],'page_number' => decode_id($data['key']),'nilai_kota'    => @$nilai_kota ? @$nilai_kota->skor : 0,
                'nilai_prov'    => @$nilai_prov ? @$nilai_prov->skor : 0]);
        
        
    }

    public function kirimData($sekolah_id, $kuesioner_id)
    {
        //cek dokumen
        $keyId = decode_id($kuesioner_id);
        $dok = DokumenAdministrasi::where('kuesioner_id',$keyId)->first();
        if($dok->status == 0){
            return response()->json(['status' => false,'message' => 'Dokumen Belum Di Verifikasi','type' => 'error']);       
        }else{
            
            $kuesioner = Kuesioner::find($keyId);
            $kuesioner->status = 3;
            $kuesioner->save();

            $log = new KuesionerLog;
            $log->kuesioner_id   = $kuesioner->KuesionerId;
            $log->ms_sekolah_id  = $kuesioner->ms_sekolah_id;
            $log->npsn           = $kuesioner->npsn;
            $log->ms_group_id    = session('group_id');
            $log->step           = 'penilaian_oleh_tim_penilai_kota';
            $log->status         = 3;
            $log->created_by     = auth()->user()->id;
            $log->save();

            return response()->json(['status' => true,'message' => 'Data Berhasil Di Update','type' => 'success']);    
        }

        
    }

    function deletFile($id,$pagenumber) {

        $file = PenilaianFile::find(decode_id($id));
        $file->delete();

        return response()->json(['status' => true,'message' => 'Data Berhasil Di Update','type' => 'success','page' =>decode_id($pagenumber)]);            
    }
}
