<?php

namespace App\Console\Commands;

use App\Models\Setting;
use App\Models\Ticket;
use App\Models\TicketStatus;
use Illuminate\Console\Command;

class SendTicketRatingReminders extends Command
{
    protected $signature = 'tickets:send-rating-reminders';
    protected $description = 'Send rating reminder emails for closed tickets that have not been rated';

    public function handle(): int
    {
        if (!Setting::get('support_ticket_rating', false)) {
            $this->info('Ticket rating is disabled.');
            return 0;
        }

        // PRC-340 — rating is voluntary; the reminder is sent whenever
        // rating is enabled and the client hasn't rated yet (no
        // ticket_rating_required gate anymore).

        $days = (int) Setting::get('ticket_rating_reminder_days', 3);
        if ($days <= 0) {
            $this->info('Rating reminder days is 0, skipping.');
            return 0;
        }

        $targetDate = now()->subDays($days);

        $closedStatusIds = TicketStatus::where('is_closed', true)->pluck('id');

        $tickets = Ticket::whereIn('status_id', $closedStatusIds)
            ->whereNotNull('client_id')
            ->whereNull('rating_reminder_sent_at')
            ->whereDoesntHave('rating')
            ->whereHas('replies', function ($q) {
                $q->whereNotNull('admin_id');
            })
            ->where('updated_at', '<=', $targetDate)
            ->where('updated_at', '>=', $targetDate->copy()->subDays(30))
            ->get();

        $count = 0;
        foreach ($tickets as $ticket) {
            \App\Jobs\SendEmailJob::dispatch(
                'Support Ticket Rating Reminder',
                'ticket',
                $ticket->id
            );

            $ticket->update(['rating_reminder_sent_at' => now()]);
            $count++;
        }

        $this->info("Sent {$count} rating reminder emails.");

        return 0;
    }
}
