<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Order;
use App\Models\Service;
use App\Mail\ChangeEmail;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\URL;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Auth;
use Illuminate\Notifications\Messages\MailMessage;
use Mail;

use Stripe\Stripe;
use Stripe\Customer;

class UserController extends Controller
{
	public function create(Request $request) {
		$validated = $request->validate([
			'name' => 'required|max:30',
			'email' => 'required|email|unique:users|max:255',
			'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();

		Auth::login($user);
		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();
			$this->clearPaying();
		} 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) {
		return Auth::user()->orders()->with('service')->withCasts(['updated_at'
			=> 'datetime:d-m-Y'])->latest()->limit(100)->get();
	}

	public function changeName(Request $request) {
		$validated = $request->validate([
			'name' => 'required|max:30'
		]);
		$user = Auth::user();
		$user->name = $request->name;
		$user->save();
		return $user;
	}

	public function changeEmail(Request $request) {
		$validated = $request->validate([
			'email' => 'required|email|unique:users,email',
		]);

		$link = URL::temporarySignedRoute('reset-email', now()->addDays(30),
		['user' => Auth::user()->id, 'email' => $request->email]);

		Mail::to($request->email)->send(new ChangeEmail(Auth::user()->email,
			$link));


	}

	public function resetEmail(Request $request) {

		if (! $request->hasValidSignature()) {
			abort(401);
		}

		$validated = $request->validate([
			'email' => 'required|email|unique:users,email',
		]);

		if (! $validated) {
			abort(401);
		}

		$user = User::find($request->user);
		$user->email = $request->email;
		$user->save();

		return view('email-changed');
	}

	public function changePassword(Request $request) {
		$validated = $request->validate([
			'current_password' => 'password',
			'password' => 'required|confirmed|min:8|regex:/.*[a-z].*/|regex:/.*[A-Z].*/|regex:/.*[0-9].*/'
		]);

		$user = Auth::user();
		$user->password = Hash::make($request->password);
		$user->save();
	}

	public function clearPaying() {
		$user = Auth::user();
		if ($user->paying) {
			$user->paying = false;
			$user->save();
		}
	}

}
