<?php

namespace App\Http\Controllers\Modules\Usulan;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Master\Provinsi;
use App\Models\Kuesioner;
use App\Models\KuesionerLog;
use App\Models\Master\Sekolah;
use App\Models\Master\FormKriteria;
use App\Models\DokumenAdministrasi;
use App\Models\Penilaian;

class CSAPController extends Controller
{
    private $template = 'modules.usulan.csap';
    private $route = 'modules.usulan.csap';
    private $title = 'Usulan CSAP';

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $data['route'] = $this->route;
        $data['title'] = $this->title;
        $data['provinsi'] = Provinsi::where('kode_wilayah','010000')->get();

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

    public function update($id)
    {
        $keyId = decode_id($id);
        $data['kuesioner']  = Kuesioner::find($keyId);
        $data['sekolah']    = Sekolah::find($data['kuesioner']->ms_sekolah_id);
        $data['route'] = $this->route;
        $data['title'] = $this->title;
        $data['page']  = FormKriteria::select('page_number')->where('tahun',tahunKuesioner($keyId))->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->toArray(); 

        $jumlah = json_decode($data['sekolah']->profile->data_jumlah);
        $data['jumlah_peserta_didik']         = @$jumlah->jumlah_peserta_didik;
        $data['jumlah_tenaga_pendidik']       = @$jumlah->jumlah_tenaga_pendidik;
        $data['jumlah_tenaga_kependidikan']   = @$jumlah->jumlah_tenaga_kependidikan;
        $data['jumlah_warga_sekolah_lainnya'] = @$jumlah->jumlah_warga_sekolah_lainnya;
        $data['jumlah_biopori']               = @$jumlah->jumlah_biopori;
        $data['jumlah_sumur_resapan']         = @$jumlah->jumlah_sumur_resapan;
        $data['jumlah_pohon']                 = @$jumlah->jumlah_pohon;

        $air = json_decode($data['sekolah']->profile->penghematan_air);
        $data['air_sebelum_pblhs'] = @$air->air_sebelum_pblhs;
        $data['air_setelah_pblhs'] = @$air->air_setelah_pblhs;

        $listrik = json_decode($data['sekolah']->profile->penghematan_listrik);
        $data['listrik_sebelum_pblhs'] = @$listrik->listrik_sebelum_pblhs;
        $data['listrik_setelah_pblhs'] = @$listrik->listrik_setelah_pblhs;
        $data['luas_ruangan_ac']       = @$listrik->luas_ruangan_ac;
        $data['luas_ruangan_non_ac']   = @$listrik->luas_ruangan_non_ac;
        $data['jumlah_kader']          = @$listrik->jumlah_kader;

        $data['dokumen'] = DokumenAdministrasi::where('ms_sekolah_id',$data['kuesioner']->ms_sekolah_id)->where('tahun',$data['kuesioner']->tahun)->first();

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

        $data['title'] = $this->title;
        $data['route'] = $this->route;   
        $keyId = decode_id($id);
        $data['sekolah']    = Sekolah::find($keyId);
        $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 grid(Request $request)
    {
        if(session('kabupaten_id') != ''){
            $kuesioner = Kuesioner::where('level',1)->whereHas('sekolah',function($query){
                $query->where('ms_kabupaten_id',session('kabupaten_id'));
            })->orderBy('created_at','DESC')->get();
        }else{
            $kuesioner = Kuesioner::where('level',1)->orderBy('created_at','DESC')->get();
        }

        foreach ($kuesioner as $key => $row) {

            $action = '';

            if((access('is_create', $this->route.'.*')) || (access('is_update', $this->route.'.*'))){
                if($row->tahun == date('Y')){
                    $action .= '<a href="'.url('usulan/csap/update/'.encode_id($row->KuesionerId)).'" data-toggle="tooltip" title="View Data" class="btn btn-xs btn-block btn-primary"><i class="fal fa-edit text-white"></i></a>';
                }
            }

            if($row->level == 0){
                $penghargaan = '<i class="fal fa-trophy"></i>&nbsp;Belum Pernah';
            }elseif($row->level == 1){
                $penghargaan = '<i class="fal fa-trophy"></i>&nbsp;Adiwiyata Kab/Kota';
            }elseif($row->level == 2){
                $penghargaan = '<i class="fal fa-trophy"></i>&nbsp;Adiwiyata Provinsi';
            }elseif($row->level == 3){
                $penghargaan = '<i class="fal fa-trophy"></i>&nbsp;Adiwiyata Nasional';
            }elseif($row->level == 4){
                $penghargaan = '<i class="fal fa-trophy"></i>&nbsp;Adiwiyata Mandiri';
            }

            $penilaian = '';

            $penilaian .= '<div class="d-flex flex-column flex-md-row gap-1 justify-content-center">';
                $penilaian .= '<div class="text-secondary bg-secondary px-1 py-1 rounded w-100">';
                    $penilaian .= '<div class="d-flex flex-column">';
                        $penilaian .= '<span class="text-center"> Sekolah </span>';
                        $penilaian .= '<h5 class="text-center font-weight-bold ">'.getNilaiAll('sekolah',$row->ms_sekolah_id,$row->KuesionerId).' </h5>';
                    $penilaian .= '</div>';
                $penilaian .= '</div>';
                $penilaian .= '<div class="text-primary bg-primary-light px-1 py-1 rounded w-100">';
                    $penilaian .= '<div class="d-flex flex-column">';
                        $penilaian .= '<span class="text-center"> Kota</span>';
                        $penilaian .= '<h5 class="text-center font-weight-bold ">'.getNilaiAll('kota',$row->ms_sekolah_id,$row->KuesionerId).' </h5>';
                    $penilaian .= '</div>';
                $penilaian .= '</div>';
                $penilaian .= '<div class="text-success bg-success-light px-1 py-1 rounded w-100">';
                    $penilaian .= '<div class="d-flex flex-column">';
                        $penilaian .= '<span class="text-center"> Provinsi</span>';
                        $penilaian .= '<h5 class="text-center font-weight-bold ">'.getNilaiAll('provinsi',$row->ms_sekolah_id,$row->KuesionerId).'</h5>';
                    $penilaian .= '</div>';
                $penilaian .= '</div>';
            $penilaian .= '</div>';

            $sekolah = '';
            $sekolah .= @$row->sekolah->nama_sekolah.'<br>';
            $sekolah .= '<span class="badge bg-success-light text-success">'.@$row->profile->tingkat->name.'</span>&nbsp;';
            $sekolah .= '<span class="badge bg-primary-light text-primary">'.@$row->profile->status_sekolah.'</span>&nbsp;';

            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->id),
                'npsn'              => $row->sekolah->npsn,
                'tahun'             => @$row->tahun,
                'nama'              => $sekolah,
                'wilayah'           => $row->sekolah->kabupaten->name,
                'kecamatan'         => $row->sekolah->kecamatan->name,
                'penilaian'         => $penilaian,
                'progress'          => kuesionerLogStatus($row->KuesionerId),
                'action'            => $action,
            ];

        }

        return response()->json($_data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $sekolahId = decode_id($request->sekolah);
        if(session('group_alias') == 'penilai_kota'){
            $status = 1;
        }else{
            $status = 2;
        }

        $soal = Penilaian::where('ms_sekolah_id',$sekolahId)->where('tahun',date('Y'))->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->toArray();
        $penilaian  = Penilaian::where('ms_sekolah_id',$sekolahId)->where('tahun',date('Y'))->where('status',$status)->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->toArray();

        if(count($soal) != count($penilaian)){
            return response()->json(['validasi' => false,'message' => 'Maaf Penilaian Belum Lengkap!']);
        }

        if($request['validasi'] == 1){

            if(session('group_alias') == 'penilai_kota'){
                $kuesioner = Kuesioner::where('ms_sekolah_id',$sekolahId)->where('tahun',date('Y'))->first();
                $kuesioner->catatan_usulan  = $request['catatan_validasi'];
                $kuesioner->status          = 4;
                $kuesioner->save();

                //kuesioner log
                $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           = 'selesai_penilaian_kota';
                $log->status         = 4;
                $log->created_by     = auth()->user()->id;
                $log->save();
            }elseif(session('group_alias') == 'penilai_provinsi'){
                $kuesioner = Kuesioner::where('ms_sekolah_id',$sekolahId)->where('tahun',date('Y'))->first();
                $kuesioner->catatan_usulan  = $request['catatan_validasi'];
                $kuesioner->status          = 10;
                $kuesioner->save();

                //kuesioner log
                $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           = 'selesai_penilaian_provinsi';
                $log->status         = 6;
                $log->created_by     = auth()->user()->id;
                $log->save();

                //kuesioner log final
                $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           = 'selesai_penilaian_tahap_akhir';
                $log->status         = 10;
                $log->created_by     = auth()->user()->id;
                $log->save();
            }


        }elseif($request['validasi'] == 2){

            $kuesioner = Kuesioner::where('ms_sekolah_id',$sekolahId)->where('tahun',date('Y'))->first();
            $kuesioner->catatan_usulan  = $request['catatan_validasi'];
            $kuesioner->status          = 5;
            $kuesioner->save();

            //kuesioner log
            $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           = 'dikembalikan_penilaian_kota';
            $log->status         = 5;
            $log->created_by     = auth()->user()->id;
            $log->save();
            
        }else{
            return response()->json(['validasi' => false,'message' => 'Maaf Terjadi Kesalahan Dalam Input Data!']);
        }

        return response()->json(['status' => true,'message' => 'Berhasil update data!']);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
