
<?php

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\Print\OrderPrintController;

Route::get('/', function () {
    return redirect('/admin');
});

Route::middleware(['web', 'auth'])
    ->prefix('admin/print')
    ->group(function () {
        Route::get('/orders/{order}/picking', [OrderPrintController::class, 'picking'])
            ->name('admin.print.orders.picking');

        Route::get('/orders/{order}/pickup', [OrderPrintController::class, 'pickup'])
            ->name('admin.print.orders.pickup');

        Route::get('/orders/{order}/shipping-label', [OrderPrintController::class, 'shippingLabel'])
            ->name('admin.print.orders.shipping-label');
    });

// Rutas de diagnóstico / mantenimiento: SOLO localhost.
// Esto evita exposición accidental en servidores si APP_ENV está mal configurado.
$isLocalRequest = in_array(request()->ip(), ['127.0.0.1', '::1'], true);

//if (app()->environment('local') && $isLocalRequest) {
    Route::get('/test-db', function () {
        try {
            DB::connection()->getPdo();

            return 'Conexión exitosa a MySQL: ' . DB::connection()->getDatabaseName();
        } catch (\Exception $e) {
            return 'Error al conectarse a MySQL: ' . $e->getMessage();
        }
    });

    Route::get('/test-universal-db', function () {
        try {
            $start = microtime(true);

            $connection = DB::connection('universal');
            $connection->select('select 1 as ok');

            $ms = (int) round((microtime(true) - $start) * 1000);

            return response()->json([
                'ok' => true,
                'connection' => 'universal',
                'database' => $connection->getDatabaseName(),
                'latency_ms' => $ms,
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'ok' => false,
                'connection' => 'universal',
                'error' => $e->getMessage(),
                'exception' => $e::class,
            ], 500);
        }
    });

    Route::get('/test-tienda-remota-orders', function () {
        try {
            $countRow = DB::connection('tienda_remota')->selectOne('select count(*) as c from orders');
            $count = (int) ($countRow->c ?? 0);

            $sample = \App\Models\RemoteOrder::query()
                ->orderByDesc('id_order')
                ->first();

            return response()->json([
                'ok' => true,
                'connection' => 'tienda_remota',
                'count' => $count,
                'sample' => $sample,
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'ok' => false,
                'connection' => 'tienda_remota',
                'error' => $e->getMessage(),
                'exception' => $e::class,
            ], 500);
        }
    });

    Route::get('/migrate', function () {
        Artisan::call('migrate:refresh --seed');

        return response()->json([
            'message' => 'migrated',
        ], 201);
    });

    Route::get('/optimize', function () {
        Artisan::call('optimize');

        return response()->json([
            'message' => 'optimized',
        ], 201);
    });

    Route::get('/clear-cache', function () {
        Artisan::call('config:clear');
        Artisan::call('cache:clear');
        Artisan::call('config:cache');

        return response()->json([
            'message' => 'Cache cleared and configuration cached successfully!',
        ]);
    });
    // Ruta protegida para limpiar caché y permisos en producción (acceso restringido por IP)
    Route::get('/admin/clear-permission-cache', function () {
        if (!in_array(request()->ip(), ['127.0.0.1', '::1'], true) && !app()->environment('local')) {
            abort(403, 'Solo permitido en localhost o ambiente local');
        }
        Artisan::call('config:clear');
        Artisan::call('cache:clear');
        Artisan::call('config:cache');
        Artisan::call('permission:cache-reset');
        return response()->json([
            'message' => 'Permisos y caché limpiados correctamente!'
        ]);
    });
    Route::get('/test-moovin-auth', function () {
        $url = 'https://developer.moovin.me/moovinApiWebServices-1/rest/api/moovinEnterprise/partners/login';

        try {
            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
            ])->post($url, [
                'username' => 'emolina@tiendauniversal.com',
                'password' => 'CUM8owbx',
            ]);

            if ($response->successful()) {
                $data = $response->json();

                return response()->json([
                    'status' => 'Conexión Exitosa',
                    'message' => 'Respuesta obtenida correctamente',
                    'full_response' => $data,
                ]);
            }

            return response()->json([
                'status' => 'Error de Autenticación',
                'code' => $response->status(),
                'error' => $response->body(),
            ], $response->status());
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'Error de Conectividad',
                'message' => $e->getMessage(),
            ], 500);
        }
    });

    Route::get('/test-moovin-estimation', function () {
        $url = 'https://developer.moovin.me/moovinApiWebServices-1/rest/api/ecommerceExternal/estimation';

        try {
            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'token' => 'eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNpMjLEKgzAURf_lzi4NSSlZxb2DbllSfcKDNJEXBSH4701w6XjOPdyCfHxgURx46YUWijv7MGWSIe4km3AmB6u6FrwlrRwa68pHjaL_NnQYeU5riuwd6iQp3Jr-Ti50oHODfRhl1POljb5-AAAA__8.SCSbwS1h3f2dMK8k-gUEmvhmMWIW5Qi1jTaEu9aOd9w',
            ])->post($url, [
                'pointCollect' => [
                    'latitude' => 9.929652,
                    'longitude' => -84.134719,
                ],
                'pointDelivery' => [
                    'latitude' => 9.969548,
                    'longitude' => -84.123881,
                ],
                'listProduct' => [
                    [
                        'quantity' => 1,
                        'nameProduct' => 'Samsumg',
                        'description' => 'Galaxy S7',
                        'size' => 'S',
                        'weight' => 0.4,
                        'price' => 200000,
                        'codeProduct' => '234234234234',
                    ],
                    [
                        'quantity' => 1,
                        'nameProduct' => 'clock',
                        'description' => 'LG color Rojo',
                        'size' => 'S',
                        'weight' => 0.1,
                        'price' => 12000,
                        'codeProduct' => '234234234234',
                    ],
                ],
                'ensure' => true,
            ]);

            if ($response->successful()) {
                return response()->json([
                    'status' => 'Conexión Exitosa',
                    'message' => 'Cotización obtenida correctamente',
                    'full_response' => $response->json(),
                ]);
            }

            return response()->json([
                'status' => 'Error en Cotización',
                'code' => $response->status(),
                'error' => $response->body(),
            ], $response->status());
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'Error de Conectividad',
                'message' => $e->getMessage(),
            ], 500);
        }
    });

//}