<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Bookings\Services\FetchesBooking;
use App\Classes\Modules\Bookings\Standards\Rules\CanFetchBooking;
use App\Classes\Modules\Bookings\Services\UpdatesBookingStatus;
use App\Classes\Modules\Transactions\Services\DeletesTransaction;
use App\Classes\Modules\Documents\Services\DeletesDocument;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionWithInvoiceNoProcessor;
use Illuminate\Support\Str;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Http\Resources\BookingResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Transaction;
use Illuminate\Support\Carbon;

class RegenerateInvoiceBookingLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification(): array
    {
        return [
            'title' => 'Regenerate Booking Invoice',
            'message' => 'You have successfully regenerate booking invoice'
        ];
    }

    /** @var CanFetchBooking */
    private $canFetchBooking;

    /** @var FetchesBooking */
    private $fetchesBooking;

    /** @var DeletesTransaction */
    private $deletesTransaction;

    /** @var UpdatesBookingStatus */
    private $updatesBookingStatus;

    /** @var DeletesDocument */
    private $deletesDocument;

    /** @var CreateInvoiceTransactionProcessor */
    private $createInvoiceTransactionProcessor;

    /** @var CreateInvoiceTransactionWithInvoiceNoProcessor */
    private $createInvoiceTransactionWithInvoiceNoProcessor;

    /**
     * FetchBookingLogic constructor.
     * @param CanFetchBooking $canFetchBooking
     * @param FetchesBooking $fetchesBooking
     * @param DeletesTransaction $deletesTransaction
     * @param UpdatesBookingStatus $updatesBookingStatus
     * @param DeletesDocument $deletesDocument
     * @param CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor
     * @param CreateInvoiceTransactionWithInvoiceNoProcessor $createInvoiceTransactionWithInvoiceNoProcessor
     */
    public function __construct(
        CanFetchBooking $canFetchBooking,
        FetchesBooking $fetchesBooking,
        DeletesTransaction $deletesTransaction,
        UpdatesBookingStatus $updatesBookingStatus,
        DeletesDocument $deletesDocument,
        CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor,
        CreateInvoiceTransactionWithInvoiceNoProcessor $createInvoiceTransactionWithInvoiceNoProcessor
    ) {
        $this->canFetchBooking = $canFetchBooking;
        $this->fetchesBooking = $fetchesBooking;
        $this->deletesTransaction = $deletesTransaction;
        $this->updatesBookingStatus = $updatesBookingStatus;
        $this->deletesDocument = $deletesDocument;
        $this->createInvoiceTransactionProcessor = $createInvoiceTransactionProcessor;
        $this->createInvoiceTransactionWithInvoiceNoProcessor = $createInvoiceTransactionWithInvoiceNoProcessor;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function logic(Request $request): JsonResponse
    {
        $this->canFetchBooking->passes();

        $booking = $this->fetchesBooking->execute(
            [
                'id' => $request->route('id'),
                'status' => ApprovalStatus::COMPLETED,
                'with_transactions' => true
            ]
        );

        $this->updatesBookingStatus->execute($booking, ApprovalStatus::APPROVED);

        $firstInvoice = $booking->transactions()
            ->whereIn('type', [TransactionType::INVOICE])
            ->withTrashed()
            ->orderBy('created_at', 'asc')
            ->first();

        // get the first bill_no
        $firstBillNo = $firstInvoice->bill_no;
        if (strpos($firstBillNo, '-deleted') !== false) {
            $firstBillNo = substr($firstBillNo, 0, strpos($firstBillNo, '-deleted'));
        }

        // update currentInvoice bill_no to '-deleted-'
        $currentInvoice = $booking->transactions()->where('type', TransactionType::INVOICE)->first();
        $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . (string)(Carbon::now()->timestamp);
        $currentInvoice->save();

        $transactionWithSameBillNo = Transaction::where('bill_no', $firstBillNo)->withTrashed()->get();
        if ($transactionWithSameBillNo) {
            foreach ($transactionWithSameBillNo as $transaction) {
                $transaction->bill_no = $transaction->bill_no . "-deleted-" . Str::random(10);
                $transaction->save();
            }
        }

        $transaction = $booking->transactions()->whereIn('type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->get();
        foreach ($transaction as $key => $row) {
            $this->deletesTransaction->execute($row);
        }

        $document = $booking->documents()->whereIn('document_type', [DocumentType::PURCHASE_ORDER, DocumentType::INVOICE, DocumentType::DELIVER_ORDER, DocumentType::SUPPLIER_DELIVER_ORDER])->get();
        foreach ($document as $key => $row) {
            $this->deletesDocument->execute($row);
        }

        $this->createInvoiceTransactionWithInvoiceNoProcessor->execute($booking, $firstBillNo);

        return $this->resourceResponse(new BookingResource($booking));
    }
}
