<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Services;

use App\Models\Order;
use App\Models\Setting;
use App\Models\Conversation;
use App\Events\MessageSent;
use App\Notifications\SystemNotification;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use App\Mail\OrderPlacedMail;
use App\Mail\OrderShippedMail;
use App\Mail\OrderCompletedMail;
use Exception;

class OrderNotificationService
{
    protected $smsService;

    public function __construct(SmsService $smsService)
    {
        $this->smsService = $smsService;
    }

    private function isEnabled($key, $default = false)
    {
        $val = Setting::where('key', $key)->value('value');
        return filter_var($val ?? $default, FILTER_VALIDATE_BOOLEAN);
    }

    private function sendAutomatedChat(Order $order, $messageBody)
    {
        if (!$this->isEnabled('notify_order_status_chat', true)) return;

        $order->loadMissing('items');

        $productId = null;
        if ($order->items && $order->items->count() > 0) {
            $productId = $order->items->first()->product_id;
        }

        $conversation = Conversation::firstOrCreate(
            [
                'buyer_id' => $order->buyer_id, 
                'seller_id' => $order->seller_id, 
                'product_id' => $productId
            ],
            ['last_message_at' => now()]
        );

        $message = $conversation->messages()->create([
            'sender_id' => $order->seller_id, 
            'body' => '[SYS]' . $messageBody 
        ]);

        $conversation->update(['last_message_at' => now()]);

        try {
            broadcast(new MessageSent($message))->toOthers();
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::warning('Websocket Broadcast Failed: ' . $e->getMessage());
        }
    }

    public function sendOrderPlaced(Order $order)
    {
        $order->loadMissing(['buyer', 'seller', 'items.product.images']);

        // 1. Automated Chat Notification
        $this->sendAutomatedChat($order, __('Automated Message: Your order #:order has been successfully placed and is being processed.', ['order' => $order->order_number]));

        // 2. Database & WebSocket Bell Notifications
        if ($order->buyer) {
            try {
                $order->buyer->notify(new SystemNotification(
                    'Order Placed', 
                    "Your order #{$order->order_number} has been placed successfully.", 
                    route('buyer.orders.index', ['search' => $order->order_number]), 
                    'success'
                ));
            } catch (Exception $e) {}
        }

        if ($order->seller) {
            try {
                $buyerName = $order->buyer?->name ?? 'a customer';
                $order->seller->notify(new SystemNotification(
                    'New Order Received', 
                    "You received a new order #{$order->order_number} from {$buyerName}.", 
                    route('seller.orders.index', ['search' => $order->order_number]), 
                    'order'
                ));
            } catch (Exception $e) {}
        }

        // 3. BUYER Email & SMS NOTIFICATIONS
        if ($this->isEnabled('notify_order_placed_email', true) && $order->buyer?->email) {
            try { Mail::to($order->buyer->email)->send(new OrderPlacedMail($order, 'buyer')); } catch (Exception $e) { Log::error('Mail Error: ' . $e->getMessage()); }
        }
        if ($this->isEnabled('notify_order_placed_sms', false) && $order->buyer?->phone) {
            $msg = __('Hi :name, your order #:order has been placed successfully and is being processed.', [
                'name' => $order->buyer->name ?? 'Customer', 
                'order' => $order->order_number
            ]);
            try { $this->smsService->send($order->buyer->phone, $msg); } catch (Exception $e) { Log::error('SMS Error: ' . $e->getMessage()); }
        }

        // 4. SELLER Email & SMS NOTIFICATIONS
        if ($this->isEnabled('notify_order_placed_email', true) && $order->seller?->email) {
            try { Mail::to($order->seller->email)->send(new OrderPlacedMail($order, 'seller')); } catch (Exception $e) { Log::error('Mail Error: ' . $e->getMessage()); }
        }
        if ($this->isEnabled('notify_order_placed_sms', false) && $order->seller?->phone) {
            $msg = __('New Order! You have received order #:order. Please check your seller dashboard.', ['order' => $order->order_number]);
            try { $this->smsService->send($order->seller->phone, $msg); } catch (Exception $e) { Log::error('SMS Error: ' . $e->getMessage()); }
        }
    }

    public function sendOrderShipped(Order $order)
    {
        $order->loadMissing(['buyer', 'seller', 'items.product.images']);

        $tracking = $order->tracking_number ? "\n" . __('Tracking Number') . ": " . $order->tracking_number : "";
        $this->sendAutomatedChat($order, __('Automated Message: Good news! Your order #:order has been shipped.', ['order' => $order->order_number]) . $tracking);

        if ($order->buyer) {
            try {
                $order->buyer->notify(new SystemNotification(
                    'Order Shipped', 
                    "Your order #{$order->order_number} is on its way!", 
                    route('buyer.orders.index', ['search' => $order->order_number]), 
                    'truck'
                ));
            } catch (Exception $e) {}
        }

        if ($this->isEnabled('notify_order_shipped_email', true) && $order->buyer?->email) {
            try { Mail::to($order->buyer->email)->send(new OrderShippedMail($order)); } catch (Exception $e) { Log::error('Mail Error: ' . $e->getMessage()); }
        }
        if ($this->isEnabled('notify_order_shipped_sms', false) && $order->buyer?->phone) {
            $msg = __('Great news! Your order #:order has been shipped. Track it via your dashboard.', ['order' => $order->order_number]);
            try { $this->smsService->send($order->buyer->phone, $msg); } catch (Exception $e) { Log::error('SMS Error: ' . $e->getMessage()); }
        }
    }

    public function sendOrderCompleted(Order $order)
    {
        $order->loadMissing(['buyer', 'seller', 'items.product.images']);

        $this->sendAutomatedChat($order, __('Automated Message: Order #:order is now marked as completed. Thank you for your business!', ['order' => $order->order_number]));

        if ($order->seller) {
            try {
                $order->seller->notify(new SystemNotification(
                    'Order Completed', 
                    "Order #{$order->order_number} was marked as received by the buyer.", 
                    route('seller.orders.index', ['search' => $order->order_number]), 
                    'success'
                ));
            } catch (Exception $e) {}
        }

        if ($this->isEnabled('notify_order_completed_email', false) && $order->buyer?->email) {
            try { Mail::to($order->buyer->email)->send(new OrderCompletedMail($order, 'buyer')); } catch (Exception $e) { Log::error('Mail Error: ' . $e->getMessage()); }
        }
        if ($this->isEnabled('notify_order_completed_sms', false) && $order->buyer?->phone) {
            $msg = __('Your order #:order is complete. Thanks for shopping with us!', ['order' => $order->order_number]);
            try { $this->smsService->send($order->buyer->phone, $msg); } catch (Exception $e) { Log::error('SMS Error: ' . $e->getMessage()); }
        }

        if ($this->isEnabled('notify_order_completed_email', false) && $order->seller?->email) {
            try { Mail::to($order->seller->email)->send(new OrderCompletedMail($order, 'seller')); } catch (Exception $e) { Log::error('Mail Error: ' . $e->getMessage()); }
        }
        if ($this->isEnabled('notify_order_completed_sms', false) && $order->seller?->phone) {
            $msg = __('Success! Order #:order has been marked as received and completed by the buyer.', ['order' => $order->order_number]);
            try { $this->smsService->send($order->seller->phone, $msg); } catch (Exception $e) { Log::error('SMS Error: ' . $e->getMessage()); }
        }
    }

    public function sendOrderCancelled(Order $order)
    {
        $order->loadMissing(['buyer', 'seller']);

        $this->sendAutomatedChat($order, __('Automated Message: Order #:order has been cancelled.', ['order' => $order->order_number]));

        if ($order->buyer) {
            try {
                $order->buyer->notify(new SystemNotification(
                    'Order Cancelled', 
                    "Order #{$order->order_number} was cancelled.", 
                    route('buyer.orders.index', ['search' => $order->order_number]), 
                    'alert'
                ));
            } catch (Exception $e) {}
        }

        if ($order->seller) {
            try {
                $order->seller->notify(new SystemNotification(
                    'Order Cancelled', 
                    "Order #{$order->order_number} was cancelled.", 
                    route('seller.orders.index', ['search' => $order->order_number]), 
                    'alert'
                ));
            } catch (Exception $e) {}
        }
    }

    public function sendOrderRefunded(Order $order)
    {
        $order->loadMissing('buyer');

        $this->sendAutomatedChat($order, __('Automated Message: Your order #:order has been successfully refunded.', ['order' => $order->order_number]));

        if ($order->buyer) {
            try {
                $order->buyer->notify(new SystemNotification(
                    'Order Refunded', 
                    "Your order #{$order->order_number} has been refunded.", 
                    route('buyer.orders.index', ['search' => $order->order_number]), 
                    'success'
                ));
            } catch (Exception $e) {}
        }
    }

    public function sendRefundDeclined(Order $order)
    {
        $order->loadMissing('buyer');

        $this->sendAutomatedChat($order, __('Automated Message: Your refund request for order #:order has been declined. Please let me know if you have any questions.', ['order' => $order->order_number]));

        if ($order->buyer) {
            try {
                $order->buyer->notify(new SystemNotification(
                    'Refund Request Declined', 
                    "Your refund request for order #{$order->order_number} was declined.", 
                    route('buyer.orders.index', ['search' => $order->order_number]), 
                    'alert'
                ));
            } catch (Exception $e) {}
        }
    }
}