<?php

namespace App\Http\Controllers;

use App\Kegiatan;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Http\Requests\ValidationRequest;
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 Yajra\DataTables\Facades\DataTables;

class KegiatanController 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.kegiatan');
    }

    function json()
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $data = Kegiatan::orderBy('id', 'DESC')->get();
        return DataTables::of($data)
                    ->addIndexColumn()
                    ->editColumn('options', function($row){
                        $edit = route('kegiatan.edit', $row->id);
                        $btn = "&emsp;<a href='{$edit}' class='btn btn-sm btn-warning modal-show edit' title='Form Edit Kegiatan: {$row->title}'><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->picture != NULL){
                            $picture = "<img src=".url('assets/files/kegiatan/'.$row->picture.'?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 Kegiatan();
        return view('pages.be.form_kegiatan', 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, [
                'title' => 'required|string',
                'caption' => 'required'
            ],[
                'title.required' => 'Title Kegiatan harus diisi!',
                'title.string' => 'Title Kegiatan hanya string!',
                'caption.required' => 'Caption harus diisi!'
            ]);

            $data = new Kegiatan();
            $data->title = $request->title;
            $data->caption = $request->caption;
            $data->tanggal_kegiatan = date('y-m-d', strtotime($request->tanggal_kegiatan));
            $data->lokasi_kegiatan = $request->lokasi_kegiatan;
            $data->slug = Helper::createKegSlug($request->title);
            $data->created_at = Carbon::now('Asia/Jakarta');
            $data->updated_at = null;
            $data->save();
            \Helper::log(\Auth::user()->username, "Menambah data kegiatan : ".$data->title);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil menambah dokumen kegiatan!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Kegiatan  $kegiatan
     * @return \Illuminate\Http\Response
     */
    public function show(Kegiatan $kegiatan)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Kegiatan  $kegiatan
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $this->validate($request, [
                'title' => 'required|string',
                'caption' => 'required'
            ],[
                'title.required' => 'Title Kegiatan harus diisi!',
                'title.string' => 'Title Kegiatan hanya string!',
                'caption.required' => 'Caption harus diisi!'
            ]);

            $data = array(
                'title' => $request->title,
                'slug' => Helper::createKegSlug($request->title, $id),
                'caption' => $request->caption,
                'tanggal_kegiatan' => $request->tanggal_kegiatan,
                'lokasi_kegiatan' => $request->lokasi_kegiatan,
                'updated_at' => Carbon::now('Asia/Jakarta')
            );
            $kegiatan = Kegiatan::findOrFail($id);
            $kegiatan->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate data kegiatan : ".$kegiatan->title);
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil update kegiatan!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

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

    }

    public function update_picture(ValidationRequest $request)
    {
        try {
            $this->validate($request, [
                'picture' => 'required'
            ],[
            'picture.required' => 'Gambar tidak boleh kosong!'
            ]);
            $id = $request->id;
            $kegiatan = Kegiatan::findOrFail($id);

            if(file_exists("assets/files/kegiatan/".$kegiatan->picture)){
                File::delete('assets/files/kegiatan/'.$kegiatan->picture);
                if(file_exists("assets/files/kegiatan/thumbnail/".$kegiatan->picture)){
                    File::delete('assets/files/kegiatan/thumbnail/'.$kegiatan->picture);
                }
            }

            if(!File::isDirectory('assets/files/kegiatan')){
                File::makeDirectory('assets/files/kegiatan', 0755, true, true);
            }
            if(!File::isDirectory('assets/files/kegiatan/thumbnail')) {
                File::makeDirectory('assets/files/kegiatan/thumbnail', 0755, true, true);
            }

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

    public function hapus_picture(Request $request)
    {
        $id = $request->id;
        $cek = Kegiatan::where('id', $id)->first();
        if(file_exists("assets/files/kegiatan/".$cek->picture)){
            File::delete('assets/files/kegiatan/'.$cek->picture);
            if(file_exists("assets/files/kegiatan/thumbnail/".$cek->picture)){
                File::delete('assets/files/kegiatan/thumbnail/'.$cek->picture);
            }
        }
        $update = Kegiatan::where('id', $id)->update(['picture' => null, 'updated_at' => Carbon::now('Asia/Jakarta')]);
        \Helper::log(\Auth::user()->username, "Menghapus foto data kegiatan : ".$cek->title);
        if($update){
            return response()->json(true);
        }else{
            return response()->json(false);
        }
    }

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

    public function remove(Request $request)
    {
        $id = $request->input('id');
        $cek = Kegiatan::where('id', $id)->first();
        if(file_exists("assets/files/kegiatan/".$cek->picture)){
            File::delete('assets/files/kegiatan/'.$cek->picture);
            if(file_exists("assets/files/kegiatan/thumbnail/".$cek->picture)){
                File::delete('assets/files/kegiatan/thumbnail/'.$cek->picture);
            }
        }
        $delete = Kegiatan::where('id', $id)->delete();
        \Helper::log(\Auth::user()->username, "Menghapus data kegiatan : ".$cek->title);
        if($delete){
            return response()->json(true);
        }else{
            return response()->json(false);
        }
    }
}
