<?php

namespace Modules\WhatsApp\Console;

use App\Transaction;
use Illuminate\Console\Command;
use Modules\WhatsApp\Entities\Services\WaNotifier;

/**
 * Reminds customers about overdue, unpaid credit invoices. Only targets sells
 * that have a payment term (a real due date), are still due/partial, and whose
 * computed due_date has passed. Deduped per invoice per day, so running daily
 * sends at most one reminder per invoice per day.
 *
 * Schedule: daily (e.g. 09:00).
 */
class SendPaymentReminders extends Command
{
    protected $signature = 'whatsapp:payment-reminders {--limit=1000}';
    protected $description = 'Send WhatsApp reminders for overdue, unpaid invoices.';

    public function handle(WaNotifier $notifier): int
    {
        $limit = (int) $this->option('limit');
        $today = now()->startOfDay();
        $sent = 0;

        Transaction::where('type', 'sell')
            ->where('status', 'final')
            ->whereIn('payment_status', ['due', 'partial'])
            ->whereNotNull('pay_term_number')
            ->where('pay_term_number', '>', 0)
            ->where('transaction_date', '>=', now()->subMonths(6))
            ->with(['contact', 'payment_lines'])
            ->orderBy('id')
            ->limit($limit)
            ->chunkById(200, function ($transactions) use ($notifier, $today, &$sent) {
                foreach ($transactions as $t) {
                    $due = $t->due_date; // computed accessor (transaction_date + pay term)
                    if (empty($due) || $due->gte($today)) {
                        continue; // not overdue yet
                    }
                    $notifier->paymentDue($t);
                    $sent++;
                }
            });

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