<?php

namespace App\Http\Controllers\Main;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    public function save(Request $request)
    {

        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'surname' => ['required', 'string', 'max:255'],
            'day' => ['required', 'integer'],
            'month' => ['required', 'string'],
            'year' => ['required', 'integer'],
            'country_id' => ['required', 'integer'],
            'city_id' => ['required', 'integer'],
            'skill' => ['required', 'string'],
            'about' => ['required', 'string'],
        ]);


        $data = $request->all();
        unset($data["_token"]);

        $user = Auth::user();

        foreach ($data as $key => $item) {
            if (
                $user->$key != $item &&
                !in_array($key, ['password', 'password_confirmation', 'day', 'month', 'year', 'username', 'email', 'avatar'])
            ) {
                $user->$key = $item;
            } elseif ($key == "password") {
                if ($item !== "no-change-password") {
                    $request->validate([
                        'password' => ['required', 'string', 'min:8', 'confirmed'],
                    ]);
                    $user->$key = Hash::make($item);
                }
            } elseif ($key == "day") {
                $user->dob = $data['day'] . " " . $data['month'] . " " . $data['year'];
            } elseif ($key == "username") {
                if ($item != $user->username) {
                    $request->validate([
                        'username' => ['required', 'string', 'max:255', 'unique:users'],
                    ]);
                    $user->$key = $item;
                }
            } elseif ($key == "email") {
                if ($item != $user->email) {
                    $request->validate([
                        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                    ]);
                    $user->$key = $item;
                }
            } elseif ($key == 'avatar') {
                $request->validate([
                    'avatar' => 'mimes:jpeg,png|max:2024'
                ]);
                $path = $request->avatar->store('avatars', 'public');
                $user->avatar_url = '/storage/' . $path;
            }
        }

        $user->save();

        return redirect()->back()->with('success', 'Изменения сохранены');

    }
}
