<?php

namespace App\Console\Commands;

use App\Mail\PaymentReminder;
use App\Models\Invoice;
use App\Models\Reminder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class SendPaymentReminders extends Command
{
    protected $signature   = 'invotrack:send-reminders';
    protected $description = 'Send payment reminder emails for invoices due in 3 days or 1 day';

    public function handle(): int
    {
        $this->info('Sending payment reminders...');

        $reminderDays = config('invotrack.reminder_days_before', [3, 1]);
        $totalSent    = 0;

        foreach ($reminderDays as $daysAhead) {
            $targetDate = now()->addDays($daysAhead)->toDateString();
            $type       = "before_due"; // same type, different timing

            $invoices = Invoice::whereIn('status', ['sent', 'viewed'])
                ->whereDate('due_date', $targetDate)
                ->with(['client', 'user'])
                ->get();

            foreach ($invoices as $invoice) {
                // Skip if user has reminders turned off
                if (! $invoice->user->notify_payment_reminder) {
                    continue;
                }

                // Skip if no client email
                if (! $invoice->client->email) {
                    continue;
                }

                // Skip if user is on free plan (no reminders)
                if (! $invoice->user->canUseReminders()) {
                    continue;
                }

                // Check if we already sent a reminder for this invoice today
                $alreadySent = $invoice->reminders()
                    ->whereDate('sent_at', today())
                    ->where('reminder_type', $type)
                    ->exists();

                if ($alreadySent) {
                    $this->line("  ⟳ Already sent: {$invoice->invoice_number}");
                    continue;
                }

                try {
                    Mail::to($invoice->client->email)
                        ->send(new PaymentReminder($invoice));

                    Reminder::create([
                        'invoice_id'    => $invoice->id,
                        'reminder_type' => $type,
                        'sent_at'       => now(),
                        'success'       => true,
                    ]);

                    $totalSent++;
                    $this->line("  ✓ Reminder sent ({$daysAhead}d before due): {$invoice->invoice_number} → {$invoice->client->email}");

                } catch (\Exception $e) {
                    Reminder::create([
                        'invoice_id'    => $invoice->id,
                        'reminder_type' => $type,
                        'sent_at'       => now(),
                        'success'       => false,
                        'error_message' => $e->getMessage(),
                    ]);

                    Log::error("Reminder failed for {$invoice->invoice_number}: " . $e->getMessage());
                    $this->error("  ✗ Failed: {$invoice->invoice_number}");
                }
            }
        }

        $this->info("Done. {$totalSent} reminder(s) sent.");
        return self::SUCCESS;
    }
}
