<?php

namespace App\Http\Controllers\Admin\Raharja;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use App\Model\Raharja\EventOrganisasi;
use App\Model\Raharja\EventOrganisasiMembers;
use App\Model\Raharja\KelompokDriver;
use App\Model\Raharja\Tips;
use Yajra\Datatables\Datatables;
use Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Validator;
use Hashids;

//load modelmu
class EventOrganisasiController extends Controller
{
    /**
     * Title untuk judul di web
     * route digunakan untuk tempat resource (file path) + routing (route/web) diusahain sama ya biar gak ngubah"
     */
    private $title      = 'Event Organisasi';                 /**jangan lupa diganti*/
    private $route      = 'admin.event-organisasi.';          //path awal foldernya ajah (misal folder di admin/dashboard) => 'admin.dashboard' | jangan lupa diganti
    private $header     = 'Event Organisasi';
    private $sub_header = 'Event Organisasi';
    private $url        = 'admin.raharja.event_organisasi.';

    public function __construct()
    {
        DB::enableQueryLog();
        /** nyalakan jika sudah set rolenya, jika ini dinyalakan halaman ini tidak akan keluar */
    }


    public function index()
    {
        Helper::swal();

        $data = [
            //bawaan
            'title'      => $this->title,
            'route'      => $this->route,
            'header'     => $this->header,
            'sub_header' => $this->sub_header,
        ];

        return view($this->url . 'index', $data);
    }
    public function getData($udd_id = null)
    {
        $query = EventOrganisasi::query();

        return Datatables::of($query)
            ->addIndexColumn()
            ->addColumn('start', function($query){
                return Carbon::parse($query->start_date)->format('Y-m-d');
            })
            ->addColumn('end', function($query){
                return Carbon::parse($query->end_date)->format('Y-m-d');
            })
            ->addColumn('aksi', function ($query) {

                /**cek role */
                $aksi = '';
                $aksi .= "<a href='" . route($this->route . 'update', ['data_id' => Hashids::encode($query->id)]) . "' class='btn btn-sm btn-primary btn-edit'>Edit</a>";
                $aksi .= "<a href='" . route($this->route . 'kelompok_driver', ['data_id' => Hashids::encode($query->id)]) . "' class='btn btn-sm btn-warning btn-edit'>Kelompok Driver</a>";
                $aksi .= "<a href='javascript:;' data-route='" . route($this->route . 'delete_action', ['data_id' => Hashids::encode($query->id)]) . "' class='btn btn-danger btn-sm btn-delete'>Delete</a>";
                return $aksi;
            })
            ->rawColumns(['aksi'])
            ->toJson();
    }
    public function create()
    {
        $data = [
            //bawaan
            'title'         => $this->title,
            'route'         => $this->route,
            'header'        => $this->header,
            'sub_header'    => $this->sub_header,

        ];

        Helper::swal();

        return view($this->url . 'create', $data);
    }

    public function create_action(Request $request)
    {
        //declare post untuk simpan semua request yang diinputkan oleh form name=""
        $post = $request->all();
        $file = $request->file('banner');

        /**digunakan untuk set rule validator */
        $rules = [
            'banner'     => 'required|file|max:1000',
            'start_date' => 'required',
            'end_date'   => 'required',
            'deskripsi'  => 'required',
        ];
        /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
        $alert = [
            'file'  => 'File maksimal 1MB'
        ];
        $validator = Validator::make($post, $rules, $alert);

        if ($validator->passes()) {
            /**menggunakan transaction */
            DB::beginTransaction();

            $nama_file = time()."_".$file->getClientOriginalName();

            Storage::putFileAs('public/images/event_organisasi/', $file, $nama_file );

            $query             = new EventOrganisasi();
            $query->start_date = $request->start_date;
            $query->end_date   = $request->end_date;
            $query->deskripsi  = $request->deskripsi;
            $query->banner     = $nama_file;
            $query->save();

            if ($query) {
                DB::commit();
                $message = 'Berhasil';
                return redirect(route($this->route . 'index'))->with('success', Helper::parsing_alert($message));
            } else {
                DB::rollback();
                $message = 'Gagal';
                return redirect()->back()->with('error', Helper::parsing_alert($message));
            }
        }
        /**kenapa menggunakan back ? karena baliknya pasti ke halaman sebelumnya */
        $message = Helper::parsing_alert($validator->errors()->all());
        return redirect()->back()->with('error', $message)->withInput();
    }

    public function update($data_id)
    {

        Helper::swal();


        $data_id = Hashids::decode($data_id);
        if (!empty($data_id)) {

            $cek_data = EventOrganisasi::where('id', $data_id[0])->first();

            if ($cek_data) {
                $data = [
                    //bawaan
                    'title'         => $this->title,
                    'route'         => $this->route,
                    'header'        => $this->header,
                    'sub_header'    => $this->sub_header,
                    'data'          => $cek_data
                ];
                return view($this->url . 'update', $data);
            }
            $message = 'Id tidak ditemukan atau sudah dihapus';
            return redirect()->back()->with('error', $message);
        }
        $message = 'Id tdak ditemukan';
        return redirect()->back()->with('error', $message);
    }

    public function update_action(Request $request)
    {
        $post = $request->all();
       /**digunakan untuk set rule validator */
        $rules = [
            'banner'     => 'file|max:1000',
            'start_date' => 'required',
            'end_date'   => 'required',
            'deskripsi'  => 'required',
        ];
        /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
        $alert = [];
        $validator = Validator::make($post, $rules, $alert);

        $data_id = Hashids::decode($request['id']);

        if (!empty($data_id)) {
            /**cek apakah data_idnya ada ? */
            $query = EventOrganisasi::find($data_id[0]);

            if ($query) {
                /**cek apakah id data benar" ada di DB ? */
                if ($validator->passes()) {
                    /**validatornya */
                    DB::beginTransaction();
                    $file = $request->file('banner');
                    if($file){
                        $nama_file = time()."_".$file->getClientOriginalName();

                        Storage::putFileAs('public/images/event_organisasi/', $file, $nama_file );

                        Storage::delete('public/images/event_organisasi/'.$query->thumbnail);
                        $query->banner = $nama_file;
                    }

                    $query->start_date = $request->start_date;
                    $query->end_date   = $request->end_date;
                    $query->deskripsi  = $request->deskripsi;
                    $query->save();

                    if ($query) {
                        DB::commit();
                        $message = 'Berhasil';
                        return redirect(route($this->route . 'index'))->with('success', Helper::parsing_alert($message));
                    } else {
                        DB::rollback();
                        $message = 'Gagal';
                        return redirect()->back()->with('error', Helper::parsing_alert($message));
                    }
                }

                $message = Helper::parsing_alert($validator->errors()->all());

                return redirect()->back()->with('error', $message);
            } else {
                $message = 'Id tdak ditemukan';
                return redirect()->back()->with('error', $message);
            }
        } else {
            $message = 'Id tidak boleh kosong';
            return redirect()->back()->with('error', $message);
        }
    }

    public function delete_action($id_modelmu)
    {
        $id = Hashids::decode($id_modelmu);
        /**cek idnya apakah ada ? */

        if (!empty($id)) {

            $cek_data = EventOrganisasi::find($id[0]);

            if ($cek_data) {
                DB::beginTransaction();
                try {
                    $arr_member = $cek_data->kelompokMember;
                    foreach($arr_member as $like){
                        $like->delete();
                    }

                    Storage::delete('public/images/event_organisasi/'.$cek_data->thumbnail);
                    $delete = $cek_data->delete();

                    DB::commit();
                    $message = 'Sukses';
                    $response = [
                        'message' => $message,
                        'status'   => true,
                    ];
                    return response()->json($response);
                } catch (Exception $e) {
                    DB::rollback();
                    $message = 'Gagal';
                    $response = [
                        'message' => $message,
                        'status'   => false,
                    ];
                    return response()->json($response);
                }
            }
            $message = 'Id tidak ditemukan atau sudah dihapus';
            $response = [
                'message' => $message,
                'status'   => false,
            ];
            return response()->json($response);
        }
        $message = 'Id tdak ditemukan';
        $response = [
            'message' => $message,
            'status'   => false,
        ];
        return response()->json($response);
    }


    public function kelompokDriver($data_id)
    {

        Helper::swal();


        $data_id = Hashids::decode($data_id);
        if (!empty($data_id)) {

            $cek_data = EventOrganisasi::where('id', $data_id[0])->first();

            if ($cek_data) {
                $data = [
                    //bawaan
                    'title'          => $this->title,
                    'route'          => $this->route,
                    'header'         => $this->header,
                    'sub_header'     => $this->sub_header,
                    'data'           => $cek_data,
                    'route_get_data' => route($this->route . 'get_data_kelompok_driver', ['data_id' => $cek_data->id]),
                ];
                return view($this->url . 'kelompok_driver_member', $data);
            }
            $message = 'Id tidak ditemukan atau sudah dihapus';
            return redirect()->back()->with('error', $message);
        }
        $message = 'Id tdak ditemukan';
        return redirect()->back()->with('error', $message);
    }

    public function getDataKelompokDriver($data_id){

        $query = EventOrganisasiMembers::where('event_organisasi_id', $data_id);

        return Datatables::of($query)
            ->addIndexColumn()
            ->addColumn('nama', function ($query){
                return $query->kelompokDriver->nama;
            })
            ->filterColumn('nama', function($query, $keyword) {

                $query->whereHas('kelompokDriver', function ($sub) use ($keyword) {
                    $sub->where('nama', 'like', '%' . $keyword . '%');
                });;
            })
            ->addColumn('aksi', function ($query) {

                /**cek role */
                $aksi = '';
                    $aksi .= "<a href='javascript:;' data-route='" . route($this->route . 'delete_kelompok_driver', ['data_id' => Hashids::encode($query->id)]) . "' class='btn btn-danger btn-sm btn-delete'>Delete</a>";
                return $aksi;
            })
            ->rawColumns(['aksi'])
            ->toJson();
    }

    public function deleteKelompokDriver($data_id){
        $id = Hashids::decode($data_id);
        /**cek idnya apakah ada ? */

        if (!empty($id)) {

            $cek_data = EventOrganisasiMembers::find($id[0]);

            if ($cek_data) {
                DB::beginTransaction();
                try {
                    $delete = $cek_data->delete();

                    DB::commit();
                    $message = 'Sukses';
                    $response = [
                        'message' => $message,
                        'status'   => true,
                    ];
                    return response()->json($response);
                } catch (Exception $e) {
                    DB::rollback();
                    $message = 'Gagal';
                    $response = [
                        'message' => $message,
                        'status'   => false,
                    ];
                    return response()->json($response);
                }
            }
            $message = 'Id tidak ditemukan atau sudah dihapus';
            $response = [
                'message' => $message,
                'status'   => false,
            ];
            return response()->json($response);
        }
        $message = 'Id tdak ditemukan';
        $response = [
            'message' => $message,
            'status'   => false,
        ];
        return response()->json($response);
    }

    public function selectKelompokDriver(Request $request){
        if (session('error')) {
            alert()->html('', session('error'), 'error');
        }

        $term = trim($request['nama']);
        $arr_organisasi = EventOrganisasiMembers::where('event_organisasi_id', $request['e_o_id'])->get()->pluck('kelompok_driver_id')->toArray();
        $kelompok_driver = KelompokDriver::whereNotIn('id', $arr_organisasi)->take(10);

        if (!empty($request['not_in'])) {
            $id = collect($request['not_in']);
            $kelompok_driver = $kelompok_driver->whereNotIn('id', $id);
        }
        if (!empty($term)) {
            $kelompok_driver = $kelompok_driver->where('nama', 'like', '%' . $term . '%');
        }
        $kelompok_driver = $kelompok_driver->get();
        $response = [];

        foreach ($kelompok_driver as $key => $value) {
            $response[] = ['id' => $value->id, 'text' => $value->nama ];
        }

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

    public function addKelompokDriver(Request $request){

        $query                      = new EventOrganisasiMembers();
        $query->event_organisasi_id = $request->organisasi_id;
        $query->kelompok_driver_id  = $request->kelompok_driver_id;
        $query->save();

        if ($query) {
            DB::commit();
            $message = 'Berhasil';
            return redirect(route($this->route . 'kelompok_driver',['data_id' => Hashids::encode($request->organisasi_id)]))->with('success', Helper::parsing_alert($message));
        } else {
            DB::rollback();
            $message = 'Gagal';
            return redirect()->back()->with('error', Helper::parsing_alert($message));
        }
    }
}
