<?php

namespace App\Http\Controllers\Admin\User_management;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;

use Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Illuminate\Support\Facades\Route;

//load modelmu
use App\User;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use App\Model\Master\MasterUdd;
use App\Model\ModelHasRoles;
use Yajra\Datatables\Datatables;
use Auth;

class UserController extends Controller
{
    /**
     * Untuk CRUD Biar cepat
     * Silahkan ganti
     * User:: => dengan model anda
     * $user_id => ganti dengan id di model anda
     */

    /**
     * Title untuk judul di web
     * route digunakan untuk tempat resource (file path) + routing (route/web) diusahain sama ya biar gak ngubah"
     */
    private $title = 'App User Management | User';
    /**jangan lupa diganti*/
    private $route = 'admin.user_management.user.'; //path awal foldernya ajah (misal folder di admin/dashboard) => 'admin.dashboard' | jangan lupa diganti
    private $namespace_controller = 'Admin\User_management';
    private $url_prefix = 'user-management/user/';

    public function __construct()
    {
        // DB::enableQueryLog();
        // $this->middleware('permission:user-list|user-create|user-update|user-delete', ['only' => ['index', 'create', 'update']]);
        // $this->middleware('permission:user-create', ['only' => ['create', 'create_action']]);
        // $this->middleware('permission:user-update', ['only' => ['update', 'update_action']]);
        // $this->middleware('permission:user-delete', ['only' => ['delete']]);
    }

    /**
     * Ini contoh crud yang sudah jalan
     * index digunakna untuk tampilan awal dari menu yang akan dibuat
     */
    public function index()
    {
        if (session('success')) {
            alert()->html('', session('success'), 'success');
        }

        if (session('error')) {
            alert()->html('', session('error'), 'error');
        }

        // if (empty(Helper::is_super_admin())) {

        //     return redirect('logout');
        // }

        $data = [
            //bawaan
            'title' => $this->title,
            'route' => $this->route,
            'data'  => User::get(),
        ];
        // dd($data);
        return view($this->route . 'index', $data);
    }

    public function getData()
    {
        $query = User::join('model_has_roles as model_role', 'model_role.model_id', 'users.id')
            ->where('role_id', 1); //super admin

        return Datatables::of($query)
            ->addIndexColumn()
            ->addColumn('role_name', function ($query) {

                $role_name = $query->roles()->get()->pluck('name')->toArray();
                $jumlah_data = count($role_name);
                foreach ($role_name as $key => $value) {
                    $semicolon = '';
                    if (($key + 1) > $jumlah_data) {
                        $semicolon = ',';
                    }

                    $name = $value . $semicolon;
                }

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

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

                if (Auth::user()->can('user-delete')) {
                    // $aksi .= "<a href='javascript:;' data-route='" . route($this->route . 'delete_action', ['user_id' => Hashids::encode($query->id)]) . "' class='btn btn-danger btn-sm btn-delete'>Delete</a>";
                }

                return $aksi;
            })
            ->rawColumns(['aksi'])
            ->toJson();
    }

    /**
     * create digunakan untuk menampilkan tampilan buat
     */
    public function create()
    {
        /**set role dengan cara dibagi 4 - 4 */
        $data = [
            //bawaan
            'title' => $this->title,
            'route' => $this->route,
        ];
        if (session('success')) {
            alert()->html('', session('success'), 'success');
        }

        if (session('error')) {
            alert()->html('', session('error'), 'error');
        }

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

    /**
     * create_action digunakan untuk aksi post
     * lengkap dengan validatornya
     */
    public function create_action(Request $request)
    {
        /**digunakan untuk set rule validator */
        $rules = [
            'name'          => 'required|min:4|unique:users,name',
            'email'         => 'required|unique:users,email',
            'password'      => 'required|min:6',
        ];
        /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
        $alert = [
            'unique'    => ':attribute sudah tersedia',
            'required'  => 'The :attribute harus diisi',
            'min'       => ':attribute minimal :min  karakter'
        ];

        $validator = Validator::make($request->all(), $rules, $alert);

        if ($validator->passes()) {
            /**menggunakan transaction */
            DB::beginTransaction();
            $insert = [
                'name'      => $request['name'],
                'password'  => Hash::make($request['password']),
                'email'     => $request['email']
            ];
            $query = User::create($insert);
            $data_role['role_id'] = 1; //super admin
            $query->assignRole($data_role);

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

        if (session('success')) {
            alert()->html('', session('success'), 'success');
        }

        if (session('error')) {
            alert()->html('', session('error'), 'error');
        }


        $user_id = Hashids::decode($user_id);
        $data_udd = MasterUdd::get();
        if (!empty($user_id)) {
            $role = Role::get();
            $jumlah_role = $role->count();
            $limit = 4;
            $take = 0;
            $jumlah_looping = ceil($jumlah_role / $limit);
            $arr_role = [];
            for ($i = 0; $i < $jumlah_looping; $i++) {
                // $cek_limit[] = $limit;
                // $cek_take[] = $take;
                $limit_data = 4;
                $role = Role::take($limit_data)->skip($take)->get();
                $cek_data[] = $role;
                $arr_role[$i] = $role;
                $take = $limit;
                $limit += 4;
            }

            $cek_data          = User::where('id', $user_id[0])->first();
            $cek_data->role    = $cek_data->roles->pluck('id')->toArray();
            $cek_data->udd_id  = $cek_data->petugas->unit_donor_darah_id ?? null;
            if ($cek_data) {
                $data = [
                    //bawaan
                    'title' => $this->title,
                    'route' => $this->route,
                    'data'  => $cek_data,
                    'role'  => $arr_role,
                    'udd'   => $data_udd,
                ];
                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 role_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)
    {
        /**digunakan untuk set rule validator */
        $rules = [
            'name'  => 'required|min:4',
            'email' => 'required',
        ];
        /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
        $alert = [
            'required'  => 'The :attribute harus diisi',
            'min'       => ':attribute minimal :min  karakter'
        ];
        $validator = Validator::make($request->all(), $rules, $alert);

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

        if (!empty($user_id)) {
            /**cek apakah id ada ? */
            $cek_data = User::where('id', $user_id[0])->first();

            if ($cek_data) {
                /**cek apakah id rolenya benar" ada di DB ? */
                if ($validator->passes()) {
                    /**validatornya */
                    $update = [
                        'name'  => $request['name'],
                        'email' => $request['email'],
                    ];

                    /**jika passwordnya disii */
                    if ($request['password']) {
                        $update['password'] = Hash::make($request['password']);
                    }

                    DB::beginTransaction();
                    ModelHasRoles::where('model_id', $user_id)->delete();
                    $query = $cek_data->update($update);
                    $role['role_id'] = 1;
                    $cek_data->assignRole($role['role_id']);

                    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($user_id)
    {
        $user_id = Hashids::decode($user_id);
        /**cek role idnya apakah ada ? */

        if (!empty($user_id)) {

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

            if ($cek_data) {
                DB::beginTransaction();
                $delete = $cek_data->delete();
                if ($delete) {
                    DB::commit();
                    $message = 'Succesfully';
                    $response = [
                        'message' => $message,
                        'status'   => true,
                    ];
                    return response()->json($response);
                } else {
                    DB::rollback();
                    $message = 'Gagal';
                    $response = [
                        'message' => $message,
                        'status'   => false,
                    ];
                    return response()->json($response);
                }
            }
            $message = 'Id tidak di temukan atau sudah di hapus';
            $response = [
                'message' => $message,
                'status'   => false,
            ];
            return response()->json($response);
        }
        $message = 'Id tdak ditemukan';
        $response = [
            'message' => $message,
            'status'   => false,
        ];
        return response()->json($response);
    }
      //custom route

      public function route()
      {
          return Route::group([
              'as' => $this->route,
              'prefix' => $this->url_prefix,
              'namespace' => $this->namespace_controller
          ], function () {
            Route::get('/', ['as' => 'index', 'uses' => 'UserController@index']);
            Route::get('/create', ['as' => 'create', 'uses' => 'UserController@create']);
            Route::get('/update/{user_id}', ['as' => 'update', 'uses' => 'UserController@update']);
            Route::get('/delete-action/{user_id}', ['as' => 'delete_action', 'uses' => 'UserController@delete_action']);
            Route::get('/get-data', ['as' => 'get_data', 'uses' => 'UserController@getData']);

            Route::post('/create-action', ['as' => 'create_action', 'uses' => 'UserController@create_action']);
            Route::post('/update-action', ['as' => 'update_action', 'uses' => 'UserController@update_action']);
          });
      }

      //end custom route
}
