<?php

namespace App\Http\Controllers;

use App\Models\ProcessTemplate;
use App\Models\ProcessTemplateTask;
use Illuminate\Http\Request;

class ProcessTemplateController extends Controller
{
    public function index()
    {
        $templates = ProcessTemplate::withCount('tasks')->latest()->paginate(10);
        return view('process_templates.index', compact('templates'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:onboarding,offboarding',
        ]);

        $template = ProcessTemplate::create($request->only('name', 'type') + ['active' => true]);

        if ($request->has('tasks')) {
            foreach ($request->input('tasks', []) as $order => $task) {
                ProcessTemplateTask::create([
                    'process_template_id' => $template->id,
                    'title' => $task['title'] ?? '',
                    'description' => $task['description'] ?? null,
                    'due_days_offset' => (int)($task['due_days_offset'] ?? 0),
                    'required' => (bool)($task['required'] ?? true),
                    'order' => $order,
                ]);
            }
        }

        return redirect()->route('process-templates.index')->with('success', 'Template created.');
    }

    public function edit(ProcessTemplate $processTemplate)
    {
        $template = $processTemplate->load('tasks');
        return view('process_templates.edit', compact('template'));
    }

    public function update(Request $request, ProcessTemplate $processTemplate)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:onboarding,offboarding',
            'active' => 'boolean',
        ]);

        $processTemplate->update($request->only('name', 'type', 'active'));

        $processTemplate->tasks()->delete();
        foreach ($request->input('tasks', []) as $order => $task) {
            ProcessTemplateTask::create([
                'process_template_id' => $processTemplate->id,
                'title' => $task['title'] ?? '',
                'description' => $task['description'] ?? null,
                'due_days_offset' => (int)($task['due_days_offset'] ?? 0),
                'required' => (bool)($task['required'] ?? true),
                'order' => $order,
            ]);
        }

        return redirect()->route('process-templates.index')->with('success', 'Template updated.');
    }

    public function destroy(ProcessTemplate $processTemplate)
    {
        $processTemplate->delete();
        return redirect()->route('process-templates.index')->with('success', 'Template deleted.');
    }
}
