<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\TaskTemplate;
use App\Models\Task;
use Carbon\Carbon;

class TaskTemplateController extends Controller
{
    public function index()
    {
        $user = auth()->user() ?? \App\Models\User::first();
        $templates = TaskTemplate::where('user_id', $user->id)->with('days')->get();
        return view('templates.index', compact('templates'));
    }

    public function create()
    {
        return view('templates.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'days' => 'required|array|min:1',
            'days.*' => 'integer|min:1|max:7',
        ]);

        $user = auth()->user() ?? \App\Models\User::first();

        $template = TaskTemplate::create([
            'user_id' => $user->id,
            'title' => $request->title,
            'description' => $request->description,
        ]);

        $daysData = [];
        foreach ($request->days as $day) {
            $daysData[] = ['day_of_week' => $day];
        }
        
        $template->days()->createMany($daysData);

        // Auto-generate task for today if it matches the chosen days
        $today = Carbon::today();
        $currentDayOfWeek = $today->dayOfWeekIso;
        
        if (in_array($currentDayOfWeek, $request->days)) {
            Task::create([
                'user_id' => $user->id,
                'task_template_id' => $template->id,
                'date' => $today->toDateString(),
                'status' => 'todo'
            ]);
        }

        return redirect()->route('templates.index')->with('success', 'Task template created!');
    }

    public function edit(TaskTemplate $template)
    {
        $template->load('days');
        return view('templates.edit', compact('template'));
    }

    public function update(Request $request, TaskTemplate $template)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'days' => 'required|array|min:1',
            'days.*' => 'integer|min:1|max:7',
        ]);

        $template->update([
            'title' => $request->title,
            'description' => $request->description,
        ]);

        $template->days()->delete();
        
        $daysData = [];
        foreach ($request->days as $day) {
            $daysData[] = ['day_of_week' => $day];
        }
        $template->days()->createMany($daysData);

        // Auto-generate task for today if newly added and matches
        $today = Carbon::today();
        $currentDayOfWeek = $today->dayOfWeekIso;
        
        if (in_array($currentDayOfWeek, $request->days)) {
            // Check if task already exists 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'
                ]);
            }
        }

        return redirect()->route('templates.index')->with('success', 'Task template updated!');
    }

    public function destroy(TaskTemplate $template)
    {
        // Delete tasks for today and future days
        $today = Carbon::today()->toDateString();
        Task::where('task_template_id', $template->id)
            ->where('date', '>=', $today)
            ->delete();
            
        $template->delete();
        return redirect()->route('templates.index')->with('success', 'Task template deleted!');
    }
}
