<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\AuthController;
use App\Http\Controllers\Admin\DashboardController;

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

// Serve support images
Route::get('/storage/support/{ticketId}/{filename}', function ($ticketId, $filename) {
    $path = storage_path('app/public/support/' . $ticketId . '/' . $filename);
    
    if (!file_exists($path)) {
        // Return 404 with proper headers to prevent console errors
        return response('', 404)
            ->header('Content-Type', 'text/plain')
            ->header('Cache-Control', 'no-cache, no-store, must-revalidate');
    }
    
    $file = file_get_contents($path);
    $type = mime_content_type($path);
    
    return response($file, 200)
        ->header('Content-Type', $type)
        ->header('Cache-Control', 'public, max-age=31536000');
})->where(['ticketId' => '[0-9]+', 'filename' => '[a-zA-Z0-9\-_\.]+']);

// Serve wallet QR code images
Route::get('/storage/wallets/{path}', function ($path) {
    // Security: Only allow qr-codes subdirectory
    if (!str_starts_with($path, 'qr-codes/')) {
        return response('Forbidden', 403);
    }
    
    $fullPath = storage_path('app/public/wallets/' . $path);
    
    if (!file_exists($fullPath)) {
        return response('Not Found', 404)
            ->header('Content-Type', 'text/plain');
    }
    
    $file = file_get_contents($fullPath);
    $type = mime_content_type($fullPath);
    
    return response($file, 200)
        ->header('Content-Type', $type)
        ->header('Cache-Control', 'public, max-age=31536000');
})->where('path', '.*');

// Serve deposit voucher images
Route::get('/storage/deposits/{path}', function ($path) {
    // Security: Only allow vouchers subdirectory
    if (!str_starts_with($path, 'vouchers/')) {
        return response('Forbidden', 403);
    }
    
    $fullPath = storage_path('app/public/deposits/' . $path);
    
    if (!file_exists($fullPath)) {
        return response('Not Found', 404)
            ->header('Content-Type', 'text/plain');
    }
    
    $file = file_get_contents($fullPath);
    $type = mime_content_type($fullPath);
    
    return response($file, 200)
        ->header('Content-Type', $type)
        ->header('Cache-Control', 'public, max-age=31536000');
})->where('path', '.*');

// Serve Discover post images (production-safe: no symlink required)
Route::get('/storage/discover/{path}', function ($path) {
    if (preg_match('/\.\./', $path)) {
        return response('Forbidden', 403);
    }
    $fullPath = storage_path('app/public/discover/' . $path);
    if (!file_exists($fullPath) || !is_file($fullPath)) {
        return response('', 404)->header('Content-Type', 'text/plain')->header('Cache-Control', 'no-cache');
    }
    $file = file_get_contents($fullPath);
    $type = mime_content_type($fullPath) ?: 'application/octet-stream';
    return response($file, 200)->header('Content-Type', $type)->header('Cache-Control', 'public, max-age=31536000');
})->where('path', '[a-zA-Z0-9_\-\.\/]+');

// Serve Announcement images (production-safe: no symlink required)
Route::get('/storage/announcements/{path}', function ($path) {
    if (preg_match('/\.\./', $path)) {
        return response('Forbidden', 403);
    }
    $fullPath = storage_path('app/public/announcements/' . $path);
    if (!file_exists($fullPath) || !is_file($fullPath)) {
        return response('', 404)->header('Content-Type', 'text/plain')->header('Cache-Control', 'no-cache');
    }
    $file = file_get_contents($fullPath);
    $type = mime_content_type($fullPath) ?: 'application/octet-stream';
    return response($file, 200)->header('Content-Type', $type)->header('Cache-Control', 'public, max-age=31536000');
})->where('path', '[a-zA-Z0-9_\-\.\/]+');

Route::prefix('axue2026/admin/dashboard')->group(function () {
    Route::get('/login', [AuthController::class, 'showLogin'])->name('admin.login');
    Route::post('/login', [AuthController::class, 'login'])->name('admin.login.submit');
    Route::post('/logout', [AuthController::class, 'logout'])->name('admin.logout');

    Route::middleware(['admin.auth', 'admin.locale', 'admin.service_restrict'])->group(function () {
        Route::post('/set-locale', function (\Illuminate\Http\Request $request) {
            $locale = $request->input('locale', 'en');
            if (in_array($locale, ['en', 'zh'], true)) {
                session(['admin.locale' => $locale]);
            }
            return redirect()->back();
        })->name('admin.set-locale');

        Route::get('/', [DashboardController::class, 'index'])->name('admin.dashboard');
        Route::get('/api/notification-counts', [DashboardController::class, 'notificationCounts'])->name('admin.api.notification-counts');

        // User Management
        Route::get('/users', [\App\Http\Controllers\Admin\UserManagementController::class, 'index'])->name('admin.users');
        Route::get('/users/{id}', [\App\Http\Controllers\Admin\UserManagementController::class, 'show'])->name('admin.users.show');
        Route::put('/users/{id}', [\App\Http\Controllers\Admin\UserManagementController::class, 'update'])->name('admin.users.update');
        Route::delete('/users/{id}', [\App\Http\Controllers\Admin\UserManagementController::class, 'destroy'])->name('admin.users.destroy');
        Route::post('/users/{id}/verify', [\App\Http\Controllers\Admin\UserManagementController::class, 'verify'])->name('admin.users.verify');
        Route::post('/users/{id}/reset-pin', [\App\Http\Controllers\Admin\UserManagementController::class, 'resetPin'])->name('admin.users.reset-pin');
        Route::post('/users/{id}/set-pin', [\App\Http\Controllers\Admin\UserManagementController::class, 'setPin'])->name('admin.users.set-pin');
        
        // Deposits
        Route::get('/deposits', [\App\Http\Controllers\Admin\DepositController::class, 'index'])->name('admin.deposits');
        Route::put('/deposits/{id}', [\App\Http\Controllers\Admin\DepositController::class, 'update'])->name('admin.deposits.update');
        
        // Withdrawals
        Route::get('/withdrawals', [\App\Http\Controllers\Admin\WithdrawalController::class, 'index'])->name('admin.withdrawals');
        Route::put('/withdrawals/{id}', [\App\Http\Controllers\Admin\WithdrawalController::class, 'update'])->name('admin.withdrawals.update');
        
        // AI Trade Systems
        Route::get('/ai-trade', [\App\Http\Controllers\Admin\AiTradeController::class, 'index'])->name('admin.ai-trade');
        Route::get('/ai-trade/{id}', [\App\Http\Controllers\Admin\AiTradeController::class, 'show'])->name('admin.ai-trade.show');
        Route::put('/ai-trade/{id}', [\App\Http\Controllers\Admin\AiTradeController::class, 'update'])->name('admin.ai-trade.update');
        Route::post('/ai-trade/{id}/control', [\App\Http\Controllers\Admin\AiTradeController::class, 'control'])->name('admin.ai-trade.control');
        Route::post('/ai-trade/{id}/adjust-profit-loss', [\App\Http\Controllers\Admin\AiTradeController::class, 'adjustProfitLoss'])->name('admin.ai-trade.adjust-profit-loss');
        Route::post('/ai-trade/{id}/set-time-based-rules', [\App\Http\Controllers\Admin\AiTradeController::class, 'setTimeBasedRules'])->name('admin.ai-trade.set-time-based-rules');
        Route::post('/ai-trade/{id}/process-now', [\App\Http\Controllers\Admin\AiTradeController::class, 'processNow'])->name('admin.ai-trade.process-now');
        Route::post('/ai-trade/{id}/close', [\App\Http\Controllers\Admin\AiTradeController::class, 'close'])->name('admin.ai-trade.close');
        
        // Financial/Ledger
        Route::get('/financial', [\App\Http\Controllers\Admin\FinancialController::class, 'index'])->name('admin.financial');
        Route::post('/financial/adjust', [\App\Http\Controllers\Admin\FinancialController::class, 'adjust'])->name('admin.financial.adjust');
        
        // Referrals
        Route::get('/referrals', [\App\Http\Controllers\Admin\ReferralController::class, 'index'])->name('admin.referrals');
        
        // Content/Tips – hidden; redirect to dashboard to avoid errors
        Route::get('/content', fn () => redirect()->route('admin.dashboard'))->name('admin.content');
        
        // Support/Tickets (Customer Service Management)
        // Support/Tickets
        Route::get('/support', [\App\Http\Controllers\Admin\SupportController::class, 'index'])->name('admin.support');
        Route::get('/support/{id}/messages', [\App\Http\Controllers\Admin\SupportController::class, 'getMessages'])->name('admin.support.messages');
        Route::get('/support/{id}', [\App\Http\Controllers\Admin\SupportController::class, 'show'])->name('admin.support.show');
        Route::post('/support/{id}/message', [\App\Http\Controllers\Admin\SupportController::class, 'sendMessage'])->name('admin.support.send-message');
        Route::put('/support/{id}/status', [\App\Http\Controllers\Admin\SupportController::class, 'updateStatus'])->name('admin.support.update-status');
        Route::put('/support/message/{messageId}', [\App\Http\Controllers\Admin\SupportController::class, 'updateMessage'])->name('admin.support.update-message');
        Route::delete('/support/message/{messageId}', [\App\Http\Controllers\Admin\SupportController::class, 'deleteMessage'])->name('admin.support.delete-message');
        
        // Audit Logs
        Route::get('/audit-logs', [\App\Http\Controllers\Admin\AuditLogController::class, 'index'])->name('admin.audit-logs');

        // Notifications (send to users, edit templates)
        Route::get('/notifications', [\App\Http\Controllers\Admin\NotificationController::class, 'index'])->name('admin.notifications');
        Route::post('/notifications/send', [\App\Http\Controllers\Admin\NotificationController::class, 'send'])->name('admin.notifications.send');
        Route::post('/notifications/templates', [\App\Http\Controllers\Admin\NotificationController::class, 'updateTemplates'])->name('admin.notifications.templates');

        // Discover (demo posts, add/edit/delete, add comments)
        Route::get('/discover', [\App\Http\Controllers\Admin\DiscoverController::class, 'index'])->name('admin.discover');
        Route::get('/discover/create', [\App\Http\Controllers\Admin\DiscoverController::class, 'create'])->name('admin.discover.create');
        Route::post('/discover', [\App\Http\Controllers\Admin\DiscoverController::class, 'store'])->name('admin.discover.store');
        Route::get('/discover/{id}/edit', [\App\Http\Controllers\Admin\DiscoverController::class, 'edit'])->name('admin.discover.edit');
        Route::put('/discover/{id}', [\App\Http\Controllers\Admin\DiscoverController::class, 'update'])->name('admin.discover.update');
        Route::delete('/discover/{id}', [\App\Http\Controllers\Admin\DiscoverController::class, 'destroy'])->name('admin.discover.destroy');
        Route::post('/discover/{id}/comments', [\App\Http\Controllers\Admin\DiscoverController::class, 'storeComment'])->name('admin.discover.comments.store');
        Route::post('/discover/{id}/likes', [\App\Http\Controllers\Admin\DiscoverController::class, 'storeLikes'])->name('admin.discover.likes.store');

        // Announcements (admin create/delete, choose ID comments, add likes)
        Route::get('/announcements', [\App\Http\Controllers\Admin\AnnouncementController::class, 'index'])->name('admin.announcements');
        Route::get('/announcements/create', [\App\Http\Controllers\Admin\AnnouncementController::class, 'create'])->name('admin.announcements.create');
        Route::post('/announcements', [\App\Http\Controllers\Admin\AnnouncementController::class, 'store'])->name('admin.announcements.store');
        Route::get('/announcements/{id}/edit', [\App\Http\Controllers\Admin\AnnouncementController::class, 'edit'])->name('admin.announcements.edit');
        Route::put('/announcements/{id}', [\App\Http\Controllers\Admin\AnnouncementController::class, 'update'])->name('admin.announcements.update');
        Route::delete('/announcements/{id}', [\App\Http\Controllers\Admin\AnnouncementController::class, 'destroy'])->name('admin.announcements.destroy');
        Route::post('/announcements/{id}/comments', [\App\Http\Controllers\Admin\AnnouncementController::class, 'storeComment'])->name('admin.announcements.comments.store');
        Route::post('/announcements/{id}/likes', [\App\Http\Controllers\Admin\AnnouncementController::class, 'storeLikes'])->name('admin.announcements.likes.store');
        
        // Wallet Management (Super Admin only)
        Route::middleware('admin.super')->group(function () {
            Route::get('/wallets', [\App\Http\Controllers\Admin\WalletManagementController::class, 'index'])->name('admin.wallets');
            Route::post('/wallets', [\App\Http\Controllers\Admin\WalletManagementController::class, 'store'])->name('admin.wallets.store');
            Route::put('/wallets/{id}', [\App\Http\Controllers\Admin\WalletManagementController::class, 'update'])->name('admin.wallets.update');
            Route::delete('/wallets/{id}', [\App\Http\Controllers\Admin\WalletManagementController::class, 'destroy'])->name('admin.wallets.destroy');
        });
        
        // Admin Management (Super Admin only)
        Route::middleware('admin.super')->group(function () {
            Route::get('/admins', [\App\Http\Controllers\Admin\AdminManagementController::class, 'index'])->name('admin.admins');
            Route::post('/admins', [\App\Http\Controllers\Admin\AdminManagementController::class, 'store'])->name('admin.admins.store');
            Route::put('/admins/{id}', [\App\Http\Controllers\Admin\AdminManagementController::class, 'update'])->name('admin.admins.update');
            Route::delete('/admins/{id}', [\App\Http\Controllers\Admin\AdminManagementController::class, 'destroy'])->name('admin.admins.destroy');
        });
        
        // System/Settings (Super Admin only)
        Route::middleware('admin.super')->group(function () {
            Route::get('/system', [\App\Http\Controllers\Admin\SystemController::class, 'index'])->name('admin.system');
            Route::put('/system', [\App\Http\Controllers\Admin\SystemController::class, 'update'])->name('admin.system.update');
        });
    });
});
