<?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 Auth;
use Illuminate\Support\Facades\Route;

//load modelmu
use Illuminate\Support\Str;
use App\Model\User\PetugasUnitDonorDarahUdds as petugas_udd;
use App\Model\Master\MasterUdd;
use App\Model\ModelHasRoles;
use App\User;
use Illuminate\Support\Facades\Hash;
use Yajra\Datatables\Datatables;

class PetugasUddController extends Controller
{
    /**
     * Untuk CRUD Biar cepat
     * Silahkan ganti
     * petugas_udd:: => dengan model anda
     * $petugas_udd_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 = 'Admin Usermanagement | Petugas UDD';
    /**jangan lupa diganti*/
    private $route = 'admin.user_management.petugas_udd.'; //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/petugas-udd/';

    public function __construct()
    {
        DB::enableQueryLog();
        /** nyalakan jika sudah set rolenya, jika ini dinyalakan halaman ini tidak akan keluar */
        $this->middleware('permission:petugas_udd-list|petugas_udd-create|petugas_udd-update|petugas_udd-delete', ['only' => ['index', 'create', 'update']]);
        $this->middleware('permission:petugas_udd-create', ['only' => ['create', 'create_action']]);
        $this->middleware('permission:petugas_udd-update', ['only' => ['update', 'update_action']]);
        $this->middleware('permission:petugas_udd-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');
        }
        $data = [
            //bawaan
            'title' => $this->title,
            'route' => $this->route,
        ];
        return view($this->route . 'index', $data);
    }

    public function getData()
    {
        /**
         * deteksi jika dia bukan superadmin
         * jika super admin tampil semua uddnya
         * jika tidak maka tampilin hanya uddnya dia sendiri
         * */
        if (!empty(Helper::is_super_admin())) {
            $petugas = petugas_udd::get();
        } else {
            $udd_id = Auth::user()->petugas->unit_donor_darah_id;
            $petugas = petugas_udd::with('udd')
                ->where('unit_donor_darah_id', $udd_id)
                ->get();
        }
        foreach ($petugas as $key => $value) {
            $value->no = $key + 1;
            $value->email   = $value->user->email;

            $role = '';
            /**get role petugas */
            $data_roles = $value->user->roles()->get();
            foreach ($data_roles as $key => $value_roles) {
                $role       .= $value_roles->name . (($key + 1) < $data_roles->count() ? ', ' : null);
            }
            $value->roles   = $role;
            $value->udd_pmi     =  $value->udd->nama;
        }

        // dd($petugas);
        return Datatables::of($petugas)
            ->addColumn('aksi', function ($petugas) {

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

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

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

    /**
     * create digunakan untuk menampilkan tampilan buat
     * Catatan :
     * Jika rolenya = 1 (superadmin) maka munculkan uddnya untuk piliham udd
     * jika rolenya != 1 maka langsung insert uddnya sesuai dengan udd User id
     */
    public function create()
    {
        $role = Helper::get_roles();
        $jumlah_role = $role->count();
        $limit = 100;
        $take = 0;
        $jumlah_looping = ceil($jumlah_role / $limit);
        $arr_role = [];
        for ($i = 0; $i < $jumlah_looping; $i++) {
            $limit_data = 100;
            $role = $role->take($limit_data)->skip($take);
            $cek_data[] = $role;
            $arr_role[$i] = $role;
            $take = $limit;
            $limit += 100;
        }
        $data = [
            //bawaan
            'title' => $this->title,
            'route' => $this->route,
            'roles' => $arr_role,
        ];
        /**get udd jika role superadmin
         * ini dibagi 4 - 4
         */
        $is_super_admin = Helper::is_super_admin();
        if (!empty($is_super_admin)) {
            $udd = MasterUdd::All();
            $jumlah_udd = $udd->count();
            $limit = 4;
            $take = 0;
            $jumlah_looping = ceil($jumlah_udd / $limit);
            $arr_udd = [];
            for ($i = 0; $i < $jumlah_looping; $i++) {
                $limit_data = 4;
                $udd = $udd->take($limit_data)->skip($take);
                $arr_udd[$i] = $udd;
                $take = $limit;
                $limit += 4;
            }
            $data['udds'] = $arr_udd;
        }
        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 = [
            'nama'                  => 'required|min:4',
            'password'              => 'required|min:6',
            'role_id'               => 'required',
            // 'unit_donor_darah_id'   => 'required',
            'email'                 => 'required|unique:users,email',
        ];
        /**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();
            $data_user = [
                'name'      => $request['nama'],
                'email'     => $request['email'],
                'password'  => Hash::make($request['password']),
            ];
            $insert_user = User::create($data_user);
            $insert_user->assignRole($request['role_id']);

            $data_petugas = [
                'nama' => $request['nama'],
                'unit_donor_darah_id' => $request['unit_donor_darah_id'] ?? Auth::user()->petugas->unit_donor_darah_id,
                'user_login_id' => $insert_user->id,
            ];
            $insert_petugas = petugas_udd::create($data_petugas);

            if ($insert_petugas && $insert_user) {
                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($petugas_udd_id)
    {

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

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


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


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

            if ($cek_data) {

                $role = Helper::get_roles();
                $jumlah_role = $role->count();
                $limit = 100;
                $take = 0;
                $jumlah_looping = ceil($jumlah_role / $limit);
                $arr_role = [];
                for ($i = 0; $i < $jumlah_looping; $i++) {
                    $limit_data = 100;
                    $role = $role->take($limit_data)->skip($take);
                    $arr_role[$i] = $role;
                    $take = $limit;
                    $limit += 100;
                }
                $data = [
                    //bawaan
                    'title' => $this->title,
                    'route' => $this->route,
                    'roles' => $arr_role,
                    'data'  => $cek_data,
                ];
                /**get udd jika role superadmin
                 * ini dibagi 4 - 4
                 */
                $is_super_admin = Helper::is_super_admin();
                if (!empty($is_super_admin)) {
                    $udd = MasterUdd::All();
                    $jumlah_udd = $udd->count();
                    $limit = 4;
                    $take = 0;
                    $jumlah_looping = ceil($jumlah_udd / $limit);
                    $arr_udd = [];
                    for ($i = 0; $i < $jumlah_looping; $i++) {
                        $limit_data = 4;
                        $udd = $udd->take($limit_data)->skip($take);
                        $arr_udd[$i] = $udd;
                        $take = $limit;
                        $limit += 4;
                    }
                    $data['udds'] = $arr_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 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)
    {
        $rules = [
            'nama'                  => 'required|min:4',
            'role_id'               => 'required',
            // 'unit_donor_darah_id'   => '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);

        $petugas_udd_id = Hashids::decode($request['petugas_id']);

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

            if ($cek_data) {
                $cek_email = User::where('id', '!=', $cek_data->user->id)
                    ->where(function ($query) use ($request) {
                        $query->where('email', $request['email']);
                    })
                    ->first();
                if (!empty($cek_email)) {
                    $message = 'Email sudah digunakan';
                    return redirect()->back()->withInput()->with('error', $message);
                }
                /**cek apakah id data benar" ada di DB ? */
                if ($validator->passes()) {
                    /**validatornya */

                    DB::beginTransaction();
                    $data_user = [
                        'name'  => $request['nama'],
                        'email' => $request['email'],
                    ];
                    if ($request['password']) {
                        $length = Str::of($request['password'])->length();
                        if ($length < 6) {
                            $message = 'Password minimal 6 karakter';
                            return redirect()->back()->withInput()->with('error', $message);
                        }
                        $data_user['password'] = Hash::make($request['password']);
                    }
                    /**delete roles */
                    ModelHasRoles::where('model_id', $cek_data->user->id)->delete();
                    $find_user = User::findOrFail($cek_data->user->id);
                    $update_user = $find_user->update($data_user);
                    $find_user->assignRole($request['role_id']);
                    $data_petugas = [
                        'nama'                  => $request['nama'],
                        'unit_donor_darah_id'   => $request['unit_donor_darah_id'] ?? Auth::user()->petugas->unit_donor_darah_id,
                    ];
                    $update_petugas = $cek_data->update($data_petugas);

                    if ($update_petugas && $update_user) {
                        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($petugas_udd_id)
    {
        $petugas_udd_id = Hashids::decode($petugas_udd_id);
        /**cek idnya apakah ada ? */

        if (!empty($petugas_udd_id)) {

            $cek_data = petugas_udd::where('id', $petugas_udd_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 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);
    }
      //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' => 'PetugasUddController@index']);
            Route::get('/create', ['as' => 'create', 'uses' => 'PetugasUddController@create']);
            Route::get('/update/{petugas_udd_id}', ['as' => 'update', 'uses' => 'PetugasUddController@update']);
            Route::get('/delete-action/{petugas_udd_id}', ['as' => 'delete_action', 'uses' => 'PetugasUddController@delete_action']);
            Route::get('/get-data', ['as' => 'get_data', 'uses' => 'PetugasUddController@getData']);

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

      //end custom route
}