<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\View\View;

use App\Http\Requests\CheckoutAddEdit;
use App\Models\{Checkout,Invoice};

class CheckoutController extends Controller
{
	/**
	 * Update a suppliers details
	 *
	 * @param CheckoutAddEdit $request
	 * @param Checkout $o
	 * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse
	 */
	public function addedit(CheckoutAddEdit $request,Checkout $o)
	{
		$this->middleware(['auth','wholesaler']);

		foreach ($request->except(['_token','active','submit']) as $key => $item)
			$o->{$key} = $item;

		$o->active = (bool)$request->active;

		try {
			$o->save();

		} catch (\Exception $e) {
			return redirect()->back()->withErrors($e->getMessage())->withInput();
		}

		return redirect()
			->back()
			->with('success','Payment saved');
	}

	public function cart_invoice(Request $request,Invoice $o=NULL)
	{
		if ($o) {
			$request->session()->put('invoice.cart.'.$o->id,$o->id);
		}

		if (! $request->session()->get('invoice.cart'))
			return redirect()
				->to('u/home');

		return view('theme.backend.adminlte.u.invoice.cart')
			->with('invoices',Invoice::find(array_values($request->session()->get('invoice.cart'))));
	}

	public function fee(Request $request,Checkout $o): float
	{
		return $o->fee($request->post('total',0));
	}

	/**
	 * Render a specific invoice for the user
	 *
	 * @return View
	 */
	public function home(): View
	{
		return view('theme.backend.adminlte.payment.home');
	}

	public function pay(Request $request,Checkout $o)
	{
		return redirect('pay/paypal/authorise');
	}

	/**
	 * View details on a specific payment method
	 *
	 * @param Checkout $o
	 * @return View
	 */
	public function view(Checkout $o): View
	{
		return view('theme.backend.adminlte.payment.view',['o'=>$o]);
	}
}