<?php

namespace Mtc\Plugins\Wisebee\Classes\Handlers;

use Exception;
use Illuminate\Database\Eloquent\Builder;
use Mtc\Core\AdminUser;
use Mtc\Modules\Members\Models\MemberNote;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeMember;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeNote;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeUser;
use Mtc\Shop\Item;
use Wisebee\Resources\CustomerNote as RemoteCustomerNote;

class CustomerNoteHandler extends BaseHandler
{
    const RESOURCE_NAME = 'customer_note';

    /**
     * Whenever customer note is updated on Wisebee, we handle it here
     *
     * @param $post
     */
    protected function handleCustomerNote($post): void
    {
        if (empty($post->id)) {
            return;
        }

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

        if (in_array($post->event, [self::EVENT_RESOURCE_CREATED, self::EVENT_RESOURCE_UPDATED])) {
            /** @var RemoteCustomerNote $remoteCustomerNote */
            $remoteCustomerNote = $this->wisebee->get(RemoteCustomerNote::class, $post->id);
            if (empty($remoteCustomerNote)) {
                return;
            }

            if ($post->event === self::EVENT_RESOURCE_CREATED) {
                $this->createCustomerNote($remoteCustomerNote);
                return;
            }

            if ($post->event === self::EVENT_RESOURCE_UPDATED) {
                $this->updateCustomerNote($remoteCustomerNote);
            }
        }
    }

    /**
     * Deletes local customer note
     * Initiated by webhook
     *
     * @param $remoteNoteID
     * @return void
     */
    protected function deleteCustomerNote($remoteNoteID): void
    {
        $remoteCustomerNote = $this->wisebee->get(RemoteCustomerNote::class, $remoteNoteID);

        // If the note still exists in Wisebee, this means this could be a malicious request
        if (!empty($remoteCustomerNote)) {
            return;
        }

        $wisebeeNote = WisebeeNote::query()
            ->where('wisebee_id', $remoteNoteID)
            ->first();

        if (empty($wisebeeNote)) {
            return;
        }

        if (!empty($wisebeeNote->note)) {
            $wisebeeNote->note->delete();
        }

        $wisebeeNote->delete();
    }

    /**
     * Updates local customer note
     * Initiated by webhook
     *
     * @param $remoteCustomerNote
     * @return void
     */
    protected function updateCustomerNote($remoteCustomerNote): void
    {
        /** @var WisebeeNote $wisebeeNote */
        $wisebeeNote = WisebeeNote::query()
            ->where('wisebee_id', $remoteCustomerNote->id)
            ->first();

        if (empty($wisebeeNote)) {
            $this->createCustomerNote($remoteCustomerNote);
            return;
        }
        $note = $wisebeeNote->note;
        if (empty($note)) {
            return;
        }
        $note->content = $remoteCustomerNote->note;
        $note->save();
    }

    /**
     * Creates local customer note
     * Initiated by webhook
     *
     * @param $remoteCustomerNote
     * @return void
     */
    protected function createCustomerNote($remoteCustomerNote): void
    {

        /** @var WisebeeMember $wisebeeMember */
        $wisebeeMember = WisebeeMember::query()
            ->where('wisebee_id', $remoteCustomerNote->customer_id)
            ->first();

        if (empty($wisebeeMember)) {
            return;
        }

        $wisebeeUser = WisebeeUser::query()
            ->where('wisebee_id', $remoteCustomerNote->created_by_id)
            ->first();

        $data = [
            'member_id' => $wisebeeMember->member_id,
            'admin_user_id' => !empty($wisebeeUser) ?
                $wisebeeUser->admin_user_id :
                null,
            'content' => $remoteCustomerNote->note,
        ];

        if (!empty($remoteCustomerNote->consultation_id)) {

            $orderItem = \Mtc\Shop\Order\Item::query()
                ->whereHas('item', function (Builder $query) use ($remoteCustomerNote) {
                    $query->whereHas('wisebee_consultation', function (Builder $query) use ($remoteCustomerNote) {
                        $query->where('wisebee_id', $remoteCustomerNote->consultation_id);
                    });
                })
                ->first();
            if (!empty($orderItem)) {
                $data['order_id'] = $orderItem->order_id;
            }
        }

        $note = MemberNote::query()
            ->create($data);

        WisebeeNote::query()
            ->create([
                'wisebee_id' => $remoteCustomerNote->id,
                'member_note_id' => $note->id,
            ]);
    }

    /**
     * When a note is created on member, creates the note in Wisebee
     *
     * @param MemberNote $note
     * @throws Exception
     */
    public function createNoteInWisebee(MemberNote $note): void
    {
        $this->member = $note->member;
        $this->wisebeeMember();

        if (empty($this->wisebeeMember)) {
            return;
        }

        if (!$adminUser = AdminUser::query()->find($_SESSION['adminId'])) {
            return;
        }
        if (empty($adminUser->wisebee_user)) {
            return;
        }

        $consultationID = null;

        if (!empty($note->order)) {
            foreach ($note->order->items as $orderItem) {
                $item = Item::query()->find($orderItem->item_id);
                if (!empty($item->wisebee_consultation)) {
                    $consultationID = $item->wisebee_consultation->wisebee_id;
                    break;
                }
            }
        }

        $noteData = [
            'customer_id' => $this->wisebeeMember->wisebee_id,
            'created_by_id' => $adminUser->wisebee_user->wisebee_id,
            'consultation_id' => $consultationID,
            'note' => $note->content,
            'is_private' => true,
        ];

        $remoteCustomerNote = $this->wisebee->create(RemoteCustomerNote::class, $noteData);

        if (empty($remoteCustomerNote)) {
            return;
        }
        WisebeeNote::query()
            ->create([
                'wisebee_id' => $remoteCustomerNote->id,
                'member_note_id' => $note->id,
            ]);
    }
}