<?php

namespace App\Console\Commands;

use App\Models\Invoice;
use App\Models\Quotation;
use App\Models\ReminderSetting;
use App\Services\ReminderService;
use Illuminate\Console\Command;

/**
 * Smart billing automation: due soon, overdue invoices, quotation expiry windows.
 * Schedule: * * * * * php artisan schedule:run  (see routes/console.php)
 */
class ProcessRemindersCommand extends Command
{
    protected $signature = 'reminders:process {--dry-run : Log actions without sending}';

    protected $description = 'Process scheduled invoice and quotation email reminders';

    public function handle(ReminderService $reminders): int
    {
        $dry = (bool) $this->option('dry-run');
        $settings = ReminderSetting::current();
        $sent = 0;

        $dueDays = max(0, (int) $settings->due_reminder_days_before);
        $targetDueDate = now()->addDays($dueDays)->toDateString();

        $expiryDays = max(0, (int) $settings->quotation_expiry_days_before);
        $targetExpiryDate = now()->addDays($expiryDays)->toDateString();

        if ($dry) {
            $this->warn('Dry run — no emails will be queued.');
        }

        // Due soon
        if ($settings->enable_invoice_due_reminder) {
            $dueSoon = Invoice::query()
                ->with('customer')
                ->whereDate('due_date', $targetDueDate)
                ->whereNotIn('status', ['paid', 'cancelled', 'draft'])
                ->where('balance', '>', 0)
                ->get();

            foreach ($dueSoon as $invoice) {
                if ($dry) {
                    $this->line("Due soon: {$invoice->invoice_number}");
                    $sent++;

                    continue;
                }
                $reminders->sendInvoiceDueSoon($invoice);
                $sent++;
            }
        }

        // Overdue
        if ($settings->enable_invoice_overdue_reminder) {
            $overdue = Invoice::query()
                ->with('customer')
                ->whereDate('due_date', '<', now()->toDateString())
                ->whereNotIn('status', ['paid', 'cancelled', 'draft'])
                ->where('balance', '>', 0)
                ->get();

            foreach ($overdue as $invoice) {
                if ($dry) {
                    $this->line("Overdue: {$invoice->invoice_number}");
                    $sent++;

                    continue;
                }
                $reminders->sendInvoiceOverdue($invoice);
                $sent++;
            }
        }

        // Quotation expiry
        if ($settings->enable_quotation_expiry) {
            $quotes = Quotation::query()
                ->with('customer')
                ->whereDate('expiry_date', $targetExpiryDate)
                ->whereNotIn('status', ['converted', 'rejected', 'cancelled', 'draft'])
                ->get();

            foreach ($quotes as $q) {
                if ($dry) {
                    $this->line("Quotation expiry: {$q->quotation_number}");
                    $sent++;

                    continue;
                }
                $reminders->sendQuotationExpiry($q);
                $sent++;
            }
        }

        $this->info($dry ? "Dry run complete ({$sent} candidate rows)." : "Reminder pass complete ({$sent} processed).");

        return self::SUCCESS;
    }
}
