<?php

namespace Mtc\Plugins\Wisebee\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Event;
use Mtc\Modules\Members\Classes\Auth;
use Mtc\Plugins\Wisebee\Classes\Events\WisebeeWebhookEvent;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeConsultation;
use Mtc\Plugins\Wisebee\Classes\WisebeeManager;

class WisebeeController extends Controller
{
    /**
     * Book a consultation page
     */
    public function book(Request $request)
    {
        $wisebeeManager = new WisebeeManager();

        if (!empty(request()->input('ocp_key'))) {
            $wisebeeManager->loginUserFromHash($request->input('ocp_key'));
            if ($request->input('ocp_action') === 'pay') {
                if ($redirect = $wisebeeManager->getPaymentRedirect($request->input('ocp_key'))) {
                    return redirect($redirect);
                }
            }
        }

        if (!Auth::isLoggedIn()) {
            return redirect(
                route('members-register-express', [
                    'redirect' => urlencode(route('wisebee-book', $_GET, false))
                ])
            );
        }

        $bookingSnippet = $wisebeeManager->getWidgetSnippet(WisebeeManager::WIDGET_BOOKING);

        return template('wisebee/booking.twig', [
            'bookingWidgetSnippet' => $bookingSnippet,
            'footerScripts' => [
                WisebeeManager::getWisebeeScript(WisebeeManager::WIDGET_BOOKING)
            ],
        ]);
    }

    /**
     * Video consultation page
     */
    public function video()
    {
        $wisebeeManager = new WisebeeManager();

        $wisebeeManager->loginUserFromHash(request()->input('ocp_key'));

        $videoSnippet = $wisebeeManager->getWidgetSnippet(WisebeeManager::WIDGET_CONSULTATION);

        return template('wisebee/video.twig', [
            'videoWidgetSnippet' => $videoSnippet,
            'footerScripts' => [
                WisebeeManager::getWisebeeScript(WisebeeManager::WIDGET_CONSULTATION)
            ],
            'fullWidth' => true,
        ]);
    }

    /**
     * Member consultations page
     */
    public function memberConsultations()
    {
        $member = Auth::getLoggedInMember();

        if (empty($member->id)) {
            return redirect(route('members-login'));
        }
        $page_meta['title'] = config('app.name') . ' | Your Consultations';

        return template('wisebee/memberConsultations.twig', [
            'page_meta' => $page_meta,
            'consultations' => WisebeeConsultation::getMemberConsultations($member->id),
        ]);
    }

    /**
     * Video consultation page
     *
     * @return void
     */
    public function webhook(): void
    {
        $post = file_get_contents("php://input");
        $post = json_decode($post);

        Event::dispatch(WisebeeWebhookEvent::class, new WisebeeWebhookEvent($post));
    }
}
