<?php

namespace App\Http\Controllers;

use App\Models\Role;
use App\Models\Route;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route as LaravelRoute;
use Illuminate\Support\Facades\Validator;

class RoutePermissionController extends Controller
{
    /**
     * Display a listing of the routes.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $routes = Route::with('roles')->paginate(15);
        $roles = Role::all();
        
        return view('admin.routes.index', compact('routes', 'roles'));
    }

    /**
     * Show the form for creating a new route.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $roles = Role::all();
        return view('admin.routes.create', compact('roles'));
    }

    /**
     * Store a newly created route in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'path' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'is_public' => 'boolean',
            'roles' => 'nullable|array',
            'roles.*' => 'exists:roles,id',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $route = Route::create([
            'path' => $request->path,
            'description' => $request->description,
            'is_public' => $request->is_public ?? false,
        ]);

        if ($request->has('roles')) {
            $route->roles()->sync($request->roles);
        }

        return redirect()->route('routes.index')
            ->with('success', __('common.route-created-successfully'));
    }

    /**
     * Show the form for editing the specified route.
     *
     * @param  \App\Models\Route  $route
     * @return \Illuminate\Http\Response
     */
    public function edit(Route $route)
    {
        $roles = Role::all();
        $selectedRoles = $route->roles->pluck('id')->toArray();
        
        return view('admin.routes.edit', compact('route', 'roles', 'selectedRoles'));
    }

    /**
     * Update the specified route in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Route  $route
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Route $route)
    {
        $validator = Validator::make($request->all(), [
            'path' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'is_public' => 'boolean',
            'roles' => 'nullable|array',
            'roles.*' => 'exists:roles,id',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $route->update([
            'path' => $request->path,
            'description' => $request->description,
            'is_public' => $request->is_public ?? false,
        ]);

        $route->roles()->sync($request->roles ?? []);

        return redirect()->route('routes.index')
            ->with('success', __('common.route-updated-successfully'));
    }

    /**
     * Remove the specified route from storage.
     *
     * @param  \App\Models\Route  $route
     * @return \Illuminate\Http\Response
     */
    public function destroy(Route $route)
    {
        $route->delete();
        
        return redirect()->route('routes.index')
            ->with('success', __('common.route-deleted-successfully'));
    }

    /**
     * Detect routes automatically from Laravel router.
     *
     * @return \Illuminate\Http\Response
     */
    public function detectRoutes()
    {
        $laravelRoutes = LaravelRoute::getRoutes();
        $detectedRoutes = [];
        
        foreach ($laravelRoutes as $route) {
            $path = $route->uri();
            
            // Skip routes that start with these prefixes
            if (strpos($path, '_') === 0 || 
                strpos($path, 'api/') === 0 || 
                strpos($path, 'livewire/') === 0 || 
                strpos($path, 'sanctum/') === 0) {
                continue;
            }
            
            // Check if route already exists in database
            if (!Route::where('path', $path)->exists()) {
                $detectedRoutes[] = [
                    'path' => $path,
                    'methods' => $route->methods(),
                    'name' => $route->getName(),
                    'action' => $route->getActionName(),
                ];
            }
        }
        
        return view('admin.routes.detect', compact('detectedRoutes'));
    }

    /**
     * Import detected routes to database.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function importRoutes(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'routes' => 'required|array',
            'routes.*' => 'string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $imported = 0;
        
        foreach ($request->routes as $path) {
            if (!Route::where('path', $path)->exists()) {
                Route::create([
                    'path' => $path,
                    'description' => 'Auto-imported: ' . $path,
                    'is_public' => false,
                ]);
                $imported++;
            }
        }
        
        return redirect()->route('routes.index')
            ->with('success', __('common.routes-imported', ['count' => $imported]));
    }
}
