<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

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

class CheckoutController extends Controller
{
	/**
	 * Update a checkout details
	 *
	 * @param CheckoutAddEdit $request
	 * @param Checkout $o
	 * @return RedirectResponse
	 */
	public function addedit(CheckoutAddEdit $request,Checkout $o): RedirectResponse
	{
		foreach ($request->validated() as $key => $item)
			$o->{$key} = $item;

		$o->active = (bool)$request->validated('active',FALSE);

		try {
			$o->save();

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

		return $o->wasRecentlyCreated
			? redirect('a/checkout/'.$o->id)
				->with('success','Checkout added')
			: redirect()
				->back()
				->with('success','Checkout saved');
	}

	/**
	 * Add an invoice to the cart
	 *
	 * @param Request $request
	 * @param Invoice $o
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application
	 * @note The route validates that the user can see the invoice
	 */
	public function cart_invoice(Request $request,Invoice $o)
	{
		$request->session()->put('invoice.cart.'.$o->id,$o->id);

		return view('theme.backend.adminlte.checkout.cart');
	}

	/**
	 * Remove an item from the cart
	 *
	 * @param Request $request
	 * @return string
	 */
	public function cart_remove(Request $request): string
	{
		if ($id=$request->post('id')) {
			$cart = $request->session()->pull('invoice.cart');
			unset($cart[$id]);

			$request->session()->put('invoice.cart',$cart);
		}

		return '';
	}

	public function fee(Request $request): float
	{
		if ((! $request->post('checkout_id') || (! $request->post('total'))))
			return 0;

		$co = Checkout::findOrFail($request->post('checkout_id'));

		return $co->fee($request->post('total'));
	}

	public function pay()
	{
		// @todo Currently sending all payments to paypal
		return redirect()
			->action([PaypalController::class,'authorise']);
	}
}