<?php

namespace App\Console\Commands;

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

class MarkOverdueInvoices extends Command
{
    protected $signature   = 'invotrack:mark-overdue';
    protected $description = 'Mark unpaid invoices past their due date as overdue and notify business owners';

    public function handle(): int
    {
        $this->info('Checking for overdue invoices...');

        // Find all sent/viewed invoices whose due date has passed
        $overdueInvoices = Invoice::whereIn('status', ['sent', 'viewed'])
            ->where('due_date', '<', now()->toDateString())
            ->with(['client', 'user'])
            ->get();

        if ($overdueInvoices->isEmpty()) {
            $this->info('No new overdue invoices found.');
            return self::SUCCESS;
        }

        $count = 0;

        foreach ($overdueInvoices as $invoice) {
            try {
                // Update status to overdue
                $invoice->update(['status' => 'overdue']);

                // Send overdue notice to client (if they have email)
                if ($invoice->client->email && $invoice->user->notify_overdue) {
                    $this->sendOverdueNotice($invoice);
                }

                $count++;
                $this->line("  ✓ Marked overdue: {$invoice->invoice_number} ({$invoice->client->display_name})");

            } catch (\Exception $e) {
                Log::error("Failed to process overdue invoice {$invoice->invoice_number}: " . $e->getMessage());
                $this->error("  ✗ Failed: {$invoice->invoice_number} — {$e->getMessage()}");
            }
        }

        $this->info("Done. {$count} invoice(s) marked as overdue.");
        return self::SUCCESS;
    }

    private function sendOverdueNotice(Invoice $invoice): void
    {
        // Check if we already sent an overdue_1 notice today
        $alreadySent = $invoice->reminders()
            ->where('reminder_type', 'overdue_1')
            ->whereDate('sent_at', today())
            ->exists();

        if ($alreadySent) {
            return;
        }

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

            // Record that we sent it
            Reminder::create([
                'invoice_id'    => $invoice->id,
                'reminder_type' => 'overdue_1',
                'sent_at'       => now(),
                'success'       => true,
            ]);

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

            Log::error("Overdue notice failed for {$invoice->invoice_number}: " . $e->getMessage());
        }
    }
}
