<?php

namespace App\Classes\Jobs\Commands\V2;

use App\Classes\Modules\KeyValuePairs\DataTransferObjects\KeyValuePairObject;
use App\Classes\Modules\KeyValuePairs\Services\CreatesKeyValuePair;
use App\Classes\Modules\KeyValuePairs\Services\UpdatesKeyValuePair;
use App\Classes\Modules\Bookings\Processors\RegenerateInvoiceBookingProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\KVPKey;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Booking;
use App\Models\Transaction;
use Illuminate\Support\Facades\Log;


class ProcessCreditNoteReportV2CommandJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** @var array */
    private $details;

    /**
     * ProcessCreditNoteReportV2CommandJob constructor.
     * @param array $details
     */
    public function __construct(array $details)
    {
        $this->details = $details;
    }

    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Processing single record for E-Invoice from Credit Note Report Import.');
        $start   = new Carbon();

        $docNo                  = $this->details['docno'] ?? null;
        $docDate                = $this->details['docdate'] ?? null;
        $debtorCode             = $this->details['debtorcode'] ?? null;
        $ref                    = $this->details['ref'] ?? null;
        $description            = $this->details['description'] ?? null;
        $reason                 = $this->details['reason'] ?? null;
        $deptNo                 = $this->details['deptno'] ?? null;
        $qty                    = $this->details['qty'] ?? null;
        $unitPrice              = $this->details['unitprice'] ?? null;
        $accNo                  = $this->details['accno'] ?? null;
        $submitEinvoice         = $this->details['submiteinvoice'] ?? null;
        $einvoiceIssueDateTime  = $this->details['einvoiceissuedatetime'] ?? null;
        $consolidatedEinvoice   = $this->details['consolidatedeinvoice'] ?? null;
        $eInvoiceValidationLink = $this->details['einvoicevalidationlink'] ?? null;

        Log::info("Processing Credit Note Report:", [
            'DocNo'                  => $docNo,
            'DocDate'                => $docDate,
            'DebtorCode'             => $debtorCode,
            'Ref'                    => $ref,
            'Description'            => $description,
            'Reason'                 => $reason,
            'DeptNo'                 => $deptNo,
            'Qty'                    => $qty,
            'UnitPrice'              => $unitPrice,
            'AccNo'                  => $accNo,
            'SubmitEinvoice'         => $submitEinvoice,
            'EInvoiceIssueDateTime'  => $einvoiceIssueDateTime,
            'ConsolidatedEinvoice'   => $consolidatedEinvoice,
            'EInvoiceValidationLink' => $eInvoiceValidationLink,
        ]);



        $transaction = Transaction::where('bill_no', $ref)->first();
        if($transaction){
            if($docNo != "" && $docNo != "<<New>>"){
                $this->updateOrCreateKeyValuePair($transaction, KVPKey::AUTOCOUNT_DOCNO_CREDIT_NOTE, $docNo);
                if($eInvoiceValidationLink){
                    $this->updateOrCreateKeyValuePair($transaction, KVPKey::AUTOCOUNT_EINVOICE_VALIDATION_LINK_CREDIT_NOTE, $eInvoiceValidationLink);
                }
            }
        }
        else {
            $booking = Booking::where('marking', $ref)->first();
            if($booking){
                if($docNo != "" && $docNo != "<<New>>"){
                    $payments = $booking->transactions()->payments()->get();
                    foreach ($payments as $payment) {
                        $refundTransaction = $payment->transactions()->refunds()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->latest()->first();
                        if($refundTransaction){
                            $this->updateOrCreateKeyValuePair($refundTransaction, KVPKey::AUTOCOUNT_DOCNO_CREDIT_NOTE, $docNo);
                            if($eInvoiceValidationLink){
                                $this->updateOrCreateKeyValuePair($refundTransaction, KVPKey::AUTOCOUNT_EINVOICE_VALIDATION_LINK_CREDIT_NOTE, $eInvoiceValidationLink);
                            }
                            break;
                        }
                    }
                }
            }
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Processing single record for E-Invoice from Credit Note Report Import. ElapsedTime: ' . $elapsedTime . '.');
    }


    private function updateOrCreateKeyValuePair($booking, $key, $value)
    {
        $keyValuePairObject = new KeyValuePairObject($key, $value);
        $metadata = $booking->attributesKVP()->where('key', $key)->first();

        if ($metadata) {
            (App()->make(UpdatesKeyValuePair::class))->execute($metadata, $keyValuePairObject);
        } else {
            (App()->make(CreatesKeyValuePair::class))->execute($booking, $keyValuePairObject);
        }
    }
}
