<?php

namespace App\Http\Controllers;

use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class ProfileController extends Controller {

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response or void
     */
    public function show(User $user) {
        if ($user->id === Auth::user()->id) {
            $roles = Role::all();

            $role = null;

            foreach ($roles as $currentRole) {
                if ($user->hasRole($currentRole->name)) {
                    $role = $currentRole;
                    break;
                }
            }

            return view('profiles.show', compact('user', 'role'));
        } else {
            abort(401);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response or void
     */
    public function edit(User $user) {
        if ($user->id === Auth::user()->id) {
            return view('profiles.edit', compact('user'));
        } else {
            abort(401);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response or void
     */
    public function update(Request $request, User $user) {
        if ($user->id === Auth::user()->id) {
            $input = $request->validate([
                'email' => 'required|string|email|max:255|unique:users,email,'
                . $user->id,
                'password' => 'nullable|string|min:8|confirmed',
                'image' => 'nullable|image|mimes:jpeg,jpg,gif,png,svg,webp|max:2048'
            ]);

            if ($input['password']) {
                $input['password'] = bcrypt($input['password']);
            } else {
                unset($input['password']);
            }

            if ($request->file('image')) {
                $image = $request->file('image');
                $imageDestinationPath = 'data/images/users/';
                $userImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
                $image->move($imageDestinationPath, $userImage);
                $input['image'] = '/' . $imageDestinationPath . $userImage;
            } else {
                unset($input['image']);
            }

            $user->update($input);

            return redirect()->route('profiles.show', $user->id)
                            ->with('success', 'Profile modified successfully.');
        } else {
            abort(401);
        }
    }

}
