<?php

namespace App\Http\Controllers\Modules\Usulan;

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

class SKController extends Controller
{

    private $template = 'modules.usulan.sk';
    private $route    = 'modules.usulan_adiwiyata.sk';
    private $title    = 'Penetapan SK';

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

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

    public function grid(Request $request)
    {
        $usulan = SK::all();
        // dd($usulan);
        $_data = [];
        foreach ($usulan as $key => $row) {

            if($row->jenis_usulan == 1){
                $jenis_usulan = 'Sekolah Adiwiyata Kab/Kota';
            }elseif($row->jenis_usulan == 2){
                $jenis_usulan = 'Sekolah Adiwiyata Provinsi';
            }elseif($row->jenis_usulan == 3){
                $jenis_usulan = 'Sekolah Adiwiyata Nasional';
            }

            $action = '';
            // $action .= '<a href="'.url('usulan/adiwiyata/sk/update/'.encode_id($row->SkId)).'" class="btn btn-primary btn-sm text-white"><i class="fal fa-pencil"></i></a>';

            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->id),
                'nomor_sk'             => $row->nomor_sk,
                'judul'             => $row->nama,
                'sekolah'           => listSekolah($row->sekolah),
                'tahun'             => $row->tahun,
                'tanggal_penetapan' => $row->tanggal_penetapan,
                'jenis_usulan'      => $jenis_usulan,
                'file'              => '<a download href="'.asset('uploads/'.$row->file).'" class="btn btn-sm btn-warning"><i class="fal fa-download"></i> SK Adiwiyata</a>',
                'action'            => @$action,
            ];

        }

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        permission('is_create', $this->route, 'module',true);

        $data['title']    = $this->title;
        $data['route']    = $this->route;

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

    public function update($id)
    {
        permission('is_update', $this->route, 'module',true);

        $data['title']    = $this->title;
        $data['route']    = $this->route;
        $data['sk']    = SK::find(decode_id($id));

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // dd($request->all());
        try {
            Validator::make($request->all(), [
                'nomor_sk'             => 'max:200',
                'judul'             => 'max:200',
                'tanggal_penetapan' => 'date',
                'jenis_usulan'      => 'required',
                'sekolah'           => 'required',
                'file'              => 'required',
            ])->validate();

            if($request->jenis_usulan == '1'){
                $usulan = 'Adiwiyata Kab/Kota';
            }elseif($request->jenis_usulan == '2'){
                $usulan = 'Adiwiyata Provinsi';
            }elseif($request->jenis_usulan == '3'){
                $usulan = 'Adiwiyata Nasional';
            }else{
                return redirect()->back()->with([
                     'message' => 'Maaf Kesalahan Input Data!',
                     'type'    => "error"
                ]);   
            }

            // if(SK::where('tahun',date('Y'))->where('jenis_usulan',$request->jenis_usulan)->count() > 0){
            //     return redirect()->back()->with([
            //          'message' => 'Maaf Penetapan SK Tahun '.date('Y').' Untuk Usulan '.$usulan.' Sudah Ada',
            //          'type'    => "error"
            //     ]);   
            // }

            if ($request->hasFile('file')) {
                $file = $request->file('file');
                $destinationPath = public_path('uploads/sk');
                $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('sk_') . '.' . $fileExtension;

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

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

            $decoded = collect($request->sekolah)->map(function($id) {
                return decode_id($id);
            })->toArray();

            // dd($decoded);

            if(@$request->file){
                $sk = new SK;
                $sk->tahun             = date('Y');
                $sk->nama              = @$request->nama;
                $sk->nomor_sk          = @$request->nomor_sk;
                $sk->tanggal_penetapan = $request->tanggal_penetapan;
                $sk->jenis_usulan      = $request->jenis_usulan;
                $sk->file              = $filePath;
                $sk->deskripsi         = @$request->deskripsi;
                $sk->created_by        = auth()->user()->id;
                $sk->sekolah           = json_encode($decoded);
                $sk->save();

                // $sk = SK::updateOrCreate([
                //     'tahun'             => date('Y'),
                //     'jenis_usulan'      => $request->jenis_usulan,
                // ],[
                //     'tahun'             => date('Y'),
                //     'nama'              => @$request->nama,
                //     'nomor_sk'          => @$request->nomor_sk,
                //     'tanggal_penetapan' => $request->tanggal_penetapan,
                //     'jenis_usulan'      => $request->jenis_usulan,
                //     'file'              => $filePath,
                //     'deskripsi'         => @$request->deskripsi,
                //     'created_by'        => auth()->user()->id,
                //     'sekolah'           => json_encode($decoded),
                // ]);
            }
            // else{
            //     $sk = SK::updateOrCreate([
            //         'tahun'             => date('Y'),
            //         'jenis_usulan'      => $request->jenis_usulan,
            //     ],[
            //         'tahun'             => date('Y'),
            //         'nomor_sk'          => @$request->nomor_sk,
            //         'nama'              => @$request->nama,
            //         'tanggal_penetapan' => $request->tanggal_penetapan,
            //         'jenis_usulan'      => $request->jenis_usulan,
            //         'deskripsi'         => @$request->deskripsi,
            //         'created_by'        => auth()->user()->id,
            //         'sekolah'           => json_encode($decoded),
            //     ]);
            // }

            foreach($request->sekolah as $sekolah){

                $kuesioner = Kuesioner::where('ms_sekolah_id',decode_id($sekolah))->where('status',10)->where('tahun',date('Y'))->first();
                $kuesioner->status = 11;
                $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           = 'terbit_sk';
                $log->status         = 11;
                $log->created_by     = auth()->user()->id;
                $log->save();
            }

            logActivity($request, __('Create',['val' => strtolower(__('Title',['val' => 'Penetapan SK Usulan '.$usulan.' tahun '.date('Y').' oleh '.auth()->user()->id]))]));
            
             return redirect()->back()->with([
                    'message' => 'Berhasil update data',
                    'type'    => 'success',
                ]);
            

        } catch (Exception $e) {
            return redirect()->back()->with([
                     'message' => $e->getMessage(),
                     'type'    => "error"
                ]);
        }
    }

    /**
     * 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)
    {
        //
    }
}
