<?php

namespace App\Http\Controllers\Admin\User_management;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Model\Master\MasterRumahSakitKepememilikans;
use App\Model\Master\MasterRumahSakitType;
use App\Model\ModelHasRoles;
use Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Yajra\Datatables\Datatables;
use Auth;
use Illuminate\Support\Facades\Route;

//load modelmu
use Illuminate\Support\Str;
use App\Model\User\MasterRumahSakits as user_rs;
use App\User;
use Spatie\Permission\Models\Role;
use Hash;


class RumahSakitController 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 = 'User Managemen | Rumah Sakit';
    /**jangan lupa diganti*/
    private $route = 'admin.user_management.rumah_sakit.'; //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/rumah-sakit/';

    public function __construct()
    {
        DB::enableQueryLog();
        /** nyalakan jika sudah set rolenya, jika ini dinyalakan halaman ini tidak akan keluar */
        $this->middleware('permission:rumah_sakit-list|rumah_sakit-create|rumah_sakit-update|rumah_sakit-delete', ['only' => ['index', 'create', 'update']]);
        $this->middleware('permission:rumah_sakit-create', ['only' => ['create', 'create_action']]);
        $this->middleware('permission:rumah_sakit-update', ['only' => ['update', 'update_action']]);
        $this->middleware('permission:rumah_sakit-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
     * user_rs:: => dengan model anda
     * $rumah_sakit_id => ganti dengan id di model anda
     * rumah_sakit_id => jangan lupa disesuaikan dengan yang dideclare di route
     */


    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,
        ];
        // dd($data);
        return view($this->route . 'index', $data);
    }
    /**
     *digunakan untuk datatable yajra
     *querynya bisa ganti" sesuai hati
     */
    public function getData()
    {
        $query = user_rs::All();
        foreach ($query as $key => $value) {
            $value->no = ($key + 1);
            $value->email = $value->user->email ?? null;
        }
        return Datatables::of($query)
            ->addColumn('aksi', function ($query) {
                $aksi = '';
                if (Auth::user()->can('rumah_sakit-update')) {
                    $aksi .= "<a href='" . route($this->route . 'update', ['rumah_sakit_id' => Hashids::encode($query->id)]) . "' class='btn btn-sm btn-primary btn-edit'>Edit</a>";
                }

                if (Auth::user()->can('rumah_sakit-delete')) {
                    // $aksi .= "<a href='javascript:;' data-route='" . route($this->route . 'delete_action', ['rumah_sakit_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()
    {
        $data = [
            //bawaan
            'title'     => $this->title,
            'route'     => $this->route,
            'roles'     => Role::where('id',5)->get(),
        ];

        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)
    {
        //declare post untuk simpan semua request yang diinputkan oleh form name=""
        $post = $request->all();
        // dd($post);
        /**digunakan untuk set rule validator */
        $rules = [
            'role_id'          => 'required',
            'nama'             => 'required',
            'deskripsi'        => 'required',
            'email'            => 'required|unique:users,email',
            'password'         => 'required:min:6',
            'alamat'           => 'required',
            'nama_bank_darah'  => 'required',
            'kode_rumah_sakit' => 'required',
            'jenis'            => 'required',
            'kepemilikan'      => 'required',
        ];
        /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
        $alert = [
            'required' => ':attribute',
            'unique'   => ':attribute telah terpakai',
            'min'      => ':attribute :min karakter',
        ];
        $validator = Validator::make($post, $rules, $alert);

        if ($validator->passes()) {
            /**menggunakan transaction */
            DB::beginTransaction();
            $user_rs = [
                'email'    => $post['email'],
                'name'     => $post['nama'],
                'password' => Hash::make($post['password']),
            ];
            $insert_user = User::create($user_rs);
            $insert_user->assignRole($request['role_id']);

                          $data_user_rs     = $request->only(['nama', 'deskripsi', 'alamat', 'nama_bank_darah', 'kode_rumah_sakit']);
            $data_user_rs['user_login_id']  = $insert_user->id;
            $data_user_rs['type_id']        = $post['jenis'];
            $data_user_rs['kepemilikan_id'] = $post['kepemilikan'];
                          $insert_user_rs   = user_rs::create($data_user_rs);

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

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

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


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

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

            if ($cek_data) {
                $data = [
                    //bawaan
                    'title' => $this->title,
                    'route' => $this->route,
                    'data'  => $cek_data,
                    'roles'     => Role::where('id',5)->get()
                ];
                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 */
        // dd($post);
        $rules = [
            'role_id'         => 'required',
            'nama'            => 'required',
            'deskripsi'       => 'required',
            'email'           => 'required',
            'alamat'          => 'required',
            'nama_bank_darah' => 'required',
            'jenis'           => 'required',
            'kepemilikan'     => 'required',
        ];
        /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
        $alert = [
            'required' => ':attribute',
        ];
        $validator = Validator::make($post, $rules, $alert);

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

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

            if ($cek_data) {
                /**cek apakah id data benar" ada di DB ? */
                if ($validator->passes()) {
                    // dd($post);
                    /**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_rs = $request->only(['nama', 'deskripsi', 'alamat', 'nama_bank_darah','kode_rumah_sakit']);
                    $data_rs['type_id']        = $post['jenis'];
                    $data_rs['kepemilikan_id'] = $post['kepemilikan'];
                    $update_rs = $cek_data->update($data_rs);

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

        if (!empty($rumah_sakit_id)) {

            $cek_data = user_rs::where('id', $rumah_sakit_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);
    }

    public function selectJenisRs(Request $request){
        if (session('error')) {
            alert()->html('', session('error'), 'error');
        }
        $term = trim($request['petugas']);
        $query = MasterRumahSakitType::take(5);

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

        $response = [];

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

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

    public function selectKepemilikanRs(Request $request){
        if (session('error')) {
            alert()->html('', session('error'), 'error');
        }
        $term = trim($request['petugas']);
        $query = MasterRumahSakitKepememilikans::take(5);

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

        $response = [];

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

        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' => 'RumahSakitController@index']);
            Route::get('/create', ['as' => 'create', 'uses' => 'RumahSakitController@create']);
            Route::get('/update/{rumah_sakit_id}', ['as' => 'update', 'uses' => 'RumahSakitController@update']);
            Route::get('/delete-action/{rumah_sakit_id}', ['as' => 'delete_action', 'uses' => 'RumahSakitController@delete_action']);
            Route::get('/get-data', ['as' => 'get_data', 'uses' => 'RumahSakitController@getData']);
            Route::get('/select_jenis_rs', ['as' => 'select_jenis_rs', 'uses' => 'RumahSakitController@selectJenisRs']);
            Route::get('/select_jenis_kepemilikan', ['as' => 'select_jenis_kepemilikan', 'uses' => 'RumahSakitController@selectKepemilikanRs']);

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

     //end custom route
}
