<?php

namespace App\Http\Controllers;

use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $projects = Project::paginate(10);
        return view('projects.index', compact('projects'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('projects.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'folder_path' => 'required|string|max:255|regex:/^[a-zA-Z0-9_\-\/]+$/',
            'status' => 'required|in:active,inactive',
        ]);

        $folderPath = $request->folder_path;

        // Verificar si la carpeta ya existe
        if (Storage::exists($folderPath)) {
            return redirect()->back()->withErrors(['folder_path' => 'The folder path already exists.']);
        }

        // Crear la carpeta en el sistema de archivos
        try {
            Storage::makeDirectory($folderPath);
        } catch (\Exception $e) {
            return redirect()->back()->withErrors(['folder_path' => 'Failed to create folder. Please try again.']);
        }

        // Crear el proyecto en la base de datos
        Project::create([
            'name' => $request->name,
            'token' => Str::uuid()->toString(),
            'folder_path' => $folderPath,
            'status' => $request->status,
        ]);

        return redirect()->route('projects.index')->with('success', 'Project created successfully, and folder has been created.');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Project $project)
    {
        return view('projects.edit', compact('project'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Project $project)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'folder_path' => 'required|string|max:255|regex:/^[a-zA-Z0-9_\-\/]+$/',
            'status' => 'required|in:active,inactive',
        ]);

        $newFolderPath = $request->folder_path;

        // Si cambia el nombre de la carpeta, renombrarla
        if ($project->folder_path !== $newFolderPath) {
            // Verificar si ya existe un directorio con el nuevo nombre
            if (Storage::exists($newFolderPath)) {
                return redirect()->back()->withErrors(['folder_path' => 'The new folder path already exists.']);
            }

            try {
                Storage::move($project->folder_path, $newFolderPath);
            } catch (\Exception $e) {
                return redirect()->back()->withErrors(['folder_path' => 'Failed to rename folder. Please try again.']);
            }
        }

        // Actualizar el proyecto en la base de datos
        $project->update([
            'name' => $request->name,
            'folder_path' => $newFolderPath,
            'status' => $request->status,
        ]);

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Project $project)
    {
        // Eliminar el directorio asociado
        try {
            Storage::deleteDirectory($project->folder_path);
        } catch (\Exception $e) {
            return redirect()->route('projects.index')->withErrors(['error' => 'Failed to delete folder.']);
        }

        // Eliminar el proyecto en la base de datos
        $project->delete();

        return redirect()->route('projects.index')->with('success', 'Project deleted successfully.');
    }
}
