<?php

namespace App\Support;

use App\Models\NotificationLog;
use App\Models\Order;
use App\Models\User;

class NotificationManager
{
    public static function log(User $user, ?Order $order, string $channel, string $subject, string $message): NotificationLog
    {
        return NotificationLog::query()->create([
            'user_id' => $user->id,
            'order_id' => $order?->id,
            'channel' => $channel,
            'recipient' => $channel === 'whatsapp' ? ($user->mobile ?? $user->email) : $user->email,
            'subject' => $subject,
            'message' => $message,
            'status' => 'queued',
            'sent_at' => now(),
        ]);
    }

    public static function orderPlaced(Order $order): void
    {
        $user = $order->user;

        if (!$user) {
            return;
        }

        $message = "Order {$order->order_number} has been placed successfully. Current status: {$order->status}.";

        static::log($user, $order, 'email', 'Order placed', $message);
        static::log($user, $order, 'whatsapp', 'Order placed', $message);
    }

    public static function paymentReceived(Order $order): void
    {
        $user = $order->user;

        if (!$user) {
            return;
        }

        $message = "Payment received for {$order->order_number}. Our team will review your document and move it to printing.";

        static::log($user, $order, 'email', 'Payment received', $message);
        static::log($user, $order, 'whatsapp', 'Payment received', $message);
    }

    public static function statusUpdated(Order $order): void
    {
        $user = $order->user;

        if (!$user) {
            return;
        }

        $message = "Order {$order->order_number} is now marked as {$order->status}.";

        static::log($user, $order, 'email', 'Order status updated', $message);
        static::log($user, $order, 'whatsapp', 'Order status updated', $message);
    }
}
