<?php

namespace App\Http\Controllers\Management;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\UserInstansi;
use App\Models\Master\Group;

class UserController extends Controller
{
    protected $title = 'User';
    protected $template = 'modules.management.user';
    protected $route = 'modules.management.user';

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        permission('is_read', $this->route, 'module',true);
        
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Management & Akses Role'],
            ['name' => 'Data User','active' => true],
        ];
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        return view($this->template.'.index',$data);
    }

    public function grid(Request $request)
    {

        $data = User::with(['group'])->where('ms_group_id','!=',1)->where('id','!=',auth()->user()->id)->orderBy('id','DESC')->get();
        // $data = User::with(['group'])->orderBy('id','DESC')->get();
        $_data = [];


        foreach ($data as $key => $row) {


            $action = '';

            $instansi = UserInstansi::where('user_id',$row->id)->first();

            if((permission('is_create', $this->route.'.*','module',false)) || (permission('is_update', $this->route.'.*','module',false))){
                $action .= '<div class="flex gap-1 justify-center items-center">';
                $action .= '<a href="'.url('management/user/update/'.encode_id($row->id)).'" data-toggle="tooltip" title="Edit Data" class="p-2 w-full rounded text-white bg-blue-500"><i class="ri-pencil-line text-white"></i></a>';
                if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
                    $action .= '<a href="#" data-href="'.url('management/user/forcelogin/'.encode_id($row->id)).'" data-toggle="tooltip" title="Force Login" class="forcelogin p-2 w-full rounded text-white bg-emerald-500"><i class="ri-user-line text-white"></i></a>';
                    $action .= '<a href="#" data-href="'.url('management/user/delete/'.encode_id($row->id)).'" data-toggle="tooltip" title="Hapus Data" class="remove_data p-2 w-full rounded text-white bg-red-500"><i class="ri-delete-bin-line text-white"></i></a>';
                }
                $action .= '</div>';
            }
            $role = '';
            $role .= '<div class="flex flex-col items-start gap-1 text-xs">';
                $role .= '<span class="bg-blue-500 text-white p-1 rounded">Role & Hak Akses : '.@$row->group->name.'</span>';
                $role .= '<span class=" '.(@$instansi->instansi ? 'bg-success' : 'bg-danger').' text-white p-1 rounded">Instansi : '.@$instansi->instansi->name.'</span>';
            $role .= '</div>';
            
           $_data[] = [
            'no'                => $key+1,
            'id'                => encode_id($row->id),
            'name'              => @$row->name,
            'role'              => @$role,
            'username'          => @$row->username,
            'instansi'          => @$instansi->instansi->name,
            'email'             => @$row->email,
            'created_at'        => dateTime(@$row->created_at),
            'action'            => @$action,
        ];

        }

        // return response()->json($_data);  // Return the data as a JSON response
        return response()->json($_data);

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {

            // dd($request->all());

            $keyId = decode_id($request->secure_id);

            if(@$keyId){
                Validator::make($request->all(), [
                    'email'           => 'required|unique:users,email,'.$keyId.'|email',
                    'name'            => 'required|max:255',
                    'group'           => 'required',
                    'ms_instansi_id'  => 'required',
                    'username'        => 'required|unique:users,username,'.$keyId,
                    'password'        => 'nullable|min:5|max:15|regex:/[a-z]/|regex:/[A-Z]/|regex:/[0-9]/|regex:/[@$!%*#?&]/', //min 8 char, maks 15 char, min 1 symbol, min 1 uppercase, min 1 lowercase, 1 number
                ],[
                    'password.max' => 'password Maksimal 15 Karakter',
                    'password.regex' => 'Format Kata Sandi harus mengandung minimal Huruf Besar, Huruf Kecil, Angka, Spesial Karakter',
                ])->validate();

                $user = User::find($keyId);
                $user->email = $request->email;
                $user->username = $request->username;
                $user->ms_group_id = decode_id($request->group);
                if(@$request->password){
                    $user->password = Hash::make($request->password);
                }
                $user->name     = $request->name;
                $user->save();

                // dd(decode_id($request->ms_instansi_id));

                UserInstansi::updateOrCreate([
                    'user_id' => $user->id,
                ],[
                    'user_id' => $user->id,
                    'ms_instansi_id' => decode_id($request->ms_instansi_id),
                ]);

            }else{
                Validator::make($request->all(), [
                    'email'           => 'required|unique:users,email|email',
                    'name'            => 'required|max:255',
                    'group'           => 'required',
                    'ms_instansi_id'  => 'required',
                    'username'        => 'required|unique:users,username',
                    'password'        => 'required|min:5|max:15|regex:/[a-z]/|regex:/[A-Z]/|regex:/[0-9]/|regex:/[@$!%*#?&]/', //min 8 char, maks 15 char, min 1 symbol, min 1 uppercase, min 1 lowercase, 1 number
                ],[
                    'password.min' => 'password Minimal 5 Karakter',
                    'password.max' => 'password Maksimal 15 Karakter',
                    'password.regex' => 'Format Kata Sandi harus mengandung minimal Huruf Besar, Huruf Kecil, Angka, Spesial Karakter',
                ])->validate();

                $user = new User;
                $user->email = $request->email;
                $user->username = $request->username;
                $user->ms_group_id = decode_id($request->group);
                if(@$request->password){
                    $user->password = Hash::make($request->password);
                }
                $user->name     = $request->name;
                $user->save();

                UserInstansi::updateOrCreate([
                    'user_id' => $user->id,
                ],[
                    'user_id' => $user->id,
                    'ms_instansi_id' => decode_id($request->ms_instansi_id),
                ]);
            }

            return redirect()->back()->with([
                'message' => 'Berhasil update data',
                'type'    => 'success',
            ]);
            
        } catch (Exception $e) {
            return redirect()->back()->with([
                     'message' => $e->getMessage(),
                     'type'    => "error"
                ]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update($id = null)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Management & Akses Role'],
            ['name' => 'Data User','active' => true],
        ];
        $keyId = decode_id($id);
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        $data['keyId'] = $id;
        $data['item'] = User::where('id',$keyId)->first();
        $data['userInstansi'] = UserInstansi::where('user_id',$keyId)->first();
        $data['group'] = Group::where('MsGroupId','!=',1)->get();
        return view($this->template.'.form',$data);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function delete($id)
    {
        $keyId = decode_id($id);

        $user = User::where('id',$keyId)->delete();

        return response()->json(['success' => true,'message' => 'Berhasil update data','type' => 'success']);
    }

    public function forcelogin($id = null)
    {

        //dd($id);
    
        if (!$id) {
            return response()->json(['success' => false,'message' => 'Data Tidak Temukan','type' => 'error']);
        }

        $id = decode_id($id);
        $user = User::find($id);
        if (!$user) {
            return response()->json(['success' => false,'message' => 'Data Tidak Temukan','type' => 'error']);
        } else {

            if ($user->username && $user->password) {
                if (Auth::loginUsingId($id)) {
                    $session = [
                        'username'                  => $user->username,
                        'name'                      => $user->name,
                        'email'                     => $user->email,
                        'currYear'                  => date('Y'),
                        'group_id'                  => @$user->ms_group_id,
                        'instansi_id'               => @UserInstansi::where('user_id',$user->id)->value('ms_instansi_id'),
                        'resource_data'             => @UserInstansi::where('user_id',$user->id)->value('resource_data'),
                        'group_alias'               => @$user->group->alias,
                        'group_name'                => @$user->group->name,
                    ];
                    session($session);

                    return response()->json(['status' => true,'message' => 'Selamat datang kembali','type' => 'success']);
                }
                else {

                    return response()->json(['status' => false,'message' => 'Maaf Terjadi Kesalahan','type' => 'error']);
                }
            } else {
                return response()->json(['status' => false,'message' => 'Maaf Terjadi Kesalahan','type' => 'error']);
            }
        }
    }
}
