<?php

namespace App\Http\Controllers;

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

class StrukturOrganisasiController 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.struktur');
    }

    function json()
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $data = StrukturOrganisasi::orderBy('id', 'DESC')->get();
        return DataTables::of($data)
                    ->addIndexColumn()
                    ->editColumn('options', function($row){
                        $edit = route('struktur.edit', $row->id);
                        $btn = "&emsp;<a href='{$edit}' class='btn btn-sm btn-warning modal-show edit' title='Form Edit Struktur'><i class='fa fa-pencil'></i></a>";
                        return $btn;
                    })
                    ->editColumn('struktur', function($row){
                        if($row->struktur != NULL){
                            $struktur = "<img src=".url('assets/files/struktur/'.$row->struktur.'?time='.time())." width='100px'>";
                        }else{
                            $struktur = "<img src=".url('assets/frontend/img/no-picture.png?time='.time())." width='100px'>";
                        }
                        return $struktur;
                    })
                    ->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', 'struktur', 'status'])
                    ->toJson();
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\StrukturOrganisasi  $strukturOrganisasi
     * @return \Illuminate\Http\Response
     */

    public function update_struktur(ValidationRequest $request)
    {
        try {
            $id = $request->id;
            $cek = StrukturOrganisasi::findOrFail($id);
            if(file_exists("assets/files/struktur/".$cek->struktur)){
                File::delete('assets/files/struktur/'.$cek->struktur);
                if(file_exists("assets/files/struktur/thumbnail/".$cek->struktur)){
                    File::delete('assets/files/struktur/thumbnail/'.$cek->struktur);
                }
            }

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

    public function hapus_struktur(Request $request)
    {
        try {
            $id = $request->id;
            $cek = StrukturOrganisasi::findOrFail($id);
            if(file_exists("assets/files/struktur/".$cek->struktur)){
                File::delete('assets/files/struktur/'.$cek->struktur);
                if(file_exists("assets/files/struktur/thumbnail/".$cek->struktur)){
                    File::delete('assets/files/struktur/thumbnail/'.$cek->struktur);
                }
            }
            $cek->update(['struktur' => null, 'updated_at' => Carbon::now('Asia/Jakarta')]);
            \Helper::log(\Auth::user()->username, "Menghapus gambar struktur organisasi!");
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil menghapus gambar struktur organisasi!']);
        } 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 = StrukturOrganisasi::findOrFail($id);
            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'));
            }
            $cek->update($data);
            \Helper::log(\Auth::user()->username, "Mengupdate status struktur organisasi!");
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil update status struktur organisasi!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }

    public function remove(Request $request)
    {
        try {
            $id = $request->input('id');
            $cek = StrukturOrganisasi::findOrFail($id);
            if(file_exists("assets/files/struktur/".$cek->struktur)){
                File::delete('assets/files/struktur/'.$cek->struktur);
                if(file_exists("assets/files/struktur/thumbnail/".$cek->struktur)){
                    File::delete('assets/files/struktur/thumbnail/'.$cek->struktur);
                }
            }
            $data = array('struktur' => NULL, 'updated_at' => Carbon::now('Asia/Jakarta'));
            $cek->update($data);
            \Helper::log(\Auth::user()->username, "Menghapus data struktur organisasi!");
            return response()->json(['code' => Response::HTTP_OK, 'msg' => 'Berhasil menghapus struktur organisasi!']);
        } catch (QueryException $e) {
            return response()->json(['code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'msg' => $e->errorInfo]);
        }
    }
}
