<?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\Usulan;
use App\Models\Kuesioner;
use App\Models\KuesionerLog;

class SuratController extends Controller
{
    private $template = 'modules.usulan.surat';
    private $route = 'modules.usulan.surat';
    private $title = 'Surat Usulan';    

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $data = [];
        $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 = Usulan::where('tahun',date('Y'))->get();
        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';
            }
            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->id),
                'judul'             => $row->nama,
                'sekolah'           => listSekolah($row->sekolah),
                'tahun'             => $row->tahun,
                'jenis_usulan'      => $jenis_usulan,
                'file'              => '<a download href="'.asset('uploads/'.$row->file).'" class="btn btn-sm btn-warning"><i class="fal fa-download"></i> Surat Usulan</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);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // dd($request->all());
        try {
            Validator::make($request->all(), [
                'judul'             => 'max:200',
                '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(Usulan::where('tahun',date('Y'))->where('jenis_usulan',$request->jenis_usulan)->count() > 0){
                return redirect()->back()->with([
                     'message' => 'Maaf Usulan Tahun '.date('Y').' Untuk Usulan '.$usulan.' Sudah Ada',
                     'type'    => "error"
                ]);   
            }

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

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

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

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

            // dd($decoded);

            if(@$request->file){
                $usulan = Usulan::updateOrCreate([
                    'tahun'             => date('Y'),
                    'jenis_usulan'      => $request->jenis_usulan,
                ],[
                    'tahun'             => date('Y'),
                    'nama'              => @$request->nama,
                    'jenis_usulan'      => $request->jenis_usulan,
                    'file'              => $filePath,
                    'deskripsi'         => @$request->deskripsi,
                    'created_by'        => auth()->user()->id,
                    'sekolah'           => json_encode($decoded),
                ]);
            }else{
                $usulan = Usulan::updateOrCreate([
                    'tahun'             => date('Y'),
                    'jenis_usulan'      => $request->jenis_usulan,
                ],[
                    'tahun'             => date('Y'),
                    'nama'              => @$request->nama,
                    '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',0)->where('tahun',date('Y'))->first();
                $kuesioner->status = 1;
                $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           = 'diusulkan';
                $log->status         = 1;
                $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)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

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