<?php

namespace App\Services;

use App\Mail\NewOrderAdmin;
use App\Mail\OrderConfirmed;
use App\Mail\OrderShipped;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class MailService
{
    /**
     * Reconfigure the mail driver at runtime using DB settings.
     * Falls back to 'log' driver when SMTP is not configured.
     */
    private function configure(): void
    {
        $s = DB::table('store_settings')->pluck('value', 'key');

        $host = $s->get('mail_host', '');
        $user = $s->get('mail_username', '');

        if (!$host || !$user) {
            // No SMTP configured — log emails to storage/logs/laravel.log
            config([
                'mail.default'                        => 'log',
                'mail.mailers.log.channel'            => 'stack',
            ]);
            return;
        }

        config([
            'mail.default'                              => 'smtp',
            'mail.mailers.smtp.host'                    => $host,
            'mail.mailers.smtp.port'                    => (int) $s->get('mail_port', 587),
            'mail.mailers.smtp.username'                => $user,
            'mail.mailers.smtp.password'                => $s->get('mail_password', ''),
            'mail.mailers.smtp.encryption'              => $s->get('mail_encryption', 'tls'),
            'mail.from.address'                         => $s->get('mail_from_address', $user),
            'mail.from.name'                            => $s->get('store_name', config('app.name')),
        ]);
    }

    public function sendOrderConfirmed(Order $order): void
    {
        $to = $order->user?->email ?? $order->guest_email;
        if (!$to) return;

        $this->configure();

        try {
            Mail::to($to)->send(new OrderConfirmed($order));
        } catch (\Throwable $e) {
            Log::error("OrderConfirmed mail failed for {$order->order_number}: " . $e->getMessage());
        }
    }

    public function sendOrderShipped(Order $order): void
    {
        $to = $order->user?->email ?? $order->guest_email;
        if (!$to) return;

        $this->configure();

        try {
            Mail::to($to)->send(new OrderShipped($order));
        } catch (\Throwable $e) {
            Log::error("OrderShipped mail failed for {$order->order_number}: " . $e->getMessage());
        }
    }

    public function sendNewOrderAdmin(Order $order): void
    {
        $s        = DB::table('store_settings')->pluck('value', 'key');
        $adminTo  = $s->get('store_email') ?: config('mail.from.address');
        if (!$adminTo) return;

        $this->configure();

        try {
            Mail::to($adminTo)->send(new NewOrderAdmin($order));
        } catch (\Throwable $e) {
            Log::error("NewOrderAdmin mail failed for {$order->order_number}: " . $e->getMessage());
        }
    }
}
