<?php

namespace App\Http\Controllers;

use Clarkeash\Doorman\Exceptions\{DoormanException,ExpiredInviteCode};
use Clarkeash\Doorman\Facades\Doorman;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;

use App\Models\{Invoice,Service,User};

/**
 * Class HomeController
 * This controller is the logged in users home page
 *
 * The methods to this controller should be projected by the route
 *
 * @package App\Http\Controllers
 */
class HomeController extends Controller
{
	/**
	 * Logged in users home page
	 *
	 * @param User $o
	 * @return View
	 */
	public function home(User $o): View
	{
		if (! $o->exists)
			$o = Auth::user();

		return view('theme.backend.adminlte.home')
			->with(['o'=>$o]);
	}

	/**
	 * Enable the user to down an invoice by providing a link in email
	 *
	 * @param Invoice $o
	 * @param string  $code
	 * @return \Illuminate\Http\RedirectResponse|mixed
	 */
	public function invoice_pdf_email(Invoice $o,string $code)
	{
		try {
			Doorman::redeem($code,$o->account->user->email);

		} catch (ExpiredInviteCode $e) {
			Log::alert(sprintf('User is using an expired token for invoice [%s] using [%s]',$o->id,$code));

			return redirect('login');

		} catch (DoormanException $e) {
			Log::alert(sprintf('An attempt to read invoice id [%s] using [%s]',$o->id,$code));

			abort(404);
		}

		return $this->invoice($o);
	}

	/**
	 * Progress the order to the next stage
	 *
	 * @note: Route Middleware protects this path
	 * @param Service $o
	 * @param string  $status
	 * @return \Illuminate\Http\RedirectResponse
	 * @deprecated
	 */
	public function service_progress(Service $o,string $status)
	{
		return redirect($o->action($status) ?: url('u/service',$o->id));
	}
}