<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Models\EmployeeProcess;
use App\Models\EmployeeProcessTask;
use App\Models\ProcessTemplate;
use App\Models\ProcessTemplateTask;
use Carbon\Carbon;
use Illuminate\Http\Request;

class EmployeeProcessController extends Controller
{
    public function index()
    {
        $type = request('type');
        $query = EmployeeProcess::with(['employee', 'template'])->latest();
        if (in_array($type, ['onboarding', 'offboarding'])) {
            $query->where('type', $type);
        }
        $processes = $query->paginate(10);
        return view('processes.index', compact('processes', 'type'));
    }

    public function create()
    {
        $employees = Employee::where('status', 'active')->get();
        $templates = ProcessTemplate::where('active', true)->get();
        return view('processes.create', compact('employees', 'templates'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'type' => 'required|in:onboarding,offboarding',
            'start_date' => 'required|date',
            'process_template_id' => 'nullable|exists:process_templates,id',
        ]);

        $process = EmployeeProcess::create($request->only('employee_id', 'type', 'start_date', 'process_template_id') + [
            'status' => 'in_progress'
        ]);

        if ($request->filled('process_template_id')) {
            $template = ProcessTemplate::with('tasks')->find($request->process_template_id);
            foreach ($template->tasks as $t) {
                EmployeeProcessTask::create([
                    'employee_process_id' => $process->id,
                    'process_template_task_id' => $t->id,
                    'title' => $t->title,
                    'description' => $t->description,
                    'due_date' => Carbon::parse($process->start_date)->addDays($t->due_days_offset),
                    'required' => $t->required,
                    'order' => $t->order,
                    'status' => 'pending',
                ]);
            }
        }

        return redirect()->route('processes.show', $process)->with('success', 'Process started.');
    }

    public function show(EmployeeProcess $process)
    {
        $process->load(['employee', 'tasks' => function ($q) {
            $q->orderBy('order');
        }]);
        return view('processes.show', compact('process'));
    }

    public function update(Request $request, EmployeeProcess $process)
    {
        $request->validate([
            'status' => 'required|in:pending,in_progress,completed,cancelled',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $process->update($request->only('status', 'end_date'));

        return redirect()->back()->with('success', 'Process updated.');
    }

    public function destroy(EmployeeProcess $process)
    {
        $process->delete();
        return redirect()->route('processes.index')->with('success', 'Process deleted.');
    }

    public function completeTask(EmployeeProcessTask $task)
    {
        $task->update([
            'status' => 'completed',
            'completed_at' => now(),
        ]);

        $process = $task->process;
        $remaining = $process->tasks()->where('status', 'pending')->count();
        if ($remaining === 0) {
            $process->update([
                'status' => 'completed',
                'end_date' => now()->toDateString(),
            ]);
        }

        return redirect()->route('processes.show', $process)->with('success', 'Task completed.');
    }
}
