<?php

namespace App\Http\Controllers\Operator;

use Uuid;
use App\Models\Role;

use App\Models\User;
use App\Helpers\InseoHelper;
use App\Models\Auth\Biodata;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use RealRashid\SweetAlert\Facades\Alert;
use Spatie\Permission\Models\Role as ModelsRole;

class UserExternalController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['title'] = 'Daftar User External';
        $data['users'] = User::with(['rBiodata','rolesCustom'])->whereHas('rolesCustom',function ($q){
                                $q->whereIn('name', ['reviewer']);
                            })->where('status', '2')->get();

        return view('backend.operator.user_external.index', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('backend.operator.user_external.create')->withTitle('Tambah User External');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $uuid = Uuid::generate();
        $password = InseoHelper::random_password();
        $data['id'] = $uuid;
        $data['name'] = $request->input('nama');
        $data['email'] = $request->input('email');
        $data['password_decrypt'] = $password;
        $data['password'] = Crypt::encrypt($password);
        $data['status'] = '2';

        if(User::create($data))
        {
            $detil['id'] = $uuid;
            $detil['email'] = $request->input('email');
            $detil['name'] = $request->input('nama');
            // $detil['noidentitas'] = $request->input('nidn');
            // $detil['fakultas'] = $request->input('fakultas');
            // $detil['prodi'] = $request->input('prodi');
            $detil['userid_created'] = Auth::user()->id;
            Biodata::create($detil);

            $values = array('role_id' => '2619bc99-0027-4997-9510-d4736bd26862', 'model_type' => 'App\Models\User', 'model_id' => $uuid);
            DB::table('model_has_roles')->insert($values);

            Alert::success('Data berhasil disimpan')->persistent('Ok');
            $successmessage = "Proses Tambah User External Berhasil.";
        }
        else
        {
            Alert::success('Data gagal disimpan')->persistent('Ok');
            $successmessage = "Proses Tambah User External Gagal.";
        }

        return redirect()->route('operator.user-external.index')->with('successMessage', $successmessage);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data['title'] = 'Ubah User External';
        $data['user'] = User::with(['rBiodata','rolesCustom'])->whereHas('rolesCustom',function ($q){
                    $q->whereIn('name', ['reviewer']);
                })->find(decrypt($id));

        return view('backend.operator.user_external.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $user = User::find(decrypt($id));
        $user->name = $request->input('nama');
        $user->save();

        if($user->save())
        {

            $biodata = Biodata::find(decrypt($id));
            $biodata->noidentitas = $request->input('nidn');
            $biodata->name = $request->input('nama');
            $biodata->fakultas = $request->input('fakultas');
            $biodata->prodi = $request->input('prodi');
            $biodata->email = $request->input('email');
            $biodata->save();

            Alert::success('Data berhasil disimpan')->persistent('Ok');
            $successmessage = "Proses Tambah User External Berhasil.";
        }
        else
        {
            Alert::success('Data gagal disimpan')->persistent('Ok');
            $successmessage = "Proses Tambah User External Gagal.";
        }

        return redirect()->route('operator.user-external.index')->with('successMessage', $successmessage);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            $biodata = Biodata::find(decrypt($id));
            $cari = DB::select("SELECT cek_data_reviewer('".$biodata->noidentitas."')")[0]->cek_data_reviewer;

            if ($cari == 1) {
                $status = false;
                $info = "Maaf data user tidak dapat dihapus karena telah dipilih untuk menjadi reviewer.";
            }
            else{

                $biodata = Biodata::find(decrypt($id));
                $biodata->delete();

                $user = User::find(decrypt($id));
                $user->delete();

                DB::table('model_has_roles')->where('model_id',decrypt($id))->delete();
                $status = true;
                $info = "Data berhasil dihapus.";
            }

            return response()->json([
                'status' => $status,
                'info' => $info,
            ]);

        } catch (\Exception $id) {
            return response()->json([
                'status' => false,
                'info' => "Data gagal dihapus.",
            ]);
        }
    }
}
