<?php

namespace App\Http\Controllers;

use App\Models\Folder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use App\Rules\UniqueFolderName;
use Illuminate\Support\Facades\Gate;

class FolderController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(Folder $folder)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Folder $folder)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Folder $folder, Request $request)
    {
        try {
            // Verificar permisos
            if (!Gate::allows('update', $folder)) {
                return response()->json([
                    'success' => false,
                    'message' => 'No tienes permisos para modificar esta carpeta'
                ], Response::HTTP_FORBIDDEN);
            }

            // Validación
            $validator = Validator::make($request->all(), [
                'name' => [
                    'required',
                    'max:255',
                    new UniqueFolderName(
                        $folder->project_id,
                        $folder->parent_id
                    )
                ]
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            // Actualizar nombre
            $folder->update(['name' => $request->name]);

            return response()->json([
                'success' => true,
                'message' => 'Carpeta actualizada',
                'folder' => $folder
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error al actualizar carpeta: ' . $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Folder $folder)
    {
        try {
            // Verificar permisos
            if (!Gate::allows('delete', $folder)) {
                return response()->json([
                    'success' => false,
                    'message' => 'No tienes permisos para eliminar esta carpeta'
                ], Response::HTTP_FORBIDDEN);
            }

            // Validar que esté vacía
            if ($folder->documents()->exists() || $folder->children()->exists()) {
                return response()->json([
                    'success' => false,
                    'message' => 'No puedes eliminar carpetas con contenido'
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            // Eliminar
            $folder->delete();

            return response()->json([
                'success' => true,
                'message' => 'Carpeta eliminada'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error al eliminar carpeta: ' . $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Move the specified folder to a new location.
     */
    public function move(Folder $folder, Request $request)
    {
        try {
            // Verificar permisos
            if (!Gate::allows('move', $folder)) {
                return response()->json([
                    'success' => false,
                    'message' => 'No tienes permisos para esta acción'
                ], Response::HTTP_FORBIDDEN);
            }

            // Validación
            $validator = Validator::make($request->all(), [
                'parent_id' => 'nullable|exists:folders,id',
                'project_id' => 'required|exists:projects,id'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            // Prevenir movimiento a sí mismo o descendientes
            if ($request->parent_id && $folder->isDescendantOf($request->parent_id)) {
                return response()->json([
                    'success' => false,
                    'message' => 'No puedes mover una carpeta a su propia jerarquía'
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            // Actualizar ubicación
            $folder->update([
                'parent_id' => $request->parent_id,
                'project_id' => $request->project_id
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Carpeta movida exitosamente',
                'folder' => $folder->fresh()
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error al mover la carpeta: ' . $e->getMessage()
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}
