<?php

namespace Mtc\Modules\B2B\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Mtc\Modules\B2B\Enums\AccountOrderStatus;
use Mtc\Modules\B2B\Models\AccountOrder;

class SendOverdueReminders extends Command
{
    protected $signature = 'b2b:send-overdue-reminders';
    protected $description = 'Send overdue payment reminders for unpaid account orders';

    public function handle(): int
    {
        $overdueDays = config('b2b.overdue_days', 30);
        $reminderIntervalDays = config('b2b.reminder_interval_days', 7);
        $cutoffDate = Carbon::now()->subDays($overdueDays);
        $reminderCutoff = Carbon::now()->subDays($reminderIntervalDays);

        // Only send a reminder if no reminder has been sent yet,
        // or if the last one was sent more than $reminderIntervalDays ago.
        $overdueOrders = AccountOrder::where('status', AccountOrderStatus::Unpaid->value)
            ->where('created_at', '<', $cutoffDate)
            ->where(function ($q) use ($reminderCutoff) {
                $q->whereNull('last_reminder_sent_at')
                  ->orWhere('last_reminder_sent_at', '<', $reminderCutoff);
            })
            ->with(['tradeCustomer.member'])
            ->get();

        if ($overdueOrders->isEmpty()) {
            $this->info('No overdue orders found.');
            return 0;
        }

        $twig = app('twig');
        $sentCount = 0;

        foreach ($overdueOrders as $accountOrder) {
            $tradeCustomer = $accountOrder->tradeCustomer;
            if (!$tradeCustomer || !$tradeCustomer->member) {
                continue;
            }

            $html = $twig->render('b2b/emails/account_payment_overdue.twig', [
                'account_order'  => $accountOrder,
                'trade_customer' => $tradeCustomer,
                'member'         => $tradeCustomer->member,
            ]);

            try {
                email(
                    $tradeCustomer->member->email,
                    'Payment Reminder - ' . $accountOrder->po_number,
                    $html
                );
                $accountOrder->update(['last_reminder_sent_at' => now()]);
                $sentCount++;
            } catch (\Throwable $e) {
                $this->warn("Failed to send reminder for {$accountOrder->po_number}: {$e->getMessage()}");
            }
        }

        $this->info("Sent {$sentCount} overdue reminder(s).");
        return 0;
    }
}
