<?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\WisebeeCategory;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeConsultation;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeDocument;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeSetting;
use Mtc\Plugins\Wisebee\Classes\WisebeeManager;
use Mtc\Shop\Category;

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_CONSULTATION)
            ],
        ]);
    }

    /**
     * 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));
    }

    /**
     * Downloads a document
     *
     * @param $id
     * @return void
     */
    public function downloadDocument($id): void
    {
        $document = WisebeeDocument::query()
            ->find($id);
        if (empty($document)) {
            return;
        }

        $fileNameParts = explode('/', $document->file);
        $fileName = end($fileNameParts);

        $fullPath = $_SERVER['DOCUMENT_ROOT'] . $document->file;

        $fp = fopen($fullPath, 'rb');

        header('Pragma: public');
        header("Content-type:application/pdf");
        header('Content-disposition: inline;filename=' . $fileName);
        header("Content-Length: " . filesize($fullPath));

        fpassthru($fp);
        exit;
    }

    /**
     * Wisebee configuration page
     */
    public function configuration()
    {
        $title = 'Wisebee Configuration';
        $page_meta['title'] = config('app.name') . ' | ' . $title;

        $requiredCategoriesIds = WisebeeCategory::query()
            ->where('consultation_required', true)
            ->pluck('category_id');

        return template('wisebee/admin/configuration.twig', [
            'page_meta' => $page_meta,
            'wisebeeSettings' => WisebeeSetting::allSettings(),
            'wisebeeSettingsDefaults' => WisebeeSetting::$settings,
            'title' => $title,
            'success' => session()->get('success'),
            'categories' => Category::getCompleteFlatTree()
                ->map(function (Category $category) use ($requiredCategoriesIds) {
                    $category->required = $requiredCategoriesIds->contains($category->id);
                    return $category;
                }),
        ]);
    }

    /**
     * Save configuration
     */
    public function configurationStore(Request $request)
    {
        WisebeeCategory::query()
            ->truncate();

        foreach ($request->input('categories') as $categoryID) {
            WisebeeCategory::query()
                ->create([
                    'category_id' => $categoryID,
                    'consultation_required' => true,
                ]);
        }

        $submittedSettings = $request->input('settings');

        foreach (WisebeeSetting::$settings as $key => $attributes) {
            if (isset($submittedSettings[$key])) {
                $value = $submittedSettings[$key];
            } else {
                $value = null;
            }
            WisebeeSetting::query()
                ->where('name', $key)
                ->update([
                    'value' => $value,
                ]);
        }

        session()->flash('success', 'Configuration updated successfully!');
        return redirect(route('wisebee-admin-configuration'));
    }
}
