<?php

namespace App\Http\Controllers\Admin\Trivia;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use App\Model\Trivia;
use App\Model\TriviaAnswer;
use Yajra\Datatables\Datatables;
use Auth;
use Illuminate\Support\Facades\Storage;
use Validator;
use Hashids;
use URL;

//load modelmu
class TriviaController 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      = 'Trivia';                 /**jangan lupa diganti*/
    private $route      = 'admin.trivia.';          //path awal foldernya ajah (misal folder di admin/dashboard) => 'admin.dashboard' | jangan lupa diganti
    private $header     = 'Trivia';
    private $sub_header = 'Trivia';
    private $url        = 'admin.trivia.';

     public function __construct()
    {
        DB::enableQueryLog();
        /** nyalakan jika sudah set rolenya, jika ini dinyalakan halaman ini tidak akan keluar */
        // $this->middleware('permission:searching-list|searching-create|searching-update|searching-delete', ['only' => ['index', 'create', 'update']]);
        // $this->middleware('permission:searching-create', ['only' => ['create', 'create_action']]);
        // $this->middleware('permission:searching-update', ['only' => ['update', 'update_action']]);
        // $this->middleware('permission:searching-delete', ['only' => ['delete']]);
    }

     /**
    * Ini contoh crud yang sudah jalan
    * index digunakna untuk tampilan awal dari menu yang akan dibuat
    * Untuk CRUD Biar cepat
    * Silahkan ganti
    * EloquentMu:: => dengan model anda
    * $id_modelmu => ganti dengan id di model anda
    * id_di_routenya => jangan lupa disesuaikan dengan yang dideclare di route
    */


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

        $data = [
            //bawaan
            'title'      => $this->title,
            'route'      => $this->route,
            'header'     => $this->header,
            'sub_header' => $this->sub_header,
        ];
        // dd($data);
        return view($this->url . 'index', $data);
    }
    public function getData($udd_id = null)
    {
        // $query = Trivia::query();
        $query = Trivia::leftJoin('trivia_answer', 'trivia.id', '=', 'trivia_answer.trivia_id')
        ->select(['trivia.question', 'trivia.id', 'trivia.image', 'trivia_answer.answer', 'trivia_answer.is_right'])
        ->where('trivia_answer.is_right', 't');
        // dd($query);

        return Datatables::of($query)
            ->addIndexColumn()
            ->addColumn('image', function ($query) {
                $image = '<img src="'.URL::to('storage/images/trivia/'.$query->image).'" alt="'.$query->image.'" style="height: 100px;">';

                return $image;
            })
            ->addColumn('aksi', function ($query) {

                /**cek role */
                $aksi = '';
                // if (Auth::user()->can('master-jenis-kantong-update')) {
                    $aksi .= "<a href='" . route($this->route . 'update', ['trivia_id' => Hashids::encode($query->id)]) . "' class='btn btn-sm btn-primary btn-edit'>Edit</a>";
                // }

                // if (Auth::user()->can('master-jenis-kantong-delete')) {
                    $aksi .= "<a href='javascript:;' data-route='" . route($this->route . 'delete_action', ['trivia_id' => Hashids::encode($query->id)]) . "' class='btn btn-danger btn-sm btn-delete'>Delete</a>";
                // }
                return $aksi;
            })
            ->rawColumns(['aksi', 'image'])
            ->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();
        // dd($post);
        $file = $request->file('image');
        //dd($post);
        /**digunakan untuk set rule validator */
        $rules = [
            'question'   => 'required',
            'image'  => 'required|file|max:1000',
        ];
        /**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();

            $tujuan_upload = 'image';

            //$file->move($tujuan_upload,$nama_file);
            Storage::putFileAs('public/images/trivia/', $file, $nama_file );

            $trivia              = new Trivia();
            $trivia->question    = $request->question;
            $trivia->image       = $nama_file;
            $trivia->save();

            foreach ($request->answer as $key => $value) {
                $trivia_answer              = new TriviaAnswer();
                $trivia_answer->answer      = $value;
                $trivia_answer->trivia_id   = $trivia->id;
                $trivia_answer->is_right    = ($key==0)?"t":"f";
                $trivia_answer->save();
            }

            if ($trivia) {
                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)) {

            $trivia = Trivia::where('id', $data_id[0])->first();
            $trivia_answer = TriviaAnswer::where('trivia_id', $data_id[0])->get();

            if ($trivia) {
                $data = [
                    //bawaan
                    'title'         => $this->title,
                    'route'         => $this->route,
                    'header'        => $this->header,
                    'sub_header'    => $this->sub_header,
                    'trivia'        => $trivia,
                    'trivia_answer' => $trivia_answer
                ];
                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();
        // dd($post);
       /**digunakan untuk set rule validator */
        $rules = [
            'question'   => '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 ? */
            $trivia = Trivia::find($data_id[0]);

            if ($trivia) {
                /**cek apakah id data benar" ada di DB ? */
                if ($validator->passes()) {
                    /**validatornya */
                    DB::beginTransaction();
                    $file = $request->file('image');
                    if($file){
                        $nama_file = time()."_".$file->getClientOriginalName();
                        $tujuan_upload = 'image';
                        //$file->move($tujuan_upload,$nama_file);
                        Storage::putFileAs('public/images/trivia/', $file, $nama_file );
                        //File::delete('image/'.$trivia->image);
                        Storage::delete('public/images/trivia/'.$trivia->image);
                        $trivia->image = $nama_file;
                    }

                    $trivia->question   = $request->question;
                    $trivia->save();

                    $counter=0;
                    foreach ($request->answer as $key => $value) {
                        // dd(($key==0)?"t":"f");
                        $trivia_answer = TriviaAnswer::find($key);
                        $trivia_answer->answer      = $value;
                        $trivia_answer->trivia_id   = $trivia->id;
                        $trivia_answer->is_right    = ($counter==0)?"t":"f";
                        $trivia_answer->save();

                        $counter += 1;
                    }

                    if ($trivia) {
                        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)) {

            $trivia = Trivia::find($id[0]);
            $trivia_answer = TriviaAnswer::where('trivia_id', $id[0])->firstOrFail();

            if ($trivia) {
                DB::beginTransaction();
                try {
                    //File::delete('image/'.$trivia->image);
                    Storage::delete('public/images/trivia/'.$trivia->image);
                    $delete = $trivia->delete();
                    $delete2 = $trivia_answer->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);
    }

}
