<?php

namespace App\Console\Commands;

use App\Mail\TaskReminderMail;
use App\Models\Task;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Mail;

class SendTaskReminders extends Command
{
    protected $signature = 'tasks:send-reminders';
    protected $description = 'Kirim email reminder untuk task yang belum selesai sesuai frekuensi';

    public function handle(): int
    {
        $now = Carbon::now();

        $tasks = Task::query()
            ->where('status', '!=', 'Selesai')
            ->get();

        $count = 0;

        foreach ($tasks as $task) {
            $shouldSend = false;

            if (!$task->last_reminded_at) {
                $shouldSend = true;
            } else {
                $nextDue = Carbon::parse($task->last_reminded_at)->addHours($task->reminder_frequency_hours);
                if ($now->greaterThanOrEqualTo($nextDue)) {
                    $shouldSend = true;
                }
            }

            if ($shouldSend) {
                $emails = $task->reminder_emails ?? [];
                if (!is_array($emails)) {
                    $emails = [];
                }
                if ($task->reminder_email) {
                    $emails[] = $task->reminder_email;
                }
                $emails = array_unique(array_filter($emails));

                if (!empty($emails)) {
                    Mail::to($emails)->send(new TaskReminderMail($task));
                    $task->last_reminded_at = $now;
                    $task->save();
                    $count++;
                }
            }
        }

        $this->info("Reminder terkirim untuk {$count} task.");
        return Command::SUCCESS;
    }
}

