<?php

namespace App\Http\Controllers\Modules\Usulan;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Master\Provinsi;
use App\Models\Kuesioner;
use App\Models\KuesionerLog;
use App\Models\DokumenAdministrasi;
use App\Models\Usulan;
use App\Models\Master\Kecamatan;

class AdministrasiController extends Controller
{
    private $template = 'modules.usulan.administrasi';
    private $route = 'modules.usulan_adiwiyata.administrasi';
    private $title = 'Usulan Adiwiyata - Dokumen Administrasi';

    public function index()
    {
        $data['route'] = $this->route;
        $data['title'] = $this->title;
        $data['provinsi'] = Provinsi::where('kode_wilayah','010000')->get();
        
        if(session('kabupaten_id') != ''){
            $data['kecamatan'] = Kecamatan::where('ms_kabupaten_id',session('kabupaten_id'))->get();
        }

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

    public function grid(Request $request)
    {
        $_data = [];
        if(session('group_alias') == 'sekolah'){
            $kuesioner = Kuesioner::where('tahun',date('Y'))->where('ms_sekolah_id',session('sekolah_id'))->orderBy('created_at','DESC');
        }else{
            if(session('kabupaten_id') != ''){
                $kuesioner = Kuesioner::whereHas('sekolah',function($query){
                    $query->where('ms_kabupaten_id',session('kabupaten_id'));
                })->orderBy('created_at','DESC');
            }else{
                $kuesioner = Kuesioner::orderBy('created_at','DESC');
            }
        }

        if(@request()->tingkat){
            $kuesioner->whereHas('sekolah',function($query){
                $query->where('ms_tingkat_sekolah_id',request()->tingkat);
            });
        }
        if(@request()->status_sekolah){
            $kuesioner->whereHas('sekolah',function($query){
                $query->where('status',request()->status_sekolah);
            });
        }
        if(@request()->level){
            $kuesioner->where('level',(request()->level-1));
        }
        if(@request()->tahun){
            $tahun = request()->tahun;
        }else{
            $tahun = date('Y');
        }
        if(@request()->provinsi != 0){
            $kuesioner->whereHas('sekolah',function($query){
                $query->where('ms_provinsi_id',decode_id(request()->provinsi));
            });
        }
        if(@request()->kabupaten != 0){
            $kuesioner->whereHas('sekolah',function($query){
                $query->where('ms_kabupaten_id',decode_id(request()->kabupaten));
            });
        }
        if(@request()->kecamatan != 0){
            $kuesioner->whereHas('sekolah',function($query){
                $query->where('ms_kecamatan_id',decode_id(request()->kecamatan));
            });
        }

        $kuesioner->where('tahun',$tahun);
        
        foreach ($kuesioner->get() as $key => $row) {

            $action = '';

            // if((access('is_create', $this->route.'.*')) || (access('is_update', $this->route.'.*'))){
            //     $action .= '<a href="#" data-secureid="'.encode_id($row->KuesionerId).'" data-toggle="modal" data-target="#modal" title="View Data" data-jenisusulan="'.$jenis_usulan.'" class="btn btn-xs btn-block btn-primary btnModal"><i class="fal fa-pencil text-white"></i></a>';
            // }

            if(($row->level+1) == 1){
                $jenis_usulan = 'Keputusan Gubernur tentang penetapan Sekolah Adiwiyata Kab/Kota';
            }elseif(($row->level+1) == 2){
                $jenis_usulan = 'Keputusan Gubernur tentang penetapan Sekolah Adiwiyata Provinsi';
            }elseif(($row->level+1) == 3){
                $jenis_usulan = 'Keputusan Gubernur tentang penetapan Sekolah Adiwiyata Nasional';
            }elseif(($row->level+1) == 4){
                $jenis_usulan = 'Keputusan Gubernur tentang penetapan Sekolah Adiwiyata Mandiri';
            }

            $usulan = Usulan::where('sekolah','like','%'.$row->ms_sekolah_id.'%')->first();

            $dok = DokumenAdministrasi::where('ms_sekolah_id',$row->ms_sekolah_id)->where('tahun',date('Y'))->first();

            if(session('group_alias') == 'sekolah'){
                if((@$dok->status == 0) || (@$dok->status == 2)){
                    if(@$dok->status != 0){
                        if($row->tahun == date('Y')){
                            $action .= '<a href="#" data-filetim="'.@$dok->file_sk_tim.'" data-fileusulan="'.@$dok->file_usulan.'" data-link="'.@$dok->link.'" data-level="'.$row->level.'" data-secureid="'.encode_id($row->KuesionerId).'" data-toggle="modal" data-target="#modal" title="View Data" data-jenisusulan="'.$jenis_usulan.'" class="btn btn-xs btn-block btn-primary btnModal"><i class="fal fa-pencil text-white"></i></a>';
                        }
                    }
                }
            }
            // $action .= '<a href="#" data-link="'.@$dok->link.'" data-jenisusulan="'.$jenis_usulan.'" class="btn btn-xs btn-block btn-secondary toggle-row" data-toggle="tooltip" data-placement="top" title="JUDUL"><i class="fal fa-list text-white"></i></a>';
            if((session('group_alias') == 'dinas') || (session('group_alias') == 'suku_dinas')){
                if(@$dok){
                    if(@$dok->status == 0){
                        if($row->tahun == date('Y')){
                            $action .= '<a href="#" data-href="'.url('usulan/adiwiyata/administrasi/verifikasi/'.encode_id($dok->DokumenAdministrasiId)).'" 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('usulan/adiwiyata/administrasi/tolak/'.encode_id($dok->DokumenAdministrasiId)).'" data-toggle="tooltip" title="Verifikasi Data" class="btn btn-xs btn-block btn-danger tolak"><i class="fal fa-times text-white"></i></a>';
                        }
                    }
                }else{
                    if($row->tahun == date('Y')){
                        $action .= '<a href="#" data-href="'.url('usulan/adiwiyata/administrasi/tolak_kosong/'.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>';
                    }
                }
            }

            $fileUsulan = '';
            $fileUsulan .= '<div class="btn-group">
                                <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">Lihat File</button>
                                <div class="dropdown-menu">';
                                if(@$dok->link){
                                    $fileUsulan .= '<a download href="'.asset('uploads/'.@$dok->link).'" class="dropdown-item">Download SK Adiwiyata</a>';
                                }
                                if(@$dok->file_usulan){
                                    $fileUsulan .= '<a download href="'.asset('uploads/'.@$dok->file_usulan).'" class="dropdown-item">Download Surat Usulan</a>';
                                }
                                if(@$dok->file_sk_tim){
                                    $fileUsulan .= '<a download href="'.asset('uploads/'.@$dok->file_sk_tim).'" class="dropdown-item">Download SK Tim Adiwiyata</a>';
                                }
                                $fileUsulan .= '</div>
                            </div>';
            

            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';
            }

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

            
            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">Dokumen Di Tolak</span>';
                }else{
                    $labelDok = '<span class="badge bg-warning-light">Menuggu Verifikasi Dokumen</span>';
                }
            }else{
                $labelDok = '<span class="badge bg-danger-light">Belum Upload Dokumen</span>';
            }

            // if($row->status == 0){
            //     $labelDok .= '<br><span class="badge bg-danger-light">Menunggu Usulan Dari Dinas/Sudin</span>';
            // }

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

            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->id),
                'npsn'              => $row->sekolah->npsn,
                'nama'              => $sekolah,
                'tahun'             => $row->tahun,
                'labelDok'          => $labelDok,
                'status_level'      => '<span style="width:100%" class="badge bg-secondary">Level '.levelAdiwiyata($row->npsn).'</span>',
                'wilayah'           => $row->sekolah->kabupaten->name,
                'kecamatan'         => $row->sekolah->kecamatan->name,
                'penghargaan'       => $penghargaan,
                'jenis_usulan'      => '<span class="badge bg-success-light">'.$jenis_usulan.'</span>',
                'usulan'            => $fileUsulan,
                'action'            => $action,
            ];

        }

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

    public function update(Request $request)
    {
        try {
            $sekolahId  = decode_id($request->sekolah);
            $dokumen    = DokumenAdministrasi::where('ms_sekolah_id',$sekolahId)->where('tahun',date('Y'))->first();
            $dokumen->nama_dalam_sk     = $request->nama_dalam_sk;
            $dokumen->sk_ttd            = $request->sk_ttd;
            $dokumen->waktu_penetapan   = $request->waktu_penetapan;
            $dokumen->save();

            return response()->json(['status' => true,'message' => 'Berhasil Update Data','type' => 'success']);
        } catch (Exception $e) {
            return response()->json(['status' => false,'message' => $e->getMessage(),'type' => 'error']);
        }
        
    }

    public function store(Request $request)
    {
        // dd($request->all());
        // $data = $request['data'];
    
        $keyId = decode_id($request->secure_id);
        // dd($keyId);

        if(!@$keyId){
            return response()->json(['status' => false,'message' => 'Maaf Terjadi Kesalahan','type' => 'error']);
        }

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

        if(@$dok->status == 1){
            return response()->json(['status' => false,'message' => 'Dokumen Sudah di verifikasi','type' => 'info']);
        }

        if (@$request->hasFile('file')) {
            $file = $request->file('file');
            $destinationPath = public_path('uploads/file');
            $current = Carbon::now()->format('Y/m/d');
            $path = $destinationPath . '/' . $current;
            $fileName = $file->getClientOriginalName();
            $fileMime = $file->getClientMimeType();
            $fileExtension = $file->getClientOriginalExtension();
            $fileSize = $file->getSize();
            if($fileExtension != 'pdf'){
                return redirect()->back()->with([
                     'message' => 'Maaf File Harus Berupa PDF!',
                     'type'    => "error"
                ]);   
            }
            $newFilename = session('uid').'_'.uniqid('file_') . '.' . $fileExtension;

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

            $filePath = 'file/' . $current . '/' . $newFilename;
            $uploaded = $file->move($path, $newFilename);
        }

        if (@$request->hasFile('sk_tim_adiwiyata')) {
            $file = $request->file('sk_tim_adiwiyata');
            $destinationPath = public_path('uploads/tim_adiwiyata');
            $current = Carbon::now()->format('Y/m/d');
            $path = $destinationPath . '/' . $current;
            $fileName = $file->getClientOriginalName();
            $fileMime = $file->getClientMimeType();
            $fileExtension = $file->getClientOriginalExtension();
            $fileSize = $file->getSize();
            if($fileExtension != 'pdf'){
                return redirect()->back()->with([
                     'message' => 'Maaf File Harus Berupa PDF!',
                     'type'    => "error"
                ]);   
            }
            $newFilename = session('uid').'_'.uniqid('file_sk_tim_') . '.' . $fileExtension;

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

            $filePathTim = 'tim_adiwiyata/' . $current . '/' . $newFilename;
            $uploaded = $file->move($path, $newFilename);

            $kuesioner = Kuesioner::find($keyId);
            $kuesioner->tim_adiwiyata_link = $filePathTim;
            $kuesioner->save();
        }

        if (@$request->hasFile('surat_usulan')) {
            $file = $request->file('surat_usulan');
            $destinationPath = public_path('uploads/file_usulan');
            $current = Carbon::now()->format('Y/m/d');
            $path = $destinationPath . '/' . $current;
            $fileName = $file->getClientOriginalName();
            $fileMime = $file->getClientMimeType();
            $fileExtension = $file->getClientOriginalExtension();
            $fileSize = $file->getSize();
            if($fileExtension != 'pdf'){
                return redirect()->back()->with([
                     'message' => 'Maaf File Harus Berupa PDF!',
                     'type'    => "error"
                ]);   
            }
            $newFilename = session('uid').'_'.uniqid('file_usulan_') . '.' . $fileExtension;

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

            $filePathUsulan = 'file_usulan/' . $current . '/' . $newFilename;
            $uploaded = $file->move($path, $newFilename);
        }
        // dd($filePathUsulan);

        

        $dok = DokumenAdministrasi::updateOrCreate([
            'kuesioner_id'  => $keyId,
            'ms_sekolah_id' => session('sekolah_id'),
            'npsn'          => session('npsn'),
            'created_by'    => auth()->user()->id,
            'tahun'         => date('Y'),
        ],[
            'kuesioner_id'  => $keyId,
            'ms_sekolah_id' => session('sekolah_id'),
            'npsn'          => session('npsn'),
            'created_by'    => auth()->user()->id,
            'tahun'         => date('Y'),
            'link'          => @$filePath,
            'file_sk_tim'   => @$filePathTim,
            'file_usulan'   => @$filePathUsulan,
            'status'        => 0,
        ]);

        $kuesioner = Kuesioner::find($keyId);
        if(@$filePathTim){
            $kuesioner->tim_adiwiyata_link = @$filePathTim;
        }
        if(@$filePath){
            $kuesioner->link_sk_adiwiyata = @$filePath;
        }
        $kuesioner->save();

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

    public function verifikasi($id)
    {
        $keyId = decode_id($id);

        $dok = DokumenAdministrasi::find($keyId);
        $dok->status = 1;
        $dok->save();

        $kuesioner = Kuesioner::where('KuesionerId',$dok->kuesioner_id)->first();

        $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           = 'sekolah_mengisi_form_pemenuhan_kriteria';
        $log->status         = 1;
        $log->created_by     = auth()->user()->id;
        $log->save();

        return response()->json(['status' => true,'message' => 'Data Berhasil Di Update','type' => 'success']);
    }
    public function tolak($id)
    {
        $keyId = decode_id($id);
        $dok = DokumenAdministrasi::find($keyId);
        $dok->status = 2;
        $dok->save();

        $kuesioner = Kuesioner::where('KuesionerId',$dok->kuesioner_id)->first();

        $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           = 'verifikasi_kuesioner_dikembalikan';
        $log->status         = 1;
        $log->created_by     = auth()->user()->id;
        $log->save();

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

    public function tolak_kosong($id)
    {
        $keyId = decode_id($id);
        $dok = Kuesioner::find($keyId);
        $dok->delete();

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