<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProjectController extends Controller
{
    use AuthorizesRequests; // ← Añadir este trait

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $projects = auth()->user()->hasRole('admin') 
            ? Project::get()  // Todos los proyectos para admin
            : auth()->user()->projects()->latest()->get(); // Solo proyectos asignados

        /*
        $projects = Project::whereHas('users', function($query) {
            $query->where('user_id', auth()->id());
        })
        ->filter(['search' => request('search')])
        ->paginate(9);*/

        return view('projects.index', compact('projects'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $this->authorize('create projects');
        $project = new Project();
        return view('projects.create', [
            'project' => $project,
            'categories' => Category::orderBy('name')->get(),
            'users' => User::where('id', '!=', auth()->id())->get(),
            'companies' => \App\Models\Company::all(), // Pass companies to the view
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'reference' => 'required|string|max:255',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'status' => 'required|in:Activo,Inactivo',
            'address' => 'nullable|string|max:255',
            'province' => 'nullable|string|max:100',
            'country' => 'nullable|string|size:2',
            'postal_code' => 'nullable|string|max:10',
            'latitude' => 'required|numeric|between:-90,90',
            'longitude' => 'required|numeric|between:-180,180',
            'start_date' => 'nullable|date',
            'deadline' => 'nullable|date|after:start_date',
            'categories' => 'nullable|array|exists:categories,id',
            'project_image_path' => 'nullable|string',
            'company_id' => 'required|exists:companies,id', // Validate company_id
        ]);

        
        try {
            // Combinar datos del usuario autenticado
            $validated = array_merge($validated, [
                'creator_id' => auth()->id()
            ]);
    
            // Manejar la imagen
            if ($request->has('project_image_path') && $request->project_image_path) {
                $tempPath = $request->project_image_path;
                $newPath = 'images/projects/' . basename($tempPath);
                
                Storage::move($tempPath, $newPath);             // Mover el archivo
                $validated['project_image_path'] = $newPath;    // Actualizar path
            }
            
            // Crear el proyecto con todos los datos validados
            $project = Project::create($validated);
    
            // Adjuntar categorías
            if($request->has('categories')) {
                $project->categories()->sync($request->categories);
            }
    
            return redirect()->route('projects.show', $project)->with('success', 'Proyecto creado exitosamente');
    
        } catch (\Exception $e) {
            return back()->withInput()->with('error', 'Error al crear el proyecto: ' . $e->getMessage());
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Project $project)
    {
        $this->authorize('update', $project);
        return view('projects.create', [
            'project' => $project,
            'categories' => Category::orderBy('name')->get(),
            'users' => User::where('id', '!=', auth()->id())->get(),
            'companies' => \App\Models\Company::all(), // Pass companies to the view
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function show(Project $project)
    {
        //$this->authorize('view', $project); // Si usas políticas
        $project->load(['categories', 'documents']);
        
        return view('projects.show', [
            'project' => $project->load(['rootFolders', 'documents', 'categories']),
            'documents' => $project->documents()->paginate(10),
        ]);
    }


    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Project $project)
    {
        $this->authorize('update', $project);

        $validated = $request->validate([
            'reference' => 'required|string|max:255',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'status' => 'required|in:Activo,Inactivo',
            'address' => 'nullable|string|max:255',
            'province' => 'nullable|string|max:100',
            'country' => 'nullable|string|size:2',
            'postal_code' => 'nullable|string|max:10',
            'latitude' => 'required|numeric|between:-90,90',
            'longitude' => 'required|numeric|between:-180,180',
            'start_date' => 'nullable|date',
            'deadline' => 'nullable|date|after:start_date',
            'categories' => 'nullable|array|exists:categories,id',
            'project_image_path' => 'nullable|string',
            'company_id' => 'required|exists:companies,id', // Validate company_id
        ]);

        $project->update($validated);

        if ($request->has('categories')) {
            $project->categories()->sync($request->categories);
        }

        return redirect()->route('projects.show', $project)->with('success', 'Project updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Project $project)
    {
        //
    }

    public function __invoke(Project $project)
    {
        return view('projects.show', [
            'project' => $project
        ]);
    }
}
