<?php

namespace App\Http\Controllers;

use App\Http\Requests\User\DeleteUser;
use App\Http\Requests\User\StoreProfile;
use App\Http\Requests\User\StoreUser;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    protected array $data = [
        'active' => 'users',
        'title'  => 'Пользователи',
        'id'        => 'users',
        'header'    => [
            'id'            => 'ID',
            'email'         => 'E-mail',
            'name'          => 'ФИО',
            'phone'         => 'Телефон',
            'role'          => 'Роль',
            'created_at'    => 'Дата создания'
        ],
        'searchFields' => [
            'name',
            'phone',
            'email',
        ],
        'ranges' => [],
        'filters' => [],
    ];


    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $model = new User;
        $this->createFilters($model, 'role');
        $this->createDateFilters($model, 'created_at');

        $q = $model::query();
        $this->acceptFilters($q, $request);
        $this->acceptSearch($q, $request);
        $this->setSortAndOrderBy($model, $request);

        $q->orderBy($this->data['sortBy'], $this->data['orderBy']);
        $this->data['users'] = $q->paginate(session('per_page', config('pagination.per_page')))->withQueryString();

        return view('users.index', $this->data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $this->data['user'] = null;
        return view('users.edit', $this->data);
    }

    /**
     * Store a newly or update existing created resource in storage.
     */
    public function store(StoreUser $request)
    {
        $validated = $request->validated();

        if(!empty($validated['password'])) {
            $validated['password'] = Hash::make($validated['password']);
        } else {
            unset($validated['password']);
        }

        if(isset($validated['id'])) {
            User::query()
                ->where('id', $validated['id'])
                ->update($validated);
        } else {
            User::query()->create($validated);
        }
        return redirect()->route('user.index')->with(['success' => 'Пользователь ' . $validated['name'] . ' сохранён!']);
    }

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        $this->data['user'] = $user;
        return view('users.edit', $this->data);
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy(User $user, DeleteUser $request)
    {
        if($user == $request->user()) {
            return redirect()->route('user.index')->with(['danger' => 'Нельзя удалить самого себя!']);
        } else {
            $user->delete();
            return redirect()->route('user.index')->with(['success' => 'Пользователь ' . $user->name . ' удалён!']);
        }
    }

    public function profile(Request $request)
    {
        $this->data['current_menu'] = 'profile';
        $this->data['user'] = $request->user();
        return view('users.profile', $this->data);
    }

    public function storeProfile(StoreProfile $request)
    {
        $data = $request->validated();

        unset($data['current_password'], $data['password']);
        if(
            isset($request->current_password)
            && isset($request->password)
            && (Hash::check($request->current_password, $request->user()->password))) {
            $data['password'] = Hash::make($request->password);
        }

        User::query()->where('id', '=', $request->user()->id)->update($data);

        return redirect()->route('user.profile')->with(['success' => 'Профиль обновлён!']);
    }


}
