<?php

namespace App\Http\Controllers;

use App\Http\Requests\ChargeAdd;
use App\Models\Charge;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;

class ChargeController extends Controller
{
	/**
	 * Add a charge to a service/account
	 *
	 * @param ChargeAdd $request
	 * @return RedirectResponse
	 */
	public function addedit(ChargeAdd $request): RedirectResponse
	{
		$o = Charge::findOrNew(Arr::get($request->validated(),'id'));

		// Dont update processed charges
		if ($o->processed)
			abort(403);

		$o->forceFill(array_merge(Arr::except($request->validated(),['id']),['active'=>TRUE]));
		$o->save();

		return redirect()
			->back()
			->with('success',sprintf('Charge %s #%d',$o->wasRecentlyCreated ? 'Created' : 'Updated',$o->id));
	}

	public function delete(Charge $o): array
	{
		if (Gate::allows('delete',$o)) {
			$o->active = FALSE;
			$o->save();

			return ['ok'];

		} else {
			abort(401,'Not Allowed');
		}
	}

	/**
	 * Add a charge to a service/account
	 *
	 * @param Request $request
	 * @return View
	 */
	public function edit(Request $request): View
	{
		$o = Charge::where('processed',FALSE)
			->where('id',$request->id)
			->firstOrFail();

		if (Gate::allows('update',$o)) {
			return view('theme.backend.adminlte.charge.widget.addedit')
				->with('o',$o)
				->with('so',$o->service);
		}

		abort(403);
	}
}