<?php

namespace MtcPharmacy\ReferAFriend;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
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) {
                Log::error('ReferAFriend: order event handler failed', [
                    'exception' => get_class($e),
                    'code'      => $e->getCode(),
                    'file'      => $e->getFile(),
                    'line'      => $e->getLine(),
                ]);
            }
        });

        Event::listen(MemberCreatedEvent::class, function (MemberCreatedEvent $event) {
            try {
                app(ReferralService::class)->processNewMember($event->getMember());
            } catch (\Exception $e) {
                Log::error('ReferAFriend: member created handler failed', [
                    'exception' => get_class($e),
                    'code'      => $e->getCode(),
                    'file'      => $e->getFile(),
                    'line'      => $e->getLine(),
                ]);
            }
        });
    }

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