<?php

namespace Mtc\Plugins\Wisebee\Classes\Handlers;

use Exception;
use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeMember;
use Mtc\Plugins\Wisebee\Classes\WisebeeManager;
use stdClass;
use Wisebee\Wisebee;
use Wisebee\WisebeeException;

class BaseHandler
{

    protected Wisebee $wisebee;
    protected Member $member;
    protected WisebeeMember|null $wisebeeMember;

    const EVENT_RESOURCE_CREATED = 'created';
    const EVENT_RESOURCE_UPDATED = 'updated';
    const EVENT_RESOURCE_DELETED = 'deleted';

    protected WisebeeManager $manager;

    public function __construct(WisebeeManager $manager)
    {
        $this->manager = $manager;
        $this->wisebee = $manager->wisebee();
    }

    /**
     * When a webhook is called, we use Wisebee library to determine what action is being made
     *
     * @param stdClass $post
     */
    public function processWebhookCall(stdClass $post): void
    {
        try {
            if (empty($post->event)) {
                throw new Exception('Empty event');
            }

            if (empty($post->resource)) {
                return;
            }
            if ($post->resource === CustomerNoteHandler::RESOURCE_NAME) {
                $handler = new CustomerNoteHandler($this->manager);
                $handler->handleCustomerNote($post);
            }
            if ($post->resource === ConsultationHandler::RESOURCE_NAME) {
                $handler = new ConsultationHandler($this->manager);
                $handler->handleConsultation($post);
            }
        } catch (WisebeeException | Exception $exception) {
            error_log($exception->getMessage());
            echo "Error: " . $exception->getMessage();
        }
    }

    /**
     * Wisebee member getter
     *
     * @return WisebeeMember|null
     * @throws Exception
     */
    protected function wisebeeMember(): WisebeeMember|null
    {
        $this->manager->setMember($this->member);
        $this->manager->setWisebeeMember();
        $this->wisebeeMember = $this->manager->wisebeeMember();
        return $this->wisebeeMember;
    }
}