<?php

namespace MtcPharmacy\ReferAFriend;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use Mtc\Shop\Events\OrderStatusChangedEvent;
use App\Events\MemberCreatedEvent;
use Mtc\Shop\Order;
use MtcPharmacy\ReferAFriend\Classes\ReferralService;

class ReferAFriendServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        if (!config('referrals.enabled')) {
            return;
        }

        $this->loadRoutesFrom(__DIR__ . '/routes/web.php');
        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');

        $view_paths = \Config::get('view.paths');
        $view_paths[] = __DIR__ . '/templates';
        \Config::set('view.paths', $view_paths);

        Event::listen(OrderStatusChangedEvent::class, function (OrderStatusChangedEvent $event) {
            try {
                $status = (int) $event->getStatus();
                $order = $event->getOrder();

                if ($status === Order::STATUS_SHIPPED) {
                    app(ReferralService::class)->processShippedOrder($order);
                }

                if (in_array($status, [Order::STATUS_CANCELLED, Order::STATUS_REFUNDED])) {
                    app(ReferralService::class)->handleOrderCancellation($order);
                }
            } catch (\Exception $e) {
                error_log('ReferAFriend: ' . $e->getMessage());
            }
        });

        Event::listen(MemberCreatedEvent::class, function (MemberCreatedEvent $event) {
            try {
                app(ReferralService::class)->processNewMember($event->getMember());
            } catch (\Exception $e) {
                error_log('ReferAFriend: ' . $e->getMessage());
            }
        });
    }

    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__ . '/../config/referrals.php', 'referrals');
    }
}
