<?php

namespace App\Listeners\Ecommerce\Order;

use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Laravel\Nova\Notifications\NovaNotification;

class SendOrderCreatedNotification implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(object $event): void
    {
        if (! app()->isProduction()) {
            return;
        }

        $this->sendSMSToClient($event->order);
        $this->sendSMSToStaff($event->order);
        // $this->sendSMSToVendors($event->order);
    }

    /**
     * Send sms to the client about order
     */
    public function sendSMSToClient($order): void
    {
        if (Validator::make(['phone' => $order->customer_phone], ['phone' => 'integer|between:61000000,71999999'])->fails()) {
            return;
        }

        $exists = DB::table('order_sent_notifications')
            ->where('order_id', $order->id)
            ->where('phone_number', $order->customer_phone)
            ->exists();

        if (! $exists) {
            DB::table('order_sent_notifications')
                ->insert([
                    'order_id' => $order->id,
                    'phone_number' => $order->customer_phone,
                ]);

            sendSMS(
                $order->customer_phone,
                sprintf(
                    'Siziň sargydygyňyz hasaba alyndy, sargydy tassyklamak üçin operatorymyz habarlaşar, sargyt belgi: %s',
                    $order->id
                )
            );

            Log::channel('order_sms_notification_sent_activity')
                ->info("SMS_SENT_FOR_ORDER[id, phone]: {$order->id}, {$order->customer_phone}");
        }
    }

    /**
     * Send sms to the staff
     */
    public function sendSMSToStaff($order): void
    {
        $exists = DB::table('order_sent_notifications')
            ->where('order_id', $order->id)
            ->where('phone_number', orderAdminNumber())
            ->exists();

        if (! $exists) {
            DB::table('order_sent_notifications')
                ->insert([
                    'order_id' => $order->id,
                    'phone_number' => orderAdminNumber(),
                ]);

            sendSMS(
                phone: orderAdminNumber(),
                message: sprintf(
                    'Täze sargyt: %s, eltip bermek: %s',
                    $order->id,
                    $order->shipping_method
                )
            );

            Log::channel('order_sms_notification_sent_activity')
                ->info(sprintf('SMS_SENT_FOR_ORDER[id, phone]: %s, %s', $order->id, orderAdminNumber()));

            // User::where('phone_number', orderAdminNumber())->first()->notify(
            //     NovaNotification::make()
            //         ->message('Täze sargyt.')
            //         ->action('Gör', sprintf('/turkmenpostadmin/resources/orders/%s', $order->id))
            //         ->icon('download')
            //         ->type('info')
            // );
        }
    }

    /**
     * Send sms to vendor
     */
    public function sendSMSToVendors($order): void
    {
        $order_items = $order->items;

        // Check is channels exists
        $channel_ids = $order_items->pluck('channel_id')->unique();
        if ($channel_ids->isEmpty()) {
            return;
        }

        // Check if channels linked to users
        $user_ids = DB::table('channels')
            ->whereIntegerInRaw('id', $channel_ids)
            ->where('channelables_type', User::class)
            ->pluck('channelables_id');

        if ($user_ids->isEmpty()) {
            return;
        }

        $users = User::whereIntegerInRaw('id', $user_ids)
            ->whereNotNull('phone_number')
            ->get(['id', 'phone_number']);

        $users->each(function ($user) use ($order) {
            if (Validator::make(['phone' => $user->phone_number], ['phone' => 'integer|between:61000000,71999999'])->passes()) {
                sendSMS($user->phone_number, 'Täze sargyt: '.$order->id);

                Log::channel('order_sms_notification_sent_activity')
                    ->info("SMS_SENT_FOR_VENDOR_ORDER[id, phone]: {$order->id}, {$user->phone_number}");
            }

            $user->notify(
                NovaNotification::make()
                    ->message('Täze sargyt.')
                    ->action('Gör', sprintf('/turkmenpostadmin/resources/orders/%s', $order->id))
                    ->icon('download')
                    ->type('info')
            );
        });
    }
}
