<?php

namespace Modules\Agents\Http\Controllers;

use App\Models\UserPermission;
use App\Models\UserPermissionStaff;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Session;


use App\Models\User;
use Illuminate\Support\Facades\Auth;

class Main extends Controller
{
    /**
     * Provide class.
     */
    private $provider = User::class;

    /**
     * Web RoutePath for the name of the routes.
     */
    private $webroute_path = 'agent.';

    /**
     * View path.
     */
    private $view_path = 'agents::';

    /**
     * Parameter name.
     */
    private $parameter_name = 'agent';

    /**
     * Title of this crud.
     */
    private $title = 'consultor';

    /**
     * Title of this crud in plural.
     */
    private $titlePlural = 'Agents';

    /**
     * Auth checker functin for the crud.
     */
    private function authChecker()
    {
        if (!auth()->user()->hasRole('owner')) {
            abort(403, 'Unauthorized action.');
        }
    }

    private function getFields()
    {
        return [
            ['class' => 'col-md-4', 'ftype' => 'input', 'name' => 'Name', 'id' => 'name', 'placeholder' => 'First and Last name', 'required' => true],
            ['class' => 'col-md-4', 'ftype' => 'input', 'name' => 'Email', 'id' => 'email', 'placeholder' => 'Enter email', 'required' => true],
            ['class' => 'col-md-4', 'ftype' => 'input', 'type' => "password", 'name' => 'Password', 'id' => 'password', 'placeholder' => 'Enter password', 'required' => true],
            [
                'class' => 'col-md-4',
                'ftype' => 'textarea',
                'name' => 'Descripción',
                'id' => 'descripcion',
                'placeholder' => 'Escribe una pequeña descripcion de lo que se encarga (máximo: 72 caracteres)',
                'required' => true
            ],
            [
                'class' => 'col-md-4',
                'ftype' => 'select',
                'name' => 'Permiso',
                'id' => 'permiso',
                'required' => true,
                'data' => [
                    'Ver nombre y celular',
                    'Ver solo nombre',
                    'Ver solo celular',
                    'No ver ninguno'
                ]
            ],
            [
                'class' => 'col-md-4',
                'ftype' => 'select',
                'name' => 'Estatus del consultor',
                'id' => 'status_consultor',
                'required' => true,
                'data' => [
                    'Disponible',
                    'No disponible'
                ]
            ],
        ];
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->authChecker();
        $fields = $this->getFields();
        unset($fields[2]);
        unset($fields[3]);
        unset($fields[4]);
        unset($fields[5]);
        $items = User::join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
            ->where('model_has_roles.role_id', 4)
            ->select('users.*') // Selecciona todas las columnas de la tabla de usuarios
            ->paginate(config('settings.paginate'));
        if(count(User::where('id', '!=', 1)->get()) < 10){
            $setup = [
                'title' => __('crud.item_managment', ['item' => __($this->titlePlural)]),
                'action_link' => route($this->webroute_path . 'create'),
                'action_name' => __('crud.add_new_item', ['item' => __($this->title)]),
                'items' => $items,
                'item_names' => $this->titlePlural,
                'webroute_path' => $this->webroute_path,
                'fields' => $fields,
                'parameter_name' => $this->parameter_name,
            ];
        }else{
            $setup = [
                'title' => __('crud.item_managment', ['item' => __($this->titlePlural)]),
                // 'action_link' => route($this->webroute_path . 'create'),
                // 'action_name' => __('crud.add_new_item', ['item' => __($this->title)]),
                'items' => $items,
                'item_names' => $this->titlePlural,
                'webroute_path' => $this->webroute_path,
                'fields' => $fields,
                'parameter_name' => $this->parameter_name,
            ];

        }
        return view('agents::index', [
            'setup' => $setup
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authChecker();

        return view('general.form', [
            'setup' => [
                'inrow' => true,
                'title' => __('crud.new_item', ['item' => __($this->title)]),
                'action_link' => route($this->webroute_path . 'index'),
                'action_name' => __('crud.back'),
                'iscontent' => true,
                'action' => route($this->webroute_path . 'store'),
            ],
            'fields' => $this->getFields(),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $this->authChecker();
        $existingUser = User::where('email', $request->email)->first();
        $cantidadUsers = count(User::where('id', '!=', 1)->get());

        if ($existingUser) {
            return redirect()->back()->withErrors(['email' => 'El correo electrónico ya está en uso.'])->withInput();
        }
        if ($cantidadUsers > 10) {
            return redirect()->back()->withErrors(['El maximo de usuarios permitidos es 10'])->withInput();
        }

        // if(!$request->password){
        //     return redirect()->route($this->webroute_path . 'create')->withErrors(['group_error' => 'La contraseña es obligatoria']);
        // }
        $item = $this->provider::create([
            'name' => $request->name,
            'email' => $request->email,
            'descripcion' => $request->descripcion,
            // 'password' => $request->password,
            'password' => Hash::make($request->password),
            'api_token' => Str::random(80),
            'company_id' => 1,
        ]);
        $userPermission = null;
        if ($request->permiso) {
            $userPermission = UserPermissionStaff::create([
                'user_id' => $item->id,
                'permiso' => $request->permiso,
                'created_at' => now(),
                'update_at' => now(),
            ]);
        } else {
            $userPermission = UserPermissionStaff::create([
                'user_id' => $item->id,
                'permiso' => 0,
                'created_at' => now(),
                'update_at' => now(),
            ]);
        }
        if ($request->status_consultor) {
            $userPermission->status = $request->status_consultor;
            $userPermission->save();
        }
        $item->save();

        $item->assignRole('staff');

        return redirect()->route($this->webroute_path . 'index')->withStatus(__('crud.item_has_been_added', ['item' => __($this->title)]));
    }


    public function loginas($id)
    {
        $this->authChecker();
        if (config('settings.is_demo', false)) {
            return redirect()->back()->withStatus('Not allowed in demo');
        }

        $agent = User::findOrFail($id);
        // if ($agent->company->user->id!=auth()->user()->id) {
        //     abort(403, 'Unauthorized action.');
        // }

        Auth::login($agent, true);

        //Set the company
        Session::put('company_id', $agent->company->id);

        //Login as owner
        Session::put('impersonate', $agent->id);

        return redirect(route('home'));


    }

    /**
     * Show the form for editing the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->authChecker();

        $item = $this->provider::findOrFail($id);
        if (!$this->getCompany()->id == $item->company_id) {
            abort(403, 'Unauthorized action.');
        }

        $fields = $this->getFields();
        foreach ($fields as &$field) {
            if ($field['id'] === 'password') {
                $field['required'] = false;
            }
        }
        $fields[0]['value'] = $item->name;
        $fields[1]['value'] = $item->email;
        $fields[3]['value'] = $item->descripcion;
        $userPermission = UserPermissionStaff::where('user_id', $item->id)->first();
        if ($userPermission) {
            $fields[4]['value'] = $userPermission->permiso;
            $fields[5]['value'] = $userPermission->status;
        }

        $parameter = [];
        $parameter[$this->parameter_name] = $id;

        return view('general.form', [
            'setup' => [
                'inrow' => true,
                'title' => __('crud.edit_item_name', ['item' => __($this->title), 'name' => $item->name]),
                'action_link' => route($this->webroute_path . 'index'),
                'action_name' => __('crud.back'),
                'iscontent' => true,
                'isupdate' => true,
                'action' => route($this->webroute_path . 'update', $parameter),
            ],
            'fields' => $fields,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->authChecker();

        $existingUser = User::where('email', $request->email)
                        ->where('id','!=',$id)
                        ->first();

        if ($existingUser) {
            return redirect()->back()->withErrors(['group_error' => 'El correo electrónico ya está en uso.'])->withInput();
        }

        $item = $this->provider::findOrFail($id);

        $item->name = $request->name;

        $item->email = $request->email;

        $item->descripcion = $request->descripcion;

        if ($request->password && strlen($request->password) > 2) {

            $item->password = Hash::make($request->password);

        }
        $item->update();

        $UserPermissionStaff = UserPermissionStaff::where('user_id', $item->id)->first();

        if ($UserPermissionStaff) {

            if (!$request->permiso) {

                $UserPermissionStaff->permiso = 0;

                $UserPermissionStaff->save();

            } else {

                $UserPermissionStaff->permiso = $request->permiso;

                $UserPermissionStaff->save();
            }
        } else {
            if ($request->permiso) {

                $UserPermissionStaff = UserPermissionStaff::create([
                    'user_id' => $item->id,
                    'permiso' => $request->permiso,
                    'created_at' => now(),
                    'update_at' => now(),
                ]);

            } else {

                $UserPermissionStaff = UserPermissionStaff::create([
                    'user_id' => $item->id,
                    'permiso' => 0,
                    'created_at' => now(),
                    'update_at' => now(),
                ]);
            }
        }
        if (isset($request->status_consultor)) {
            $UserPermissionStaff->status = $request->status_consultor;
            $UserPermissionStaff->save();
        }

        return redirect()->route($this->webroute_path . 'index')->withStatus(__('crud.item_has_been_updated', ['item' => __($this->title)]));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->authChecker();
        $item = $this->provider::findOrFail($id);
        $item->delete();
        return redirect()->route($this->webroute_path . 'index')->withStatus(__('crud.item_has_been_removed', ['item' => __($this->title)]));
    }
}


