<?php

namespace App\Core\Services\Invoice;

use App\Core\Repositories\InvoiceRepository;
use App\Models\Invoice;
use App\Models\InvoiceReminder;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

/**
 * Reminder Service
 * Handles invoice due reminders
 */
class ReminderService
{
    public function __construct(
        private InvoiceRepository $invoiceRepository
    ) {}

    /**
     * Send due reminders
     */
    public function sendDueReminders(): int
    {
        $count = 0;
        $overdueInvoices = $this->invoiceRepository->getOverdue();
        $dueSoonInvoices = $this->invoiceRepository->getDueSoon(7);

        // Send overdue reminders
        foreach ($overdueInvoices as $invoice) {
            if ($this->shouldSendReminder($invoice, 'overdue')) {
                $this->sendReminder($invoice, 'overdue');
                $count++;
            }
        }

        // Send due soon reminders
        foreach ($dueSoonInvoices as $invoice) {
            if ($this->shouldSendReminder($invoice, 'before_due')) {
                $this->sendReminder($invoice, 'before_due', 7);
                $count++;
            }
        }

        return $count;
    }

    /**
     * Send a reminder for an invoice
     */
    public function sendReminder(Invoice $invoice, string $type, ?int $daysBefore = null): bool
    {
        try {
            $reminderDate = match ($type) {
                'before_due' => $invoice->due_date->subDays($daysBefore ?? 0),
                'on_due' => $invoice->due_date,
                'after_due', 'overdue' => now(),
                default => now(),
            };

            // Create reminder record
            $reminder = InvoiceReminder::create([
                'invoice_id' => $invoice->id,
                'type' => $type,
                'days_before' => $daysBefore,
                'reminder_date' => $reminderDate,
                'status' => 'pending',
                'message' => $this->generateReminderMessage($invoice, $type),
                'created_by' => auth()->id(),
            ]);

            // Send email (implement email sending logic)
            // Mail::to($invoice->customer->email)->send(new InvoiceReminderMail($invoice, $reminder));

            $reminder->update([
                'status' => 'sent',
                'sent_at' => now(),
            ]);

            return true;
        } catch (\Exception $e) {
            Log::error("Reminder sending failed for invoice {$invoice->id}: ".$e->getMessage());

            return false;
        }
    }

    /**
     * Check if reminder should be sent
     */
    private function shouldSendReminder(Invoice $invoice, string $type): bool
    {
        // Check if reminder already sent for this type
        $existingReminder = InvoiceReminder::where('invoice_id', $invoice->id)
            ->where('type', $type)
            ->where('status', 'sent')
            ->exists();

        return ! $existingReminder;
    }

    /**
     * Generate reminder message
     */
    private function generateReminderMessage(Invoice $invoice, string $type): string
    {
        $messages = [
            'before_due' => "Reminder: Invoice {$invoice->invoice_number} is due soon.",
            'on_due' => "Reminder: Invoice {$invoice->invoice_number} is due today.",
            'after_due' => "Reminder: Invoice {$invoice->invoice_number} is overdue.",
            'overdue' => "Urgent: Invoice {$invoice->invoice_number} is overdue. Please pay immediately.",
        ];

        return $messages[$type] ?? "Reminder: Invoice {$invoice->invoice_number} requires attention.";
    }
}
