<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\RedirectController;
use App\Models\Shortlink;

/*
|--------------------------------------------------------------------------
| Debug Routes - HANYA UNTUK DEVELOPMENT/TROUBLESHOOTING
|--------------------------------------------------------------------------
| 
| Routes ini untuk debugging masalah Open Graph preview.
| HAPUS atau COMMENT setelah masalah selesai untuk keamanan!
|
*/

// Test 1: Cek Bot Detection
Route::get('/debug/bot-detection/{code}', function($code) {
    $userAgent = request()->userAgent();
    $ip = request()->ip();
    
    $controller = new RedirectController();
    $reflection = new ReflectionClass($controller);
    
    // Access private methods untuk testing
    $isSocialBotMethod = $reflection->getMethod('isSocialMediaBot');
    $isSocialBotMethod->setAccessible(true);
    
    $isBotIPMethod = $reflection->getMethod('isBotIP');
    $isBotIPMethod->setAccessible(true);
    
    $isSocialBot = $isSocialBotMethod->invoke($controller, $userAgent);
    $isBotIP = $isBotIPMethod->invoke($controller, $ip);
    
    return response()->json([
        'code' => $code,
        'user_agent' => $userAgent,
        'ip' => $ip,
        'is_social_bot_by_ua' => $isSocialBot,
        'is_bot_by_ip' => $isBotIP,
        'is_bot_final' => $isSocialBot || $isBotIP,
        'will_show_preview' => $isSocialBot || $isBotIP ? 'YES ✅' : 'NO ❌ (Will redirect directly)',
    ], 200, [], JSON_PRETTY_PRINT);
});

// Test 2: Force Preview Page (Bypass bot detection)
Route::get('/debug/preview/{code}', function($code) {
    $shortlink = Shortlink::where('custom_alias', $code)
        ->orWhere('short_code', $code)
        ->where('is_active', true)
        ->first();
    
    if (!$shortlink) {
        return response()->json([
            'error' => 'Shortlink tidak ditemukan',
            'code' => $code,
        ], 404);
    }
    
    return view('preview', [
        'shortlink' => $shortlink,
        'title' => $shortlink->title ?: 'Shortlink',
        'description' => $shortlink->description ?: 'Klik untuk membuka link',
        'url' => $shortlink->original_url,
        'image' => $shortlink->og_image ?? null,
    ]);
});

// Test 3: Cek Data Shortlink di Database
Route::get('/debug/shortlink-data/{code}', function($code) {
    $shortlink = Shortlink::where('custom_alias', $code)
        ->orWhere('short_code', $code)
        ->first();
    
    if (!$shortlink) {
        return response()->json([
            'error' => 'Shortlink tidak ditemukan',
            'code' => $code,
        ], 404);
    }
    
    return response()->json([
        'id' => $shortlink->id,
        'title' => $shortlink->title,
        'description' => $shortlink->description,
        'og_image' => $shortlink->og_image,
        'original_url' => $shortlink->original_url,
        'short_code' => $shortlink->short_code,
        'custom_alias' => $shortlink->custom_alias,
        'is_active' => $shortlink->is_active,
        'created_at' => $shortlink->created_at,
        'short_url' => $shortlink->getShortUrl(),
        
        // Validasi
        'validation' => [
            'has_title' => !empty($shortlink->title) ? '✅' : '❌',
            'has_description' => !empty($shortlink->description) ? '✅' : '❌',
            'has_og_image' => !empty($shortlink->og_image) ? '✅' : '❌',
            'image_accessible' => !empty($shortlink->og_image) ? 'Test manually: ' . $shortlink->og_image : 'N/A',
        ]
    ], 200, [], JSON_PRETTY_PRINT);
});

// Test 4: Test Meta Tags Output
Route::get('/debug/meta-tags/{code}', function($code) {
    $shortlink = Shortlink::where('custom_alias', $code)
        ->orWhere('short_code', $code)
        ->where('is_active', true)
        ->first();
    
    if (!$shortlink) {
        return "Shortlink tidak ditemukan: {$code}";
    }
    
    $title = $shortlink->title ?: 'Shortlink';
    $description = $shortlink->description ?: 'Klik untuk membuka link';
    $image = $shortlink->og_image ?? null;
    $url = $shortlink->original_url;
    
    $html = "<!DOCTYPE html>\n<html>\n<head>\n";
    $html .= "    <title>{$title}</title>\n";
    $html .= "    <meta property=\"og:title\" content=\"{$title}\">\n";
    $html .= "    <meta property=\"og:description\" content=\"{$description}\">\n";
    $html .= "    <meta property=\"og:url\" content=\"{$url}\">\n";
    
    if ($image) {
        $html .= "    <meta property=\"og:image\" content=\"{$image}\">\n";
    }
    
    $html .= "</head>\n<body>\n";
    $html .= "<h1>Meta Tags Preview</h1>\n";
    $html .= "<pre>\n";
    $html .= "Title: {$title}\n";
    $html .= "Description: {$description}\n";
    $html .= "Image: " . ($image ?: 'NONE') . "\n";
    $html .= "URL: {$url}\n";
    $html .= "</pre>\n";
    
    if ($image) {
        $html .= "<h2>Image Preview:</h2>\n";
        $html .= "<img src=\"{$image}\" style=\"max-width: 500px;\" onerror=\"this.style.display='none'; document.getElementById('img-error').style.display='block';\">\n";
        $html .= "<p id=\"img-error\" style=\"display:none; color:red;\">❌ Image failed to load. URL might be invalid or inaccessible.</p>\n";
    }
    
    $html .= "</body>\n</html>";
    
    return response($html);
});

// Test 5: Test cURL Functionality
Route::get('/debug/test-curl', function() {
    $testUrl = "https://paketbuku.com/shop/bukngadsense8/";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $testUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
    
    $startTime = microtime(true);
    $result = curl_exec($ch);
    $endTime = microtime(true);
    
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    $success = $httpCode === 200 && !$error && $result;
    
    return response()->json([
        'test_url' => $testUrl,
        'status' => $success ? '✅ SUCCESS' : '❌ FAILED',
        'http_code' => $httpCode,
        'error' => $error ?: 'None',
        'response_size' => strlen($result) . ' bytes',
        'execution_time' => round(($endTime - $startTime) * 1000, 2) . ' ms',
        'curl_enabled' => function_exists('curl_init') ? '✅ Yes' : '❌ No',
    ], 200, [], JSON_PRETTY_PRINT);
});

// Test 6: Comprehensive Debug Report
Route::get('/debug/report/{code}', function($code) {
    $shortlink = Shortlink::where('custom_alias', $code)
        ->orWhere('short_code', $code)
        ->first();
    
    if (!$shortlink) {
        return response()->json([
            'error' => 'Shortlink tidak ditemukan',
            'code' => $code,
        ], 404);
    }
    
    // Bot Detection
    $userAgent = request()->userAgent();
    $ip = request()->ip();
    
    $controller = new RedirectController();
    $reflection = new ReflectionClass($controller);
    
    $isSocialBotMethod = $reflection->getMethod('isSocialMediaBot');
    $isSocialBotMethod->setAccessible(true);
    
    $isBotIPMethod = $reflection->getMethod('isBotIP');
    $isBotIPMethod->setAccessible(true);
    
    $isSocialBot = $isSocialBotMethod->invoke($controller, $userAgent);
    $isBotIP = $isBotIPMethod->invoke($controller, $ip);
    
    return response()->json([
        'shortlink_data' => [
            'id' => $shortlink->id,
            'title' => $shortlink->title,
            'description' => $shortlink->description,
            'og_image' => $shortlink->og_image,
            'original_url' => $shortlink->original_url,
            'short_url' => $shortlink->getShortUrl(),
            'is_active' => $shortlink->is_active,
        ],
        'validation' => [
            'has_title' => !empty($shortlink->title),
            'has_description' => !empty($shortlink->description),
            'has_og_image' => !empty($shortlink->og_image),
        ],
        'bot_detection' => [
            'user_agent' => $userAgent,
            'ip' => $ip,
            'is_social_bot' => $isSocialBot,
            'is_bot_ip' => $isBotIP,
            'will_show_preview' => ($isSocialBot || $isBotIP),
        ],
        'urls_to_test' => [
            'preview_page' => url("/debug/preview/{$code}"),
            'meta_tags' => url("/debug/meta-tags/{$code}"),
            'facebook_debugger' => "https://developers.facebook.com/tools/debug/?q=" . urlencode($shortlink->getShortUrl()),
        ],
        'recommendations' => [
            'database' => !empty($shortlink->title) && !empty($shortlink->og_image) ? '✅ Data lengkap' : '❌ Data tidak lengkap, perlu refresh metadata',
            'bot_detection' => ($isSocialBot || $isBotIP) ? '✅ Bot terdeteksi, preview akan muncul' : '⚠️ Bot tidak terdeteksi dari request ini',
            'image_url' => !empty($shortlink->og_image) ? 'Test akses: ' . $shortlink->og_image : '❌ Tidak ada gambar',
        ]
    ], 200, [], JSON_PRETTY_PRINT);
});
