<?php

namespace App\Console\Commands;

use App\Models\Todo;
use App\Notifications\TodoReminderNotification;
use Illuminate\Console\Command;
use Carbon\Carbon;

class SendTodoReminders extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'todo:send-reminders';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send reminders for upcoming todos based on user reminder settings';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Checking for todos that need reminders...');

        // Get all todos that need reminders
        $todos = Todo::needsReminder()->with('user')->get();

        if ($todos->isEmpty()) {
            $this->info('No todos need reminders at this time.');
            return 0;
        }

        $sentCount = 0;

        foreach ($todos as $todo) {
            try {
                // Send database notification to user
                $todo->user->notify(new TodoReminderNotification($todo));

                // Send WhatsApp notification if user has phone and device available
                if (!empty($todo->user->phone)) {
                    $device = \App\Models\Device::where('user_id', $todo->user->id)
                        ->where('status', 'ONLINE')
                        ->first();
                    
                    if ($device) {
                        $message = "⏰ *Todo Reminder*\n\n";
                        $message .= "*{$todo->title}*\n";
                        if ($todo->description) {
                            $message .= "{$todo->description}\n\n";
                        }
                        $message .= "📅 Scheduled: {$todo->todo_time->format('M d, Y h:i A')}\n";
                        $message .= "⏱️ Time remaining: {$todo->todo_time->diffForHumans()}\n";
                        $message .= "🔔 Priority: " . ucfirst($todo->priority);
                        
                        try {
                            \App\Http\Controllers\SendmsgController::sendMessage(
                                $todo->user->phone,
                                $message,
                                $device->sender
                            );
                            $this->info("  → WhatsApp reminder sent to {$todo->user->phone}");
                        } catch (\Exception $e) {
                            $this->warn("  → WhatsApp failed: {$e->getMessage()}");
                        }
                    }
                }

                // Mark reminder as sent
                $todo->markReminderSent();

                $sentCount++;

                $this->info("✓ Sent reminder for todo #{$todo->id}: {$todo->title} (User: {$todo->user->name})");
            } catch (\Exception $e) {
                $this->error("✗ Failed to send reminder for todo #{$todo->id}: " . $e->getMessage());
            }
        }

        $this->info("Completed! Sent {$sentCount} reminder(s).");

        return 0;
    }
}
