<?php

namespace App\Http\Controllers;

use App\Enums\ProjectStatus;
use App\Models\Project;
use App\Services\ProjectService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ProjectController extends Controller
{
    public function __construct(
        private ProjectService $projectService
    ) {}

    public function store(Request $request)
    {
        $validated = $request->validate([
            'naam' => 'required|string|max:255',
            'beschrijving' => 'nullable|string',
            'speerpunt_id' => 'nullable|exists:speerpunten,id',
            'prioriteit' => 'nullable|string',
            'startdatum' => 'nullable|date',
            'streef_einddatum' => 'nullable|date|after:startdatum',
        ]);

        $project = $this->projectService->create($validated);

        return back()->with('success', "Project '{$project->naam}' aangemaakt.");
    }

    public function show(Project $project)
    {
        $project = $this->projectService->getWithDetails($project->id);

        return Inertia::render('Project/Show', [
            'project' => $project,
        ]);
    }

    public function update(Request $request, Project $project)
    {
        $validated = $request->validate([
            'naam' => 'sometimes|string|max:255',
            'beschrijving' => 'nullable|string',
            'prioriteit' => 'nullable|string',
            'speerpunt_id' => 'nullable|exists:speerpunten,id',
            'streef_einddatum' => 'nullable|date',
        ]);

        $this->projectService->update($project, $validated);

        return back()->with('success', 'Project bijgewerkt.');
    }

    public function transition(Request $request, Project $project)
    {
        $validated = $request->validate([
            'status' => 'required|string',
        ]);

        $newStatus = ProjectStatus::from($validated['status']);
        $this->projectService->transitionPhase($project, $newStatus);

        return back()->with('success', 'Projectfase bijgewerkt.');
    }

    public function park(Request $request, Project $project)
    {
        $reason = $request->input('reason', '');
        $this->projectService->park($project, $reason);

        return back()->with('success', 'Project geparkeerd.');
    }

    public function stop(Request $request, Project $project)
    {
        $reason = $request->input('reason', '');
        $this->projectService->stop($project, $reason);

        return back()->with('success', 'Project gestopt.');
    }

    public function destroy(Project $project)
    {
        $project->delete();

        return redirect('/map')->with('success', 'Project verwijderd.');
    }
}
