<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Order;
use App\Models\Service;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
	public function create(Request $request) {
		$validated = $request->validate([
			'name' => 'required',
			'email' => 'required|email|unique:users,email',
			/* 'password' => 'required' */
			'password' => 'required|confirmed|min:8|regex:/[a-z]/|regex:/[A-Z]/|regex:/[0-9]/'
		]);

		$user = new User;
		$user->name = $request->name;
		$user->email = $request->email;
		$user->role = "client";
		$user->active = true;
		$user->password = Hash::make($request->password);
		$user->save();

		event(new Registered($user));
	}

	public function forgotPassword(Request $request) {
		$request->validate(['email' => 'required|email']);

		$status = Password::sendResetLink(
			$request->only('email')
		);
	}

	public function resetPassword(Request $request) {
		$request->validate([
		'token' => 'required',
		'email' => 'required|email',
		'password' => 'required|min:8|confirmed',
		]);

		$status = Password::reset(
		$request->only('email', 'password',
		'password_confirmation', 'token'),
		function ($user, $password) use ($request) {
			$user->forceFill([ 
				'password' => Hash::make($password) 
		])->setRememberToken(Str::random(60));
		});
		if ($status == Password::PASSWORD_RESET) {
			return response()->json([
				"status" => "success"
			]);
		}
	}

	public function login(Request $request) {
		$credentials = $request->only('email', 'password');

		//This should probably be changed to not return a page
		if (Auth::attempt($credentials)) {
			$request->session()->regenerate();
		} else {
			abort(401);
		}
	}

	public function logout(Request $request) {
		Auth::logout();
		$request->session()->invalidate();
		$request->session()->regenerateToken();
		return redirect('/');
	}

	//It should have an orderBy clause to make sure the most recent are first
	//This should limit non pending orders to 50. Should also return a json of all services
	public function getOrders(Request $request) {
		/* Log::debug(Auth::user()->orders()->service_name); */
		return Auth::user()->orders()->with('service')->withCasts(['updated_at'
			=> 'datetime:d-m-Y'])->get();

	}

}
