<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Barryvdh\Snappy\Facades\SnappyPdf as PDF;

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

class UserHomeController extends Controller
{
	public function __construct()
	{
		$this->middleware('auth');
	}

	/**
	 * Logged in users home page
	 *
	 * @return Factory|View
	 */
	public function home(User $o=NULL): View
	{
		if ($o)
			return View('u.home',['o'=>$o]);

		// If User was null, then test and see what type of logged on user we have
		$o = Auth::user();

		switch (Auth::user()->role()) {
			case 'customer':
				return View('u.home',['o'=>$o]);

			case 'reseller':
			case 'wholesaler':
				return View('r.home',['o'=>$o]);

			default:
				abort(500,'Unknown role: '.$o->role());
		}
	}

	/**
	 * Render a specific invoice for the user
	 *
	 * @param Invoice $o
	 * @return View
	 */
	public function invoice(Invoice $o): View
	{
		return View('u.invoice',['o'=>$o]);
	}

	/**
	 * Return the invoice in PDF format, ready to download
	 *
	 * @param Invoice $o
	 * @return mixed
	 */
	public function invoice_pdf(Invoice $o)
	{
		return PDF::loadView('u.invoice', ['o'=>$o])->stream(sprintf('%s.pdf',$o->invoice_account_id));
	}

	/**
	 * Helper to redirect to the old site, when functions are not available in this one.
	 *
	 * @param $type
	 * @param $action
	 * @param $id
	 * @return void
	 * @deprecated @todo Remove once all functions added
	 */
	public function oldsite($type,$action,$id)
	{
		abort(307,sprintf('http://www.graytech.net.au/u/%s/%s/%s',$type,$action,$id));
	}

	/**
	 * Return details on the users service
	 *
	 * @param Service $o
	 * @return View
	 */
	public function service(Service $o): View
	{
		return View('u.service',['o'=>$o]);
	}
}