<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Response;

// ================== FAVICON ROUTE ==================
Route::get('/favicon.ico', function () {
    $paths = [
        public_path('favicon.ico'),
        public_path('favicon.png'),
        public_path('favicon.svg'),
        storage_path('app/public/favicon.ico'),
    ];
    
    foreach ($paths as $path) {
        if (file_exists($path)) {
            $mime = mime_content_type($path);
            if (!$mime) {
                $mime = 'image/x-icon';
            }
            
            return response()->file($path, [
                'Content-Type' => $mime,
                'Cache-Control' => 'public, max-age=31536000, immutable',
            ]);
        }
    }
    
    // Fallback: SVG embebido
    $svg = '<?xml version="1.0" encoding="UTF-8"?>
    <svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
        <rect width="64" height="64" fill="#2563eb" rx="8"/>
        <rect x="12" y="18" width="40" height="32" fill="#ffffff" rx="4"/>
        <rect x="20" y="26" width="10" height="10" fill="#1e40af" rx="2"/>
        <rect x="34" y="26" width="10" height="10" fill="#1e40af" rx="2"/>
        <rect x="20" y="40" width="10" height="10" fill="#1e40af" rx="2"/>
        <rect x="34" y="40" width="10" height="10" fill="#1e40af" rx="2"/>
        <rect x="27" y="52" width="10" height="6" fill="#0f172a" rx="2"/>
    </svg>';
    
    return response($svg, 200)
        ->header('Content-Type', 'image/svg+xml')
        ->header('Cache-Control', 'public, max-age=3600');
});

// ================== RUTA RAIZ - REDIRECCIÓN INTELIGENTE ==================
Route::get('/', function () {
    if (auth()->check()) {
        return redirect()->route('dashboard');
    }
    return view('welcome');
})->name('home');

// ================== RUTAS PÚBLICAS (sin autenticación) ==================
Route::middleware('guest')->group(function () {
    // Login
    Route::get('login', [App\Http\Controllers\Auth\LoginController::class, 'showLoginForm'])->name('login');
    Route::post('login', [App\Http\Controllers\Auth\LoginController::class, 'login']);
    
    // Registro público (con token opcional)
    Route::get('register/{token?}', [App\Http\Controllers\Auth\LoginController::class, 'showRegistrationForm'])->name('register.public');
    
    // Recuperación de contraseña
    Route::get('password/reset', [App\Http\Controllers\Auth\LoginController::class, 'showLinkRequestForm'])->name('password.request');
    Route::post('password/email', [App\Http\Controllers\Auth\LoginController::class, 'sendResetLinkEmail'])->name('password.email');
    Route::get('password/reset/{token}', [App\Http\Controllers\Auth\LoginController::class, 'showResetForm'])->name('password.reset');
    Route::post('password/reset', [App\Http\Controllers\Auth\LoginController::class, 'reset'])->name('password.update');
    
    // Login específico para condominio
    Route::get('condominio/{condominioId}/login', [App\Http\Controllers\Auth\LoginController::class, 'condominioLogin'])
         ->name('condominio.login');
});

// ================== RUTAS PARA USUARIOS AUTENTICADOS ==================
Route::middleware(['auth'])->group(function () {
    // Logout
    Route::post('logout', [App\Http\Controllers\Auth\LoginController::class, 'logout'])->name('logout');
    
    // Dashboard principal
    Route::get('/dashboard', function () {
        $user = auth()->user();
        
        switch ($user->role) {
            case 'superadmin':
                return redirect()->route('superadmin.dashboard');
            case 'admin':
                return redirect()->route('admin.dashboard');
            case 'propietario':
            case 'inquilino':
                return redirect()->route('resident.dashboard');
            case 'guardia':
                return redirect()->route('security.dashboard');
            default:
                Auth::logout();
                return redirect()->route('login')->with('error', 'Rol de usuario no válido.');
        }
    })->name('dashboard');
    
    // Verificación de autenticación
    Route::get('/check-auth', [App\Http\Controllers\Auth\LoginController::class, 'checkAuth'])->name('auth.check');
    
    // Perfil de usuario
    Route::get('/profile', function () {
        return view('profile.edit', [
            'user' => auth()->user(),
            'pageTitle' => 'Mi Perfil - UrbanOSS'
        ]);
    })->name('profile.edit');
    
    Route::put('/profile', function (\Illuminate\Http\Request $request) {
        $user = auth()->user();
        $user->update($request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $user->id,
        ]));
        
        return back()->with('success', 'Perfil actualizado correctamente.');
    })->name('profile.update');
    
    // Configuración general
    Route::get('/settings', function () {
        return view('settings.index', [
            'pageTitle' => 'Configuración - UrbanOSS'
        ]);
    })->name('settings');
});

// ================== RUTAS DE SUPERADMIN ==================
Route::middleware(['auth', 'role:superadmin'])->prefix('admin/superadmin')->name('superadmin.')->group(function () {
    // Dashboard
    Route::get('/dashboard', [App\Http\Controllers\Admin\SuperAdminController::class, 'dashboard'])->name('dashboard');
    
    // Gestión de Administradores
    Route::get('administrators', [App\Http\Controllers\Admin\SuperAdminController::class, 'administrators'])->name('administrators.index');
    Route::post('administrators', [App\Http\Controllers\Admin\SuperAdminController::class, 'storeAdministrator'])->name('administrators.store');
    Route::delete('administrators/{user}', [App\Http\Controllers\Admin\SuperAdminController::class, 'destroyAdministrator'])->name('administrators.destroy');
    
    // Reportes
    Route::get('reports/financial', [App\Http\Controllers\Admin\SuperAdminController::class, 'financialReports'])->name('reports.financial');
    Route::get('reports/operational', [App\Http\Controllers\Admin\SuperAdminController::class, 'operationalReports'])->name('reports.operational');
    Route::get('reports/export/{type}', [App\Http\Controllers\Admin\SuperAdminController::class, 'exportReports'])->name('reports.export');
    
    // Configuración
    Route::get('settings', [App\Http\Controllers\Admin\SuperAdminController::class, 'settings'])->name('settings');
    Route::put('settings', [App\Http\Controllers\Admin\SuperAdminController::class, 'updateSettings'])->name('settings.update');
    
    // Auditoría
    Route::get('audit-logs', [App\Http\Controllers\Admin\SuperAdminController::class, 'auditLogs'])->name('audit.logs');
    Route::get('activity-logs', [App\Http\Controllers\Admin\SuperAdminController::class, 'activityLogs'])->name('activity.logs');
});

// ================== RUTAS DE ADMINISTRADOR ==================
Route::middleware(['auth', 'role:admin'])->prefix('admin')->name('admin.')->group(function () {
    // Dashboard
    Route::get('/dashboard', [App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('dashboard');
    
    // Configuración
    Route::get('config', [App\Http\Controllers\Admin\DashboardController::class, 'config'])->name('config');
    Route::put('config', [App\Http\Controllers\Admin\DashboardController::class, 'updateConfig'])->name('config.update');
    
    // Reportes
    Route::get('reports', [App\Http\Controllers\Admin\DashboardController::class, 'reports'])->name('reports');
});

// ================== RUTAS DE RESIDENTE ==================
Route::middleware(['auth', 'role:propietario,inquilino'])->prefix('resident')->name('resident.')->group(function () {
    // Dashboard
    Route::get('/dashboard', [App\Http\Controllers\Resident\DashboardController::class, 'index'])->name('dashboard');
    
    // Perfil
    Route::get('/profile', [App\Http\Controllers\Resident\DashboardController::class, 'profile'])->name('profile');
    Route::put('/profile', [App\Http\Controllers\Resident\DashboardController::class, 'updateProfile'])->name('profile.update');
});

// ================== RUTAS DE SEGURIDAD ==================
Route::middleware(['auth', 'role:guardia'])->prefix('security')->name('security.')->group(function () {
    // Dashboard
    Route::get('/dashboard', [App\Http\Controllers\Security\DashboardController::class, 'index'])->name('dashboard');
});

// ================== RUTAS PÚBLICAS ADICIONALES ==================
Route::middleware('guest')->group(function () {
    // Acerca de
    Route::get('/about', function () {
        return view('public.about');
    })->name('about');
    
    // Contacto
    Route::get('/contact', function () {
        return view('public.contact');
    })->name('contact');
    
    // Características
    Route::get('/features', function () {
        return view('public.features');
    })->name('features');
});

// ================== RUTAS UTILITARIAS ==================
// Acceso no autorizado
Route::get('/unauthorized', function () {
    return view('errors.unauthorized');
})->name('unauthorized');

// Verificación de email
Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');

// Health check
Route::get('/health', function () {
    return response()->json([
        'status' => 'healthy',
        'timestamp' => now(),
        'version' => 'UrbanOSS 3.1',
        'laravel' => app()->version()
    ]);
})->name('health');

// Sitemap
Route::get('/sitemap.xml', function () {
    return response()->view('sitemap')->header('Content-Type', 'text/xml');
});

// Página 404 personalizada
Route::fallback(function () {
    if (request()->expectsJson()) {
        return response()->json([
            'success' => false,
            'message' => 'Ruta no encontrada',
            'path' => request()->path()
        ], 404);
    }
    
    return response()->view('errors.404', [
        'title' => 'Página no encontrada',
        'message' => 'La página que buscas no existe o ha sido movida.'
    ], 404);
});
