<?php

namespace Mtc\Plugins\Wisebee\Classes\Handlers;

use Exception;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeConsultation;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeParticipant;
use Mtc\Shop\Basket\Item as BasketItem;
use Mtc\Shop\Order;
use Wisebee\Resources\Consultation as RemoteConsultation;

class ConsultationHandler extends BaseHandler
{
    const RESOURCE_NAME = 'consultation';

    /**
     * Handles incoming consultation changes from Wisebee
     *
     * @throws Exception
     */
    protected function handleConsultation($post): void
    {
        if (in_array($post->event, [self::EVENT_RESOURCE_CREATED, self::EVENT_RESOURCE_UPDATED])) {
            $this->createUpdateConsultation($post->id);
            return;
        }

        if ($post->event === self::EVENT_RESOURCE_DELETED) {
            $this->deleteConsultation($post->id);
        }
    }


    /**
     * Creates / updates consultation received from Wisebee
     *
     * @param $remoteConsultationID
     * @return WisebeeConsultation
     * @throws Exception
     */
    protected function createUpdateConsultation($remoteConsultationID): WisebeeConsultation
    {
        /** @var RemoteConsultation $remoteConsultation */
        $remoteConsultation = $this->wisebee->get(RemoteConsultation::class, $remoteConsultationID);

        if (empty($remoteConsultation)) {
            throw new Exception('Consultation not found');
        }

        /** @var WisebeeConsultation $wisebeeConsultation */
        $wisebeeConsultation = WisebeeConsultation::query()
            ->where('wisebee_id', $remoteConsultation->id)
            ->first();

        if (empty($wisebeeConsultation)) {
            $wisebeeConsultation = new WisebeeConsultation();
        } else {
            // If consultation status changes to complete
            if (
                $wisebeeConsultation->status !== 'complete' &&
                $remoteConsultation->status === 'complete'
            ) {
                try {
                    $documentHandler = new DocumentHandler($this->manager);
                    $documentHandler->pullDocuments($remoteConsultation->id);

                    $orderItem = Order\Item::query()
                        ->where('item_id', $wisebeeConsultation->item->id)
                        ->first();
                    $order = new \Order($orderItem->order_id);
                    $order->updateStatus(Order::STATUS_COMPLETE);
                } catch (Exception $e) {

                }
            }
        }
        $wisebeeConsultation->fill((array)$remoteConsultation);
        $wisebeeConsultation->wisebee_id = $remoteConsultation->id;
        $wisebeeConsultation->wisebee_user_id = $remoteConsultation->user_id;
        $wisebeeConsultation->wisebee_created_by_id = $remoteConsultation->created_by_id;
        $wisebeeConsultation->save();

        $wisebeeConsultation->participants()->delete();

        $customerParticipant = null;
        foreach ($remoteConsultation->all_participants as $remoteParticipant) {
            $wisebeeParticipant = new WisebeeParticipant();
            $wisebeeParticipant->fill((array)$remoteParticipant);
            if ($wisebeeParticipant->lastname === null) {
                $wisebeeParticipant->lastname = '';
            }
            $wisebeeParticipant->wisebee_id = $remoteParticipant->id;
            $wisebeeParticipant->wisebee_consultation_id = $remoteParticipant->consultation_id;
            $wisebeeParticipant->wisebee_user_id = $remoteParticipant->user_id;
            $wisebeeParticipant->hash = $remoteParticipant->hash;
            $wisebeeParticipant->save();

            if ($wisebeeParticipant->type === WisebeeParticipant::TYPE_CUSTOMER) {
                $customerParticipant = $wisebeeParticipant;
            }
        }

        $wisebeeConsultation->load('participants');

        // If a new consultation has been created by customer
        if (
            !empty($customerParticipant) &&
            empty($wisebeeConsultation->added_to_basket) &&
            $remoteConsultation->created_by_id === $customerParticipant->wisebee_user_id
        ) {
            $this->manager->addToBasket($wisebeeConsultation);
        }

        $wisebeeConsultation->save();
        return $wisebeeConsultation;
    }


    /**
     * Deletes consultation initiated by Wisebee
     *
     * @param $remoteConsultationID
     * @throws Exception
     */
    protected function deleteConsultation($remoteConsultationID): void
    {
        $remoteConsultation = $this->wisebee->get(RemoteConsultation::class, $remoteConsultationID);

        if (!empty($remoteConsultation)) {
            return;
        }

        $wisebeeConsultation = WisebeeConsultation::query()
            ->where('wisebee_id', $remoteConsultationID)
            ->first();

        if (!empty($wisebeeConsultation->item_id)) {
            // Remove deleted consultation from basket
            BasketItem::query()
                ->where('item_id', $wisebeeConsultation->item_id)
                ->delete();
        }

        WisebeeParticipant::query()
            ->where('wisebee_consultation_id', $remoteConsultationID)
            ->delete();

        WisebeeConsultation::query()
            ->where('wisebee_id', $remoteConsultationID)
            ->delete();
    }

    /**
     * Gets consultation participant with type 'customer'
     *
     * @param WisebeeConsultation|null $wisebeeConsultation
     * @return WisebeeParticipant|null
     */
    public static function getCustomerParticipant(?WisebeeConsultation $wisebeeConsultation): ?WisebeeParticipant
    {
        if (empty($wisebeeConsultation)) {
            return null;
        }
        /** @var WisebeeParticipant $customerParticipant */
        $customerParticipant = $wisebeeConsultation->participants()
            ->where('type', WisebeeParticipant::TYPE_CUSTOMER)
            ->first();
        return $customerParticipant;
    }
}