<?php

namespace App\Http\Controllers;

use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        Gate::authorize('view projects');

        return view('projects.index');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        Gate::authorize('create projects');
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'address' => 'required',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
            'start_date' => 'required|date',
            'end_date_estimated' => 'nullable|date',
        ]);
        $project = Project::create(array_merge($validated, ['created_by' => Auth::id(), 'status' => 'planning']));

        // Assign creator as supervisor in project
        $project->users()->attach(Auth::id(), ['role_in_project' => 'supervisor']);

        return redirect()->route('projects.map', $project)->with('success', 'Proyecto creado');
    }

    /**
     * Display the specified resource.
     */
    public function show(Project $project)
    {
        // No usamos show, redirigimos al mapa
        return redirect()->route('projects.map', $project);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Project $project)  // <--- ROUTE MODEL BINDING
    {
        Gate::authorize('edit projects', $project);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'address' => 'required|string',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
            'status' => 'required|in:planning,in_progress,paused,completed',
            'start_date' => 'required|date',
            'end_date_estimated' => 'nullable|date|after:start_date',
        ]);

        $project->update($validated);

        return redirect()->route('projects.index')
            ->with('success', 'Proyecto actualizado correctamente.');
    }

    /**
     * Remove the specified project from storage.
     */
    public function destroy(Project $project)  // <--- ROUTE MODEL BINDING
    {
        Gate::authorize('delete projects', $project);

        $project->delete();

        return redirect()->route('projects.index')
            ->with('success', 'Proyecto eliminado correctamente.');
    }

    /**
     * Show the map view for a specific project.
     */
    public function map(Project $project)
    {
        // Cualquier usuario autenticado puede ver el mapa si tiene acceso al proyecto
        // (lo validaremos dentro del componente Livewire)
        return view('projects.map', compact('project'));
    }
}
