<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ValidationRequest;
use App\ManagementSekolah;
use Helper;
use Carbon\Carbon;
use Image;
use File;
use Alert;
use Illuminate\Database\QueryException;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Yajra\DataTables\Facades\DataTables;

class ManagementSekolahController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('pages.be.management_sekolah');
    }

    function json()
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $data = ManagementSekolah::orderBy('id', 'DESC')->get();
        return DataTables::of($data)
                    ->addIndexColumn()
                    ->editColumn('options', function($row){
                        $edit = route('sekolah.edit', $row->id);
                        $btn = "&emsp;<a href='{$edit}' class='btn btn-sm btn-warning modal-show edit' title='Form Edit : {$row->nama}'><i class='fa fa-pencil'></i></a> <button type='button' class='btn btn-sm btn-danger' id='destroy' data-id='{$row->id}'><i class='fa fa-trash'></i></button>";
                        return $btn;
                    })
                    ->editColumn('picture', function($row){
                        if($row->foto != NULL){
                            $picture = "<img src=".url('assets/files/sekolah/'.$row->foto.'?time='.time())." width='100px'>";
                        }else{
                            $picture = "<img src=".url('assets/frontend/img/no-picture.png?time='.time())." width='100px'>";
                        }
                        return $picture;
                    })
                    ->editColumn('status', function($row){
                        if($row->status == 1){
                            $status = "<label class='switch switch-primary'><input data-id='{$row->id}' type='checkbox' id='status' checked ><span></span></label>";
                        }else{
                            $status = "<label class='switch switch-primary'><input data-id='{$row->id}' type='checkbox' id='status' ><span></span></label>";
                        }
                        return $status;
                    })
                    ->editColumn('created_at', function($row){
                        return $row->created_at != NULL ? \Helper::tgl_indo($row->created_at) : "-";
                    })
                    ->editColumn('updated_at', function($row){
                        return $row->updated_at != NULL ? \Helper::tgl_indo($row->updated_at) : "-";
                    })
                    ->rawColumns(['options', 'picture', 'status'])
                    ->toJson();
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $model = new ManagementSekolah();
        return view('pages.be.form_management_sekolah', compact('model'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            $this->validate($request, [
                'nama' => 'required|string',
                'jabatan' => 'required|string'
            ],[
                'nama.required' => 'Nama tidak boleh kosong!',
                'jabatan.required' => 'Jabatan tidak boleh kosong!',
                'string' => 'Hanya format string diperbolehkan!'
            ]);

            $data = new ManagementSekolah();
            $data->nama = $request->nama;
            $data->jabatan = $request->jabatan;
            $data->facebook = $request->facebook;
            $data->twitter = $request->twitter;
            $data->instagram = $request->instagram;
            $data->created_at = Carbon::now('Asia/Jakarta');
            $data->updated_at = null;
            $data->save();
            \Helper::log(\Auth::user()->username, "Menambah data guru/staff : ".$data->nama);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil menyimpan data guru dan staff!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $model = ManagementSekolah::findOrFail($id);
        return view('pages.be.form_management_sekolah', compact('model'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $this->validate($request, [
                'nama' => 'required|string',
                'jabatan' => 'required|string',
            ],[
            'nama.required' => 'Nama tidak boleh kosong!',
            'jabatan.required' => 'Jabatan tidak boleh kosong!',
            'string' => 'Hanya format string diperbolehkan!'
            ]);

            $data = array(
                'nama' => $request->nama,
                'jabatan' => $request->jabatan,
                'facebook' => $request->facebook,
                'twitter' => $request->twitter,
                'instagram' => $request->instagram,
                'updated_at' => Carbon::now('Asia/Jakarta'),
            );
            $sekolah = ManagementSekolah::findOrFail($id);
            $sekolah->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate data guru/staff : ".$sekolah->nama);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil mengupdate data guru dan staff!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    public function update_status(Request $request){
        try {
            $id = $request->id;
            $sekolah = ManagementSekolah::findOrFail($id);
            if($sekolah->status == 0){
                $data = array('status' => '1', 'updated_at' => Carbon::now('Asia/Jakarta'));
            }else{
                $data = array('status' => '0', 'updated_at' => Carbon::now('Asia/Jakarta'));
            }
            $sekolah->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate status data guru/staff : ".$sekolah->nama);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil mengupdate status guru dan staff!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    public function update_foto(ValidationRequest $request)
    {
        try {
            $this->validate($request, [
                'foto' => 'required'
            ],[
            'foto.required' => 'Foto tidak boleh kosong!'
            ]);
            $id = $request->id;
            $sekolah = ManagementSekolah::findOrFail($id);
            if(file_exists("assets/files/sekolah/".$sekolah->foto)){
                File::delete('assets/files/sekolah/'.$sekolah->foto);
                if(file_exists("assets/files/sekolah/thumbnail/".$sekolah->foto)){
                    File::delete('assets/files/sekolah/thumbnail/'.$sekolah->foto);
                }
            }
            if(!File::isDirectory('assets/files/sekolah')){
                File::makeDirectory('assets/files/sekolah', 0755, true, true);
            }
            if(!File::isDirectory('assets/files/sekolah/thumbnail')) {
                File::makeDirectory('assets/files/sekolah/thumbnail', 0755, true, true);
            }

            $id = $request->id;
            $file = $request->file('foto');
            $filename = strtolower('foto-'.Helper::acakstring(8)).'.'.$request->foto->extension();
            $path = "assets/files/sekolah/".$filename;
            $uploaded = Helper::resizeImageAR($file, $path, 800, 600);
            if($uploaded){
                $thumbnailsource = "assets/files/sekolah/".$filename;
                $thumbnailpath = "assets/files/sekolah/thumbnail/". $filename;
                Helper::createThumbnail($thumbnailsource, $thumbnailpath, 300, 225);
            }
            //create backupdata
            // Storage::disk('SFTP')->putFileAs(Helper::web_config('npsn')."/assets/files/sekolah/", $path, $filename);
            // Storage::disk('SFTP')->putFileAs(Helper::web_config('npsn')."/assets/files/sekolah/thumbnail", $thumbnailpath, $filename);
            $data = array('foto' => $filename, 'updated_at' => Carbon::now('Asia/Jakarta'));
            $sekolah->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate foto data guru/staff : ".$sekolah->nama);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil mengupdate foto guru dan staff!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    public function hapus_foto(Request $request)
    {
        try {
            $id = $request->id;
            $sekolah = ManagementSekolah::findOrFail($id);
            if(file_exists("assets/files/sekolah/".$sekolah->foto)){
                File::delete('assets/files/sekolah/'.$sekolah->foto);
                if(file_exists("assets/files/sekolah/thumbnail/".$sekolah->foto)){
                    File::delete('assets/files/sekolah/thumbnail/'.$sekolah->foto);
                }
            }
            $sekolah->update(['foto' => null, 'updated_at' => Carbon::now('Asia/Jakarta')]);
            \Helper::log(\Auth::user()->username, "Menghapus foto data guru/staff : ".$sekolah->nama);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil menghapus foto guru dan staff!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function remove(Request $request)
    {
        try {
            $id = $request->input('id');
            $sekolah = ManagementSekolah::findOrFail($id);
            if(file_exists("assets/files/sekolah/".$sekolah->foto)){
                File::delete('assets/files/sekolah/'.$sekolah->foto);
                if(file_exists("assets/files/sekolah/thumbnail/".$sekolah->foto)){
                    File::delete('assets/files/sekolah/thumbnail/'.$sekolah->foto);
                }
            }
            $sekolah->delete();
            \Helper::log(\Auth::user()->username, "Menghapus data guru/staff : ".$sekolah->nama);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil menghapus data guru dan staff!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }
}
