<?php

namespace App\Listeners;

use App\Events\OrderApproved;
use App\Events\OrderRejected;
use App\Jobs\SendEmailJob;
use App\Models\Log;
use App\Traits\ChecksNotificationPreference;

class OrderEventListener
{
    use ChecksNotificationPreference;

    public function handleApproved(OrderApproved $event): void
    {
        $order = $event->order;
        $order->loadMissing('client');

        // Send email notification
        if ($this->shouldSendNotification($order->client, 'invoice_created')) {
            SendEmailJob::dispatch(
                'Order Approved',
                'order',
                $order->id,
                ['ORDER_NUMBER' => $order->order_number]
            );
        }

        Log::create([
            'type' => Log::TYPE_SYSTEM,
            'observer' => 'OrderEventListener',
            'module' => 'Order',
            'method' => 'handleApproved',
            'description' => "Order #{$order->order_number} approved notification sent",
            'client_id' => $order->client_id,
            'ip_address' => request()->ip() ?? '0.0.0.0',
        ]);
    }

    public function handleRejected(OrderRejected $event): void
    {
        $order = $event->order;
        $order->loadMissing('client');

        SendEmailJob::dispatch(
            'Order Rejected',
            'order',
            $order->id,
            [
                'ORDER_NUMBER' => $order->order_number,
                'REJECTION_REASON' => $event->reason,
            ]
        );

        Log::create([
            'type' => Log::TYPE_SYSTEM,
            'observer' => 'OrderEventListener',
            'module' => 'Order',
            'method' => 'handleRejected',
            'description' => "Order #{$order->order_number} rejected. Reason: {$event->reason}",
            'client_id' => $order->client_id,
            'ip_address' => request()->ip() ?? '0.0.0.0',
        ]);
    }

    public function subscribe($events): array
    {
        return [
            OrderApproved::class => 'handleApproved',
            OrderRejected::class => 'handleRejected',
        ];
    }
}
