<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\TaskTemplate;
use App\Models\Task;
use Carbon\Carbon;

class GenerateDailyTasks extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:generate-daily-tasks';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate daily tasks from templates based on the current day of the week';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $today = Carbon::today();
        $dayOfWeek = $today->dayOfWeekIso; // 1 (Mon) - 7 (Sun)

        // Find templates that have the current day of week configured
        $templates = TaskTemplate::whereHas('days', function ($query) use ($dayOfWeek) {
            $query->where('day_of_week', $dayOfWeek);
        })->get();
        
        $count = 0;

        foreach ($templates as $template) {
            // Only create if it doesn't already exist for today
            $exists = Task::where('task_template_id', $template->id)
                          ->where('user_id', $template->user_id)
                          ->where('date', $today->toDateString())
                          ->exists();

            if (!$exists) {
                Task::create([
                    'user_id' => $template->user_id,
                    'task_template_id' => $template->id,
                    'date' => $today->toDateString(),
                    'status' => 'todo'
                ]);
                $count++;
            }
        }

        $this->info("Successfully generated {$count} tasks for today!");
    }
}
