<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Validator;
use Hashids;
use Yajra\Datatables\Datatables;
use Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

//load modelmu
use App\Model\Transportation;

class TransportationController 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 = 'Transportation'; /**jangan lupa diganti*/
    private $route = 'admin.transportation.'; //path awal foldernya ajah (misal folder di admin/dashboard) => 'admin.dashboard' | jangan lupa diganti
    private $header = 'Transportation';
    private $sub_header = 'Transportation';
    /**khusus namespace ambil pathnya aja contoh : App\Http\Controllers\Admin\Simdondar\DonorDarah -> Admin\Simdondar\DonorDarah*/
    private $namespace_controller = 'Admin';
    private $url_prefix = 'admin/transportation/';

     public function __construct()
    {
        // DB::enableQueryLog();
        // /** nyalakan jika sudah set rolenya, jika ini dinyalakan halaman ini tidak akan keluar */
        // $this->middleware('permission:master_alat-list|master_alat-create|master_alat-update|master_alat-delete', ['only' => ['index', 'create', 'update']]);
        // $this->middleware('permission:master_alat-create', ['only' => ['create', 'create_action']]);
        // $this->middleware('permission:master_alat-update', ['only' => ['update', 'update_action']]);
        // $this->middleware('permission:master_alat-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->route . 'index', $data);
    }
    /**
    *digunakan untuk datatable yajra
    *querynya bisa ganti" sesuai hati
    */
    public function getData()
    {
        $query = Transportation::query();
        $data_table =  Datatables::of($query)
            ->addIndexColumn()
            ->addColumn('aksi', function ($query) {

                /**cek role */
                $aksi = '';
                    $aksi .= "<a href='" . route($this->route . 'update', ['id_di_routenya' => Hashids::encode($query->id)]) . "' class='btn btn-sm btn-primary btn-edit'>Edit</a>";

                // if (Auth::user()->can('master_alat-delete')) {
                //     $aksi .= "<a href='javascript:;' data-route='" . route($this->route . 'delete_action', ['id_di_routenya' => Hashids::encode($query->id)]) . "' class='btn btn-danger btn-sm btn-delete'>Delete</a>";
                // }
                return $aksi;
            })
            ->addIndexColumn()
            ->rawColumns(['aksi'])
            ->escapeColumns([]) //digunakan untuk render html
            ->toJson();
        return $data_table;
    }

    /**
    * create digunakan untuk menampilkan tampilan buat
    */
    public function create()
    {
        $data = [
            //bawaan
            'title'         => $this->title,
            'route'         => $this->route,
            'header'        => $this->header,
            'sub_header'    => $this->sub_header,

        ];

        Helper::swal();

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

    /**
     * create_action digunakan untuk aksi post
     * lengkap dengan validatornya
     */
    public function create_action(Request $request)
    {
        //declare post untuk simpan semua request yang diinputkan oleh form name=""
        $post = $request->all();
        $file = $request->file('gambar');
        //dd($post);
        /**digunakan untuk set rule validator */
        $rules = [
            'gambar' => '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 = 'gambar';

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

            $query                              = new Transportation();
            $query->name                        = $request->name;
            $query->transportation_identity     = $request->transportation_identity;
            $query->transportation_type         = $request->transportation_type;
            $query->transportation_photo        = $nama_file;
            $query->user_id                     = Auth::user()->id;
            $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();
    }

    /** update sama seperti create hanya saja digunakan untuk update (viewnya saja) */
    public function update($id_modelmu)
    {

        Helper::swal();


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

            $cek_data = MasterAlat::where('id', $id_modelmu[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->route . '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);
    }

    /**update_action POST
     * Logikanya :
     * 1. Cek Hashids::decode dari data_id apalah benar" di hash ?
     * -iya
     *  2. Cek ID yang didapatkan dari hash apakah benar adanya ?
     *  -iya
     *    3. proses validate
     *    -iya
     *      4. Proses update
     *        - iya benar
     *        - tidak salah
     *    - tidak return error
     *  - tidak return Id tdak ditemukan
     * -tidak skip reutrn id null
     */
    public function update_action(Request $request)
    {
        $post = $request->all();
       /**digunakan untuk set rule validator */
        $rules = [];
        /**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);

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

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

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

                    $query->nama                = $request->nama;
                    $query->type_alat_id        = $request->type_alat_id;
                    $query->deskripsi           = $request->deskripsi;
                    $query->unit_donor_darah_id = Auth::user()->petugas->unit_donor_darah_id;
                    $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);
        }
    }

    /**digunakan untuk delete
     * Logikanya :
     * 1. Cek hash id
     * -ya
     *  2. Cek id dari hash
     *  - ya
     *      3. Proses delete
     *      -Ya
     *      -Tidak
     *  - tidak return Id tidak ditemukan atau sudah dihapus
     * -tidak reutrn Id tdak ditemukan
     */
    public function delete_action($id_modelmu)
    {
        $id = Hashids::decode($id_modelmu);
        /**cek idnya apakah ada ? */

        if (!empty($id)) {

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

            if ($cek_data) {
                DB::beginTransaction();
                try {
                    //File::delete('gambar/'.$cek_data->gambar);
                    Storage::delete('public/images/'.$cek_data->gambar);
                    $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);
    }

    /**declare routenya disni*/
    public function route(){
        $route = Route::namespace($this->namespace_controller)
            ->prefix($this->url_prefix)
            ->name($this->route)
            ->group(function () {
                Route::get('/', ['as' => 'index', 'uses' => 'TransportationController@index']);
                Route::get('/get-data/{udd_id?}', ['as' => 'get_data', 'uses' => 'TransportationController@getData']);
                Route::get('/datatables', ['as' => 'datatables', 'uses' => 'TransportationController@datatables']);
                Route::get('/create', ['as' => 'create', 'uses' => 'TransportationController@create']);
                Route::get('/update/{id_di_routenya}', ['as' => 'update', 'uses' => 'TransportationController@update']);
                Route::get('/delete-action/{id_di_routenya}', ['as' => 'delete_action', 'uses' => 'TransportationController@delete_action']);

                Route::post('/create-action', ['as' => 'create_action', 'uses' => 'TransportationController@create_action']);
                Route::post('/update-action', ['as' => 'update_action', 'uses' => 'TransportationController@update_action']);
            });
        return $route;
    }
    /**end declare route */
}
