<?php

namespace MtcPharmacy\Subscriptions;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use Mtc\Shop\Events\OrderPaidEvent;
use Mtc\Shop\Order;


class SubscriptionsServiceProvider extends ServiceProvider
{

    public function boot() : void
    {
        $this->loadRoutesFrom(__DIR__ . '/routes/web.php');

        // Pharmacy platform uses custom twig template loaders.
        $view_paths = \Config::get('view.paths');
        $view_paths[] = __DIR__ . '/templates';
        \Config::set('view.paths', $view_paths);
    }


    public function register()
    {
        Event::listen('Members/Admin/MemberOpenTabNav', function($member_id = null) {
            if (! $member_id) return;

            return '
                    <li>
                        <a href="' . route('admin-subscriptions-create', [ $member_id ], false) . '"> Create a subscription </a>
                    </li>
                ';
        });

        Event::listen(OrderPaidEvent::class, function(OrderPaidEvent $event) {
            try {
                $order = Order::query()->find($event->getOrder()->getId());
                $subscription = $order->subscriptions->first();
                if ($subscription) {
                    $subscription->setActive();
                }
            } catch(\Exception $e) {
                error_log($e->getMessage());
            }
        });

    }
}
