<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\Company;
use App\Models\User;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $user = auth()->user();
        
        if ($user->role === 'administrador') {
            $projects = Project::with(['company'])->get();
        } elseif (in_array($user->role, ['responsable', 'ingeniero', 'supervisor'])) {
            // Ver solo proyectos asignados
            $projects = $user->projects()->with(['company'])->get();
        } else {
            // Clientes ven solo su proyecto
            $projects = Project::where('id', $user->project_id)->with(['company'])->get();
        }
        
        return view('projects.index', compact('projects'));
    }

    public function create()
    {
        if (!auth()->user()->hasRole(['administrador', 'supervisor'])) {
            abort(403, 'No autorizado');
        }
        
        $companies = Company::where('is_active', true)->get();
        $users = User::whereIn('role', ['responsable', 'ingeniero', 'supervisor'])->get();
        
        return view('projects.create', compact('companies', 'users'));
    }

    public function store(Request $request)
    {
        if (!auth()->user()->hasRole(['administrador', 'supervisor'])) {
            abort(403, 'No autorizado');
        }
        
        $request->validate([
            'company_id' => 'required|exists:companies,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'status' => 'required|in:activo,inactivo,completado',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $project = Project::create($request->all());

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

    public function show(Project $project)
    {
        $project->load(['company', 'tickets.requester', 'tickets.assignedUser']);
        
        return view('projects.show', compact('project'));
    }

    public function edit(Project $project)
    {
        if (!auth()->user()->hasRole(['administrador', 'supervisor'])) {
            abort(403, 'No autorizado');
        }
        
        $companies = Company::where('is_active', true)->get();
        $users = User::whereIn('role', ['responsable', 'ingeniero', 'supervisor'])->get();
        
        return view('projects.edit', compact('project', 'companies', 'users'));
    }

    public function update(Request $request, Project $project)
    {
        if (!auth()->user()->hasRole(['administrador', 'supervisor'])) {
            abort(403, 'No autorizado');
        }
        
        $request->validate([
            'company_id' => 'required|exists:companies,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'status' => 'required|in:activo,inactivo,completado',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $project->update($request->all());

        return redirect()->route('projects.show', $project)->with('success', 'Proyecto actualizado exitosamente');
    }

    public function destroy(Project $project)
    {
        if (!auth()->user()->hasRole(['administrador'])) {
            abort(403, 'No autorizado');
        }
        
        // Verificar si tiene tickets asociados
        if ($project->tickets()->count() > 0) {
            return back()->with('error', 'No se puede eliminar un proyecto con tickets asociados');
        }
        
        $project->delete();

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