<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use Telegram\Bot\Api;
use App\Services\TelegramBotService;
use App\Models\TelegramUser;
use App\Models\UserInvestment;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

// Welcome page
Route::get('/', function () {
    return view('welcome');
});

/*
|--------------------------------------------------------------------------
| Telegram Bot Management Routes
|--------------------------------------------------------------------------
*/

// Delete webhook
Route::get('/delete-webhook', function () {
    try {
        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));

        $client = new \GuzzleHttp\Client([
            'verify' => false,
            'timeout' => 30,
        ]);

        $telegram->setHttpClientHandler(
            new \Telegram\Bot\HttpClients\GuzzleHttpClient($client)
        );

        $result = $telegram->deleteWebhook();

        return response()->json([
            'success' => true,
            'message' => 'Webhook deleted successfully!',
            'result' => $result
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ], 500);
    }
});

// Get webhook info
Route::get('/webhook-info', function () {
    try {
        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));

        $client = new \GuzzleHttp\Client([
            'verify' => false,
            'timeout' => 30,
        ]);

        $telegram->setHttpClientHandler(
            new \Telegram\Bot\HttpClients\GuzzleHttpClient($client)
        );

        $info = $telegram->getWebhookInfo();

        return response()->json([
            'success' => true,
            'webhook_info' => $info
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ], 500);
    }
});

// Get updates (for manual testing)
Route::get('/get-updates', function () {
    try {
        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));

        $client = new \GuzzleHttp\Client([
            'verify' => false,            // keep false only for local debugging if you have SSL issues
            'timeout' => 60,              // total request timeout (seconds)
            'connect_timeout' => 10,      // connection phase timeout
            'http_errors' => false,
        ]);

        $telegram->setHttpClientHandler(
            new \Telegram\Bot\HttpClients\GuzzleHttpClient($client)
        );

        // use long polling timeout as well
        $updates = $telegram->getUpdates(['timeout' => 60]);

        // Process each update
        $botService = new TelegramBotService();
        foreach ($updates as $update) {
            $botService->handleUpdate($update);
        }

        return response()->json([
            'success' => true,
            'updates_count' => count($updates),
            'updates' => $updates
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'line' => $e->getLine(),
            'file' => $e->getFile()
        ], 500);
    }
});

// Set webhook (for production)
Route::get('/set-webhook', function () {
    try {
        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));

        $client = new \GuzzleHttp\Client([
            'verify' => false,
            'timeout' => 30,
        ]);

        $telegram->setHttpClientHandler(
            new \Telegram\Bot\HttpClients\GuzzleHttpClient($client)
        );

        $webhookUrl = env('APP_URL') . '/webhook';
        $result = $telegram->setWebhook(['url' => $webhookUrl]);

        return response()->json([
            'success' => true,
            'message' => 'Webhook set successfully!',
            'webhook_url' => $webhookUrl,
            'result' => $result
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ], 500);
    }
});

// Webhook endpoint (for production with webhook)
Route::post('/webhook', function (Request $request) {
    try {
        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));

        $client = new \GuzzleHttp\Client([
            'verify' => false,
            'timeout' => 30,
        ]);

        $telegram->setHttpClientHandler(
            new \Telegram\Bot\HttpClients\GuzzleHttpClient($client)
        );

        $update = $telegram->commandsHandler(true);

        $botService = new TelegramBotService();
        $botService->handleUpdate($update);

        return response()->json(['success' => true]);
    } catch (\Exception $e) {
        \Log::error('Webhook Error: ' . $e->getMessage());
        return response()->json(['success' => false], 200); // Always return 200 to Telegram
    }
});

/*
|--------------------------------------------------------------------------
| Admin Panel Routes
|--------------------------------------------------------------------------
*/

// Admin dashboard
Route::get('/admin-panel', function () {
    try {
        $users = TelegramUser::with('investments')
            ->latest()
            ->paginate(20);

        $stats = [
            'total_users' => TelegramUser::count(),
            'total_investments' => UserInvestment::sum('amount') ?? 0,
            'pending_investments' => UserInvestment::where('status', 'pending')->count(),
            'approved_investments' => UserInvestment::where('status', 'approved')->count(),
        ];

        return view('admin.dashboard', compact('users', 'stats'));
    } catch (\Exception $e) {
        return response()->json([
            'error' => $e->getMessage(),
            'message' => 'Please make sure database is migrated'
        ], 500);
    }
});

// Send message to specific user
Route::post('/admin/send-message', function (Request $request) {
    try {
        $request->validate([
            'chat_id' => 'required',
            'message' => 'required|string',
        ]);

        $botService = new TelegramBotService();

        $photo = null;
        $video = null;

        // Handle photo upload
        if ($request->hasFile('photo')) {
            $photo = $request->file('photo')->store('telegram/photos', 'public');
        }

        // Handle video upload
        if ($request->hasFile('video')) {
            $video = $request->file('video')->store('telegram/videos', 'public');
        }

        $result = $botService->sendMessageToUser(
            $request->chat_id,
            $request->message,
            $photo,
            $video
        );

        return response()->json([
            'success' => $result !== false,
            'message' => $result !== false ? 'Message sent successfully!' : 'Failed to send message'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

// Make user admin
Route::post('/admin/make-admin/{chatId}', function ($chatId) {
    try {
        $user = TelegramUser::where('chat_id', $chatId)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }

        $user->update(['is_admin' => true]);

        return response()->json([
            'success' => true,
            'message' => 'User is now admin!'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

// Remove admin privileges
Route::post('/admin/remove-admin/{chatId}', function ($chatId) {
    try {
        $user = TelegramUser::where('chat_id', $chatId)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }

        $user->update(['is_admin' => false]);

        return response()->json([
            'success' => true,
            'message' => 'Admin privileges removed!'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

// Block user
Route::post('/admin/block-user/{chatId}', function ($chatId) {
    try {
        $user = TelegramUser::where('chat_id', $chatId)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }

        $user->update(['is_blocked' => true]);

        return response()->json([
            'success' => true,
            'message' => 'User blocked successfully!'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

// Unblock user
Route::post('/admin/unblock-user/{chatId}', function ($chatId) {
    try {
        $user = TelegramUser::where('chat_id', $chatId)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }

        $user->update(['is_blocked' => false]);

        return response()->json([
            'success' => true,
            'message' => 'User unblocked successfully!'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

// View user details
Route::get('/admin/user/{chatId}', function ($chatId) {
    try {
        $user = TelegramUser::with('investments')
            ->where('chat_id', $chatId)
            ->firstOrFail();

        return response()->json([
            'success' => true,
            'user' => $user
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'User not found'
        ], 404);
    }
});

// Get all pending investments
Route::get('/admin/pending-investments', function () {
    try {
        $investments = UserInvestment::with('user')
            ->where('status', 'pending')
            ->latest()
            ->get();

        return response()->json([
            'success' => true,
            'investments' => $investments
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

// Approve investment (via web panel)
Route::post('/admin/approve-investment/{id}', function ($id) {
    try {
        $investment = UserInvestment::with('user')->findOrFail($id);

        $investment->update(['status' => 'approved']);

        // Send notification to user
        $botService = new TelegramBotService();
        $botService->sendMessage(
            $investment->user->chat_id,
            "🎉 *Investment Approved!*\n\n" .
                "💰 Amount: \${$investment->amount}\n" .
                "✅ Your investment has been approved!\n" .
                "📈 You will start receiving daily returns.\n\n" .
                "Thank you for trusting Elite Crypto! 🚀"
        );

        return response()->json([
            'success' => true,
            'message' => 'Investment approved successfully!'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

// Reject investment (via web panel)
Route::post('/admin/reject-investment/{id}', function ($id) {
    try {
        $investment = UserInvestment::with('user')->findOrFail($id);

        $investment->update(['status' => 'rejected']);

        // Send notification to user
        $botService = new TelegramBotService();
        $botService->sendMessage(
            $investment->user->chat_id,
            "❌ *Investment Rejected*\n\n" .
                "💰 Amount: \${$investment->amount}\n" .
                "Unfortunately, your investment could not be verified.\n\n" .
                "📞 Please contact support for assistance."
        );

        return response()->json([
            'success' => true,
            'message' => 'Investment rejected successfully!'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

// Broadcast message to all users (via web panel)
Route::post('/admin/broadcast', function (Request $request) {
    try {
        $request->validate([
            'message' => 'required|string',
        ]);

        $botService = new TelegramBotService();

        $users = TelegramUser::where('is_blocked', false)->get();

        $sent = 0;
        $failed = 0;

        foreach ($users as $user) {
            try {
                $botService->sendMessage($user->chat_id, $request->message);
                $sent++;
            } catch (\Exception $e) {
                $failed++;
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Broadcast completed!',
            'sent' => $sent,
            'failed' => $failed
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

/*
|--------------------------------------------------------------------------
| API Routes (Optional - for mobile app integration)
|--------------------------------------------------------------------------
*/

// Get bot statistics
Route::get('/api/stats', function () {
    try {
        $stats = [
            'total_users' => TelegramUser::count(),
            'active_users' => TelegramUser::where('is_blocked', false)->count(),
            'total_investments' => UserInvestment::sum('amount') ?? 0,
            'pending_investments' => UserInvestment::where('status', 'pending')->count(),
            'approved_investments' => UserInvestment::where('status', 'approved')->count(),
            'total_investment_count' => UserInvestment::count(),
        ];

        return response()->json([
            'success' => true,
            'stats' => $stats
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
});

/*
|--------------------------------------------------------------------------
| Test Routes (for development only - remove in production)
|--------------------------------------------------------------------------
*/

// Test database connection
Route::get('/test-db', function () {
    try {
        $users = TelegramUser::count();
        return response()->json([
            'success' => true,
            'message' => 'Database connected successfully!',
            'total_users' => $users
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'message' => 'Database connection failed. Please check your .env file'
        ], 500);
    }
});

// Test bot service
Route::get('/test-bot', function () {
    try {
        $botService = new TelegramBotService();
        return response()->json([
            'success' => true,
            'message' => 'Bot service initialized successfully!'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'message' => 'Bot service initialization failed'
        ], 500);
    }
});

// Get Telegram file (for viewing images in dashboard)
Route::get('/admin/get-telegram-file/{fileId}', function ($fileId) {
    try {
        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));

        $client = new \GuzzleHttp\Client([
            'verify' => false,
            'timeout' => 30,
        ]);

        $telegram->setHttpClientHandler(
            new \Telegram\Bot\HttpClients\GuzzleHttpClient($client)
        );

        // Get file info
        $file = $telegram->getFile(['file_id' => $fileId]);
        $filePath = $file->getFilePath();

        // Telegram file URL
        $fileUrl = "https://api.telegram.org/file/bot" . env('TELEGRAM_BOT_TOKEN') . "/" . $filePath;

        return response()->json([
            'success' => true,
            'file_url' => $fileUrl,
            'file_path' => $filePath
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
});