<?php

namespace App\Domains\Event\Controllers;

use App\Domains\Event\Actions\ParticipantPayment\ParticipantPaymentCommand;
use App\Domains\Event\Actions\ParticipantPayment\ParticipantPaymentRequest;
use App\Scopes\CommonController;
use App\ValueObjects\Amount;
use Illuminate\Http\Request;

class ParticipantPaymentController extends CommonController
{
    public function paymentComplete(string $participantIdentifier, Request $request) {
        $participant = $this->eventParticipants->getByIdentifier($participantIdentifier, $this->events);

        $paymentRequest = new ParticipantPaymentRequest($participant, $participant->amount);

        $paymentCommand = new ParticipantPaymentCommand($paymentRequest);
        $paymentResponse = $paymentCommand->execute();

        return response()->json([
            'status' => $paymentResponse->success ? 'success' : 'error',
            'message' => $paymentResponse->success ? 'Die Zahlung wurde erfolgreich gebucht.' : 'Beim Buchen der Zahlung ist ein Fehler aufgetreten.'
        ]);
    }

    public function partialPaymentComplete(string $participantIdentifier, Request $request) {
        $participant = $this->eventParticipants->getByIdentifier($participantIdentifier, $this->events);

        $paymentRequest = new ParticipantPaymentRequest($participant, Amount::fromString($request->input('amount')));

        $paymentCommand = new ParticipantPaymentCommand($paymentRequest);
        $paymentResponse = $paymentCommand->execute();


        $amountLeft = clone($paymentResponse->amountExpected);
        $amountLeft->subtractAmount($paymentResponse->amountPaid);

        return response()->json([
            'status' => $paymentResponse->success ? 'success' : 'error',
            'message' => $paymentResponse->success ? 'Die Zahlung wurde erfolgreich gebucht.' : 'Beim Buchen der Zahlung ist ein Fehler aufgetreten.',
            'identifier' => $participant->identifier,
            'amount' => [
                'paid' => $paymentResponse->amountPaid->toString(),
                'expected' => $paymentResponse->amountExpected->toString(),
                'actions' => $amountLeft->getAmount() != 0 ? 'inline' : 'none',
                'class' => $amountLeft->getAmount() != 0 ? 'not-paid' : 'paid',
            ]
        ]);
    }
}
