<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Arr;

use App\Http\Requests\PaymentAddEdit;
use App\Models\{Payment,PaymentItem};

class PaymentController extends Controller
{
	/**
	 * Record payments on an account.
	 *
	 * @param PaymentAddEdit $request
	 * @param Payment $o
	 * @return RedirectResponse
	 */
	public function addedit(PaymentAddEdit $request,Payment $o): RedirectResponse
	{
		foreach (Arr::except($request->validated(),'invoices') as $k=>$v)
			$o->{$k} = $v;

		foreach ($request->validated('invoices',[]) as $id => $amount) {
			// See if we already have a payment item that we need to update
			$items = $o->items
				->filter(fn($item)=>$item->invoice_id == $id);

			if ($items->count() === 1) {
				$oo = $items->pop();

				if ($amount == 0) {
					$oo->delete();
					continue;
				}

			} else {
				$oo = new PaymentItem;
				$oo->invoice_id = $id;
			}

			$oo->amount = ($oo->invoice->due >= 0) && ($oo->invoice->due-$amount >= 0)
				? $amount
				: 0;

			// If the amount is empty, ignore it.
			if (! $oo->amount)
				continue;

			$oo->site_id = config('site')->site_id;
			$oo->active = TRUE;
			$o->items->push($oo);
		}

		try {
			$o->pushNew();

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

		return $o->wasRecentlyCreated
			? redirect('r/payment/'.$o->id)
				->with('success','Payment added')
			: redirect()
				->back()
				->with('success','Payment saved');
	}
}