<?php

namespace App\Classes\Modules\PerfexCRM\Processors;

use App\Classes\Modules\PerfexCRM\DataTransferObjects\UpdatePerfexCRMObject;
use App\Classes\ValueObjects\Constants\PerfexCRMTasks;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PerfexCRMProjectStatus;
use App\Classes\ValueObjects\Constants\PerfexCRMTaskStatus;
use App\Classes\Jobs\UpdatePerfexCRMPrelude;
use App\Classes\Jobs\CreatePerfexCRMInvoice;
use App\Models\Booking;
use App\Models\Transaction;
use Illuminate\Support\Facades\Log;

class TransactionToPerfexCRMV2Processor
{
    public function execute(Transaction $model, int $status)
    {
        try {
            if($model->owner instanceof \App\Models\Transaction && in_array($model->type, [TransactionType::PAYMENT])) {
                //
                $transaction = $model;
                $info = $this->extractInfo($transaction);
                $tasks = $this->defineTasks($model, $status);

                //if(count($tasks) > 0) { //commented, otherwise when customer paid, invoice payment will not get created at crm because there is no tasks attached
                    $updatePerfexCRMObject = new UpdatePerfexCRMObject(
                        $info['companyName'],
                        $info['companyReference'],
                        $info['contactName'],
                        $info['contactEmail'],
                        $info['bookingMarking'],
                        $info['projectName'],
                        PerfexCRMProjectStatus::IN_PROGRESS,
                        0,      //invoiceId
                        [],     //milestoneNames
                        $tasks
                    );

                    $this->dispatchUpdateJob($transaction, $status, $updatePerfexCRMObject);
                //}
            }
            else if($model->owner instanceof \App\Models\PackingList && $model->status == ApprovalStatus::PENDING_SUBMISSION && $status == ApprovalStatus::APPROVED)
            {
                CreatePerfexCRMInvoice::dispatch($model);
            }
        } catch (\Exception $exception) {
            Log::error($exception);
        }
        return true;
    }

    //Level 1
    private function extractInfo(Transaction $model): array
    {
        $packingList = $model->owner->owner;
        $order = $packingList->owner()->first();
        $companyModule = $order->companyModule()->first();
        $employee = $companyModule->employees()->first();

        $info = [];
        $info['companyName'] = $companyModule->name;
        $info['companyReference'] = $companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
        $info['contactName'] = $employee->name;
        $info['contactEmail'] = $employee->email;
        $info['bookingMarking'] = $packingList->id."-".$packingList->owner->id;
        $info['projectName'] = 'IZYIM | X1 Shipping | '.$order->reference.' | '.$packingList->reference;

        return $info;
    }

    private function defineTasks(Transaction $model, int $status): array
    {
        $tasks = [];

        if ($status === ApprovalStatus::PENDING_SUBMISSION) {
            $tasks = $this->defineTasks_handlePendingVerificationStatus($model);
        } elseif ($status === ApprovalStatus::APPROVED) {
            $tasks = $this->defineTasks_handleApprovedStatus($model);
        }

        return $tasks;
    }

    private function dispatchUpdateJob(Transaction $model, int $status, UpdatePerfexCRMObject $updatePerfexCRMObject)
    {
        $withInvoice = ($model->type === TransactionType::PAYMENT && $model->owner instanceof \App\Models\Transaction && $status == ApprovalStatus::APPROVED);
        UpdatePerfexCRMPrelude::dispatch(null, $model, $updatePerfexCRMObject, $withInvoice);
    }




    //Level Others: Nested
    private function defineTasks_handlePendingVerificationStatus(Transaction $model): array
    {
        $tasks = [];
        switch($model->type) {
            case TransactionType::PAYMENT:
                $tasks = $this->definePaymentTasks($model);
                break;
        }

        return $tasks;
    }

    private function defineTasks_handleApprovedStatus(Transaction $model): array
    {
        $tasks = [];
        switch($model->type) {
            case TransactionType::PAYMENT:
                $tasks = $this->defineTasks_handleApprovedStatus_handlePaymentApprovedStatus();
                break;
        }

        return $tasks;
    }


    private function definePaymentTasks(Transaction $model): array //cief todo: to comfirm what tasks need to be created at crm
    {
        $tasks = [];
        return $tasks;
    }

    private function defineTasks_handleApprovedStatus_handlePaymentApprovedStatus(): array //cief todo: to comfirm what tasks need to be created at crm
    {
        $tasks = [];
        // $tasks = [
        //     PerfexCRMTasks::TASK_POST_PAYMENT_1,
        //     PerfexCRMTasks::TASK_POST_PAYMENT_2,
        //     PerfexCRMTasks::TASK_POST_PAYMENT_3,
        //     PerfexCRMTasks::TASK_POST_PAYMENT_4,
        // ];
        return $tasks;
    }

    private function completeTask($startTask, $endTask) {
        $startTask['status'] = PerfexCRMTaskStatus::COMPLETED;
        $endTask['status'] = PerfexCRMTaskStatus::IN_PROGRESS;
        return [$startTask, $endTask];
    }
}
