<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Kuesioner;
use App\Models\KuesionerLog;
use App\Models\ProfileSekolah;
use App\Models\Master\FormKriteria;
use App\Models\DokumenAdministrasi;
use App\Models\Penilaian;
use App\Models\SK;
use App\Models\Usulan;
use App\Models\SampahTerkelola;

class HomeController extends Controller
{
    protected $template = 'modules.dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }

    public function session()
    {
        $key = request('key');
        $val = request('val');
        session([$key => $val]);
        return response()->json([
            'status' => 'success'
        ]);
    }

    public function dashboard()
    {
        // dd(date('Y'));
        $data['title'] = 'Dashboard';
        $data['group']  = session('group_alias');
        if(session('group_alias') == 'sekolah'){
            $data['kuesioner']  = Kuesioner::where('ms_sekolah_id',session('sekolah_id'))->where('tahun',date('Y'))->first();
            $data['profile']    = ProfileSekolah::where('ms_sekolah_id',session('sekolah_id'))->first();
            $data['page']       = FormKriteria::select('page_number')->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->count(); 
            $data['penilaian']  = Penilaian::select('page_number')->groupBy('page_number')->orderBy('page_number','ASC')->pluck('page_number')->count(); 
            $data['sk']         = SK::where('tahun',date('Y'))->where('sekolah','like','%'.session('sekolah_id').'%')->first();
            $data['log']  = KuesionerLog::where('kuesioner_id',@$data['kuesioner']->KuesionerId)->orderBy('created_at','DESC')->first();
            $data['dok'] = DokumenAdministrasi::where('ms_sekolah_id',session('sekolah_id'))->where('tahun',date('Y'))->first();

            $series = SampahTerkelola::where('ms_sekolah_id',session('sekolah_id'))->where('tahun',date('Y'))->orderBy('bulan','ASC')->get();
            $organik = array_fill(1, 12, 0);
            $anorganik = array_fill(1, 12, 0);
            $b3 = array_fill(1, 12, 0);
            $minyak = array_fill(1, 12, 0);

            foreach ($series as $row) {
                $bulan = (int) $row->bulan;

                $organik[$bulan]   = (int) $row->organik;
                $anorganik[$bulan] = (int) $row->sampah_anorganik;
                $b3[$bulan]        = (int) $row->b3;
                $minyak[$bulan]    = (int) $row->minyak_jelantah;
            }

            $data['series'] = [
                [
                    'name' => 'Organik',
                    'data' => array_values($organik),
                ],
                [
                    'name' => 'Anorganik',
                    'data' => array_values($anorganik),
                ],
                [
                    'name' => 'B3',
                    'data' => array_values($b3),
                ],
                [
                    'name' => 'Minyak Jelantah',
                    'data' => array_values($minyak),
                ],
            ];

            return view($this->template.'.sekolah', $data);
        }else{
            if(session('kabupaten_id') != ''){
                $data['usulan'] = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->get();
                $data['total_usulan_kab']       = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->where('level',0)->count();
                $data['total_usulan_prov']      = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->where('level',1)->count();
                $data['total_usulan_nasional']  = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->where('level',2)->count();
                $data['total_usulan_mandiri']   = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->where('level',3)->count();

                $data['total_sekolah_kab']       = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->where('level',0)->where('status',11)->count();
                $data['total_sekolah_prov']      = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->where('level',1)->where('status',11)->count();
                $data['total_sekolah_nasional']  = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->where('level',2)->where('status',11)->count();
                $data['total_sekolah_mandiri']   = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->where('tahun',date('Y'))->where('level',3)->where('status',11)->count();
            }else{
                $data['usulan'] = Kuesioner::where('tahun',date('Y'))->get();
                $data['total_usulan_kab']       = Kuesioner::where('tahun',date('Y'))->where('level',0)->count();
                $data['total_usulan_prov']      = Kuesioner::where('tahun',date('Y'))->where('level',1)->count();
                $data['total_usulan_nasional']  = Kuesioner::where('tahun',date('Y'))->where('level',2)->count();
                $data['total_usulan_mandiri']   = Kuesioner::where('tahun',date('Y'))->where('level',3)->count();

                $data['total_sekolah_kab']       = Kuesioner::where('tahun',date('Y'))->where('level',0)->where('status',11)->count();
                $data['total_sekolah_prov']      = Kuesioner::where('tahun',date('Y'))->where('level',1)->where('status',11)->count();
                $data['total_sekolah_nasional']  = Kuesioner::where('tahun',date('Y'))->where('level',2)->where('status',11)->count();
                $data['total_sekolah_mandiri']   = Kuesioner::where('tahun',date('Y'))->where('level',3)->where('status',11)->count();

                $data['summary'] = SampahTerkelola::where('tahun', date('Y'))
                    ->selectRaw('SUM(organik::integer) as organik,
                        SUM(sampah_anorganik::integer) as anorganik,
                        SUM(b3::integer) as b3,
                        SUM(minyak_jelantah::integer) as minyak
                    ')->first();
            }
            
            $data['route']                  = 'modules';
            return view($this->template.'.admin', $data);
        }
    }

    public function gridUsulan(Request $request)
    {
        if(session('kabupaten_id') != ''){
            $usulan = Kuesioner::whereHas('sekolah',function($query){
                $query->where('ms_kabupaten_id',session('kabupaten_id'));
            })->where('tahun',date('Y'))->get();
        }else{
            $usulan = Kuesioner::where('tahun',date('Y'))->get();
        }
        $_data = [];
        foreach ($usulan as $key => $row) {
            $action = '';

            

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

            if(($row->level+1) == 1){
                $jenis_usulan = '<span class="badge bg-success-light text-success">Adiwiyata Kab/Kota</span>';
            }elseif(($row->level+1) == 2){
                $jenis_usulan = '<span class="badge bg-primary-light text-primary">Adiwiyata Provinsi</span>';
            }elseif(($row->level+1) == 3){
                $jenis_usulan = '<span class="badge bg-info-light text-info">Adiwiyata Nasional</span>';
            }elseif(($row->level+1) == 4){
                $jenis_usulan = '<span class="badge bg-warning-light text-warning">Adiwiyata Mandiri</span>';
            }

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

            $dataSekolah = '';
            $dataSekolah .= @$sekolah.'<br>';
            $dataSekolah .= 'Usulan '.@$row->tahun.' : '.@$jenis_usulan.'<br>';

            
            $_data[] = [
                'no'                 => $key+1,
                'dataSekolah'        => @$dataSekolah,
                'nama_sekolah'       => @$sekolah,
                'npsn'               => @$row->sekolah->npsn,
                'kab'                => @$row->sekolah->kabupaten->name,
                'kecamatan'          => @$row->sekolah->kecamatan->name,
                'tahun'              => @$row->tahun,
                'usulan_sebelumnya'  => @$usulanAwal,
                'pengajuan_usulan'   => @$jenis_usulan,
                'status'             => kuesionerLogStatus($row->KuesionerId),
            ];
        }
        return response()->json($_data);
    }

    public function gridAdministrasi(Request $request)
    {
        if(session('group_alias') == 'sekolah'){
            $kuesioner = Kuesioner::where('ms_sekolah_id',session('sekolah_id'))->orderBy('created_at','DESC')->get();
        }else{
            if(session('kabupaten_id') != ''){
                $kuesioner = Kuesioner::where('tahun',date('Y'))->whereHas('dokumen',function($query){
                    $query->where('status',0);
                })->whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->orderBy('created_at','DESC')->get();
            }else{
                $kuesioner = Kuesioner::where('tahun',date('Y'))->whereHas('dokumen',function($query){
                    $query->where('status',0);
                })->orderBy('created_at','DESC')->limit(5)->get();
            }
        }
        
        foreach ($kuesioner as $key => $row) {

            $action = '';

            if((permission('is_create','modules.kuesioner.*','module',false)) || (permission('is_update','modules.kuesioner.*','module',false))){
                $action .= '<a href="'.url('kuesioner/update/'.encode_id($row->ms_sekolah_id)).'" data-toggle="tooltip" title="View Data" class="btn btn-xs btn-block btn-primary"><i class="fal fa-eye text-white"></i></a>';
                if($row->tahun == date('Y')){
                    if(session('group_alias') == 'dinas'){
                        if($row->status == 0){
                            $action .= '<a href="#" data-href="'.url('kuesioner/verifikasi/'.encode_id($row->KuesionerId)).'" data-toggle="tooltip" title="Verifikasi Data" class="btn btn-xs btn-block btn-success verifikasi"><i class="fal fa-check text-white"></i></a>';
                            $action .= '<a href="#" data-href="'.url('kuesioner/tolak/'.encode_id($row->KuesionerId)).'" data-toggle="tooltip" title="Verifikasi Data" class="btn btn-xs btn-block btn-danger tolak"><i class="fal fa-times 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';
            }

            $dok = DokumenAdministrasi::where('ms_sekolah_id',$row->ms_sekolah_id)->where('tahun',date('Y'))->first();
            if(@$dok){
                if(@$dok->status == 1){
                    $labelDok = '<span class="badge bg-success-light">Dokumen Di Verifikasi</span>';
                }elseif(@$dok->status == 2){
                    $labelDok = '<span class="badge bg-danger-light text-white">Dokumen Di Tolak</span>';
                }else{
                    $labelDok = '<span class="badge bg-danger-light text-white">Menuggu Verifikasi Dokumen</span>';
                }
            }else{
                $labelDok = '<span class="badge bg-danger-light text-white">Belum Upload Dokumen</span>';
            }

            $status = '';
            if($row->status == 0){
                $status = '<span class="badge bg-info-light text-info">Belum Diverifikasi</span>';
            }elseif($row->status == 1){
                $status = '<span class="badge bg-success-light text-success">Sudah Diverifikasi</span>';
            }elseif($row->status == 2){
                $status = '<span class="badge bg-danger-light text-danger">Ditolak</span>';
            }elseif($row->status == 11){
                $status = '<span class="badge bg-primary-light text-primary">Terbit SK</span>';
            }else{
                $log  = KuesionerLog::where('kuesioner_id',$row->KuesionerId)->orderBy('created_at','DESC')->first();
                $status = '<span class="badge bg-warning-light text-warning">'.str_replace('_',' ',\Str::title($log->step)).'</span>';
            }

            $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 mt-1">'.@$row->profile->status_sekolah.'</span>&nbsp;';
            $sekolah .= '<span class="badge bg-secondary text-secondary text-left mt-1">'.@$row->profile->alamat_sekolah.'</span>&nbsp;';
            $sekolah .= '<span class="badge text-left mt-1">'.@$row->sekolah->npsn.'</span>&nbsp;';

            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->id),
                'npsn'              => $row->sekolah->npsn,
                'nama'              => $sekolah,
                'status_level'      => '<span style="width:100%" class="badge bg-success-light text-success">Level '.levelAdiwiyata($row->npsn).'</span>',
                'wilayah'           => $row->sekolah->kabupaten->name,
                'kecamatan'         => $row->sekolah->kecamatan->name,
                'alamat_sekolah'    => $row->sekolah->alamat_sekolah,
                'tingkat_sekolah'   => $row->sekolah->tingkat->name,
                'status_sekolah'    => $row->sekolah->status,
                'tahun'             => $row->tahun,
                'alamat_sekolah'    => $row->profile->alamat_sekolah,
                'status'            => kuesionerLogStatus($row->KuesionerId),
                'action'            => $action,
            ];

        }

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