<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\TransactionController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\TripayController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\NicknameCheckController;
use App\Http\Controllers\PaymentController;
use App\Http\Admin\AdminController;
use App\Http\Controllers\Auth\AuthController;
use App\Http\Controllers\Api\SearchController;
use App\Http\Controllers\ReviewController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\Admin\AdminReviewController;
use App\Http\Controllers\ReviewVoteController;
use App\Http\Controllers\Admin\VoucherController;
use App\Http\Controllers\SitemapController;
use App\Http\Controllers\ReviewReplyController;
use App\Http\Controllers\AccountController;
use App\Http\Admin\GameController;
use Illuminate\Support\Facades\DB;

/*
|--------------------------------------------------------------------------
| PUBLIC ROUTES
|--------------------------------------------------------------------------
*/

// Homepage
Route::get('/', [HomeController::class, 'index'])->name('home');

// Product pages by category type
Route::get('/{type}/{slug}', [HomeController::class, 'productsByCategory'])
    ->where('type', 'game|ewallet|pulsa|voucher|streaming|subscription|utility');

// Track order
Route::get('/track-order', [HomeController::class, 'trackOrder'])->name('track-order');

// Search API
Route::get('/api/search-categories', [HomeController::class, 'apiSearchCategories'])->name('api.search');

// Nickname check API
Route::post('api/check-nickname', [NicknameCheckController::class, 'check']);


/*
|--------------------------------------------------------------------------
| GUEST REVIEW ROUTES (Public - Token Based)
|--------------------------------------------------------------------------
*/

Route::get('/review/{token}', [ReviewController::class, 'createByToken'])
    ->name('reviews.create.token');

Route::post('/review/{token}', [ReviewController::class, 'storeByToken'])
    ->name('reviews.store.token');

Route::get('/products/{slug}/reviews', [ReviewController::class, 'index'])
    ->name('reviews.index');

/*
|--------------------------------------------------------------------------
| AUTHENTICATION ROUTES
|--------------------------------------------------------------------------
*/

Route::middleware('guest')->group(function () {
    Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [AuthController::class, 'login']);
});

Route::post('/logout', [AuthController::class, 'logout'])
    ->name('logout')
    ->middleware('auth');

/*
|--------------------------------------------------------------------------
| TRANSACTION ROUTES (Public)
|--------------------------------------------------------------------------
*/

Route::prefix('transactions')->group(function () {
    // Get payment methods
    Route::get('/payment-methods', [TransactionController::class, 'getPaymentMethods'])
        ->name('transactions.payment-methods');
    
    // Create transaction
    Route::post('/create', [TransactionController::class, 'create'])
        ->name('transactions.create');
    
    // Check status
    Route::get('/{invoiceNumber}/status', [TransactionController::class, 'checkStatus'])
        ->name('transactions.status');
    
    // Payment page
    Route::get('/{invoiceNumber}/payment', [TransactionController::class, 'paymentPage'])
        ->name('transactions.payment');
});

// Tripay callback (webhook)
Route::post('/api/tripay/callback', [TransactionController::class, 'tripayCallback'])
    ->name('tripay.callback');

/*
|--------------------------------------------------------------------------
| AUTHENTICATED USER ROUTES
|--------------------------------------------------------------------------
*/

Route::middleware(['auth'])->prefix('account')->name('account.')->group(function () {
    
    /*
    |--------------------------------------------------------------------------
    | Dashboard
    |--------------------------------------------------------------------------
    */
    Route::get('/dashboard', [AdminController::class, 'dashboard'])->name('dashboard');
    
    /*
    |--------------------------------------------------------------------------
    | User Profile & Settings
    |--------------------------------------------------------------------------
    */
    Route::get('/profile', [AccountController::class, 'profile'])->name('profile');
    Route::put('/profile', [AccountController::class, 'updateProfile'])->name('profile.update');
    Route::put('/password', [AccountController::class, 'updatePassword'])->name('password.update');
    
    /*
    |--------------------------------------------------------------------------
    | User Transactions
    |--------------------------------------------------------------------------
    */
    Route::get('/transactions', [TransactionController::class, 'history'])->name('transactions');
    
    /*
    |--------------------------------------------------------------------------
    | Product Management
    |--------------------------------------------------------------------------
    */
    Route::prefix('products')->name('products.')->group(function () {
        Route::get('/', [ProductController::class, 'index'])->name('index');
        Route::put('/{id}', [ProductController::class, 'update'])->name('update');
        Route::post('/{id}/toggle-status', [ProductController::class, 'toggleStatus'])->name('toggle');
        Route::post('/{id}/apply-markup', [ProductController::class, 'applyMarkup'])->name('markup');
        Route::post('/bulk-toggle', [ProductController::class, 'bulkToggleStatus'])->name('bulk-toggle');
        Route::post('/bulk-markup', [ProductController::class, 'bulkApplyMarkup'])->name('bulk-markup');
        Route::post('/fix-categories', [ProductController::class, 'fixCategories'])->name('fix-categories');
        
        // VIP Reseller Sync
        Route::post('/sync-vipreseller-games', [ProductController::class, 'syncVipResellerGames'])->name('sync-games');
        Route::post('/sync-vipreseller-ppob', [ProductController::class, 'syncVipResellerPpob'])->name('sync-ppob');
    });
    
    /*
    |--------------------------------------------------------------------------
    | Category Management
    |--------------------------------------------------------------------------
    */
    Route::prefix('categories')->name('categories.')->group(function () {
        Route::get('/', [CategoryController::class, 'index'])->name('index');
        Route::post('/', [CategoryController::class, 'store'])->name('store');
        Route::get('/{id}', [CategoryController::class, 'show'])->name('show');
        Route::put('/{id}', [CategoryController::class, 'update'])->name('update');
        Route::delete('/{id}', [CategoryController::class, 'destroy'])->name('destroy');
        Route::post('/{id}/toggle-status', [CategoryController::class, 'toggleStatus'])->name('toggle');
        Route::post('/update-banner', [CategoryController::class, 'updateBanner'])->name('update-banner');
        Route::delete('/delete-banner/{id}', [CategoryController::class, 'deleteBanner'])->name('delete-banner');
    });
    
    /*
    |--------------------------------------------------------------------------
    | Review Management (Admin)
    |--------------------------------------------------------------------------
    */
    Route::prefix('reviews')->name('reviews.')->group(function () {
        // List all reviews (admin)
        Route::get('/', [AdminReviewController::class, 'index'])->name('index');
        
        // Approve/Reject/Delete
        Route::post('/{review}/approve', [AdminReviewController::class, 'approve'])->name('approve');
        Route::post('/{review}/reject', [AdminReviewController::class, 'reject'])->name('reject');
        Route::delete('/{review}', [AdminReviewController::class, 'destroy'])->name('destroy');
    });
    // User Management (Admin Only)
Route::middleware('admin')->prefix('users')->name('users.')->group(function () {
    Route::get('/', [UserController::class, 'index'])->name('index');
    Route::post('/', [UserController::class, 'store'])->name('store');
    Route::get('/{id}', [UserController::class, 'show'])->name('show');
    Route::put('/{id}', [UserController::class, 'update'])->name('update');
    Route::post('/{id}/toggle-status', [UserController::class, 'toggleStatus'])->name('toggle');
    Route::delete('/{id}', [UserController::class, 'destroy'])->name('destroy');
});
    /*
|--------------------------------------------------------------------------
| Voucher Management
|--------------------------------------------------------------------------
*/
Route::prefix('vouchers')->name('vouchers.')->group(function () {
    Route::get('/', [VoucherController::class, 'index'])->name('index');
    Route::post('/', [VoucherController::class, 'store'])->name('store');
    Route::put('/{id}', [VoucherController::class, 'update'])->name('update');
    Route::post('/{id}/toggle', [VoucherController::class, 'toggleStatus'])->name('toggle');
    Route::delete('/{id}', [VoucherController::class, 'destroy'])->name('destroy');
    Route::get('/{id}/usage', [VoucherController::class, 'usage'])->name('usage');
});
    
    /*
    |--------------------------------------------------------------------------
    | User Reviews (Create/Edit Own Reviews)
    |--------------------------------------------------------------------------
    */
    Route::get('/orders/{order}/review', [ReviewController::class, 'create'])->name('reviews.create');
    Route::post('/orders/{order}/review', [ReviewController::class, 'store'])->name('reviews.store');
    Route::get('/reviews/{review}/edit', [ReviewController::class, 'edit'])->name('reviews.edit');
    Route::put('/reviews/{review}', [ReviewController::class, 'update'])->name('reviews.update');
    
    /*
    |--------------------------------------------------------------------------
    | Review Votes & Replies
    |--------------------------------------------------------------------------
    */
    Route::post('/reviews/{review}/vote', [ReviewVoteController::class, 'vote'])->name('reviews.vote');
    Route::post('/reviews/{review}/reply', [ReviewReplyController::class, 'store'])->name('reviews.reply');
    Route::put('/reviews/replies/{reply}', [ReviewReplyController::class, 'update'])->name('reviews.reply.update');
    Route::delete('/reviews/replies/{reply}', [ReviewReplyController::class, 'destroy'])->name('reviews.reply.destroy');
    
    /*
    |--------------------------------------------------------------------------
    | Games Management (Admin Only)
    |--------------------------------------------------------------------------
    */
    Route::middleware('admin')->prefix('games')->name('games.')->group(function () {
        Route::get('/', [GameController::class, 'index'])->name('index');
        Route::post('/store', [GameController::class, 'store'])->name('store');
        Route::post('/{id}/update', [GameController::class, 'update'])->name('update');
        Route::delete('/{id}', [GameController::class, 'destroy'])->name('destroy');
    });
});

/*
|--------------------------------------------------------------------------
| ADMIN TRANSACTION ROUTES
|--------------------------------------------------------------------------
*/

Route::middleware(['auth', 'admin'])->prefix('admin/transactions')->group(function () {
    Route::get('/', [TransactionController::class, 'index'])->name('admin.transactions.index');
    Route::get('/{id}', [TransactionController::class, 'show'])->name('admin.transactions.show');
    Route::post('/{id}/refund', [TransactionController::class, 'refund'])->name('admin.transactions.refund');
    Route::post('/{id}/retry', [TransactionController::class, 'retry'])->name('admin.transactions.retry');
});

Route::get('/sitemap.xml', [SitemapController::class, 'index'])->name('sitemap');
Route::get('/robots.txt', [SitemapController::class, 'robots'])->name('robots');


/*
|--------------------------------------------------------------------------
| UTILITY ROUTES (Dev/Testing)
|--------------------------------------------------------------------------
*/

// Fix all category input types
Route::get('/fix-all-categories', function() {
    // E-Wallet - Phone Number
    DB::table('categories')->whereIn('slug', ['dana', 'ovo', 'gopay', 'shopeepay', 'linkaja', 'bri-brizzi'])
        ->update(['input_type' => 'phone']);
    
    // Pulsa & Paket Data - Phone Number
    DB::table('categories')->whereIn('slug', [
        'smartfren', 'telkomsel', 'indosat', 'xl-axiata', 'tri', 'axis', 'by-u', 'smartfren-data'
    ])->update(['input_type' => 'phone']);
    
    // Subscription/Streaming - Email
    DB::table('categories')->whereIn('slug', [
        'chatgpt', 'canva-pro', 'netflix', 'spotify', 'youtube-premium', 'disney-plus', 
        'midjourney', 'grammarly', 'notion'
    ])->update(['input_type' => 'email']);
    
    // Discord - Username
    DB::table('categories')->where('slug', 'discord-nitro')
        ->update(['input_type' => 'username']);
    
    // Games dengan Zone ID
    DB::table('categories')->whereIn('slug', [
        'mobile-legends-a', 'mobile-legends-b', 'mobile-legends-gift',
        'genshin-impact', 'honkai-star-rail', 'marvel-snap', 'magic-chess-go-go'
    ])->update(['input_type' => 'user-id-zone']);
    
    // Games tanpa Zone ID
    DB::table('categories')->whereIn('slug', [
        'free-fire', 'pubg-mobile', 'cod-mobile', 'valorant', 'clash-of-clans', 
        'clash-royale', 'brawl-stars', 'roblox', 'steam-wallet'
    ])->update(['input_type' => 'user-id']);
    
    $stats = [
        'phone' => DB::table('categories')->where('input_type', 'phone')->count(),
        'email' => DB::table('categories')->where('input_type', 'email')->count(),
        'username' => DB::table('categories')->where('input_type', 'username')->count(),
        'user-id' => DB::table('categories')->where('input_type', 'user-id')->count(),
        'user-id-zone' => DB::table('categories')->where('input_type', 'user-id-zone')->count(),
    ];
    
    return '✅ All categories updated successfully!<br><br>' .
           '<b>Statistics:</b><br>' .
           '📱 Phone: ' . $stats['phone'] . ' categories<br>' .
           '📧 Email: ' . $stats['email'] . ' categories<br>' .
           '👤 Username: ' . $stats['username'] . ' categories<br>' .
           '🎮 User ID: ' . $stats['user-id'] . ' categories<br>' .
           '🎯 User ID + Zone: ' . $stats['user-id-zone'] . ' categories';
});

Route::get('/search-games', function(Request $request) {
    try {
        $query = $request->get('q', '');
        
        if (strlen($query) < 2) {
            return response()->json([
                'success' => true,
                'games' => []
            ]);
        }
        
        // Simple DB query
        $games = \DB::table('categories')
            ->where('name', 'LIKE', "%{$query}%")
            ->select('id', 'name', 'slug', 'image')
            ->limit(10)
            ->get();
        
        return response()->json([
            'success' => true,
            'games' => $games
        ]);
        
    } catch (\Exception $e) {
        // Return error tapi status 200 biar JS ga error
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'games' => []
        ], 200);
    }
});

Route::post('/account/products/bulk-markup', [ProductController::class, 'bulkMarkup']);
Route::post('/account/products/bulk-markup', [ProductController::class, 'bulkMarkup']);
// Reviews bulk actions
Route::post('/account/reviews/bulk-approve', [ReviewController::class, 'bulkApprove']);
Route::post('/account/reviews/bulk-reject', [ReviewController::class, 'bulkReject']);
Route::post('/account/reviews/bulk-delete', [ReviewController::class, 'bulkDelete']);

// Vouchers bulk actions
Route::post('/account/vouchers/bulk-activate', [VoucherController::class, 'bulkActivate']);
Route::post('/account/vouchers/bulk-deactivate', [VoucherController::class, 'bulkDeactivate']);
Route::post('/account/vouchers/bulk-delete', [VoucherController::class, 'bulkDelete']);

// Users bulk actions
Route::post('/account/users/bulk-activate', [UserController::class, 'bulkActivate']);
Route::post('/account/users/bulk-deactivate', [UserController::class, 'bulkDeactivate']);
Route::post('/account/users/bulk-delete', [UserController::class, 'bulkDelete']);

// Products bulk actions
Route::post('/account/products/bulk-markup', [ProductController::class, 'bulkMarkup']);


// ============================================
// PASTE KE routes/web.php (PALING BAWAH)
// ============================================

Route::get('/admin/delete-all-video-categories', function() {
    
    try {
        $patterns = [
            // Video variants
            '%video%premier%',
            '%vidio%premier%',
            'vidprem%',
            '%yt%premium%',
            
            // YouTube variants
            '%youtube%premium%',
            '%youtube%music%',
            '%yt%music%',
            
            // Social media
            '%likee%',
            '%like%video%',
            '%tiktok%',
            '%snack%video%',
            '%bigo%',
            '%showroom%',
            
            // Streaming
            '%netflix%',
            '%spotify%',
            '%disney%',
            '%viu%',
            '%iqiyi%',
            '%wetv%',
        ];
        
        $deleted = 0;
        $deletedList = [];
        
        foreach ($patterns as $pattern) {
            $categories = DB::table('categories')
                ->whereRaw('LOWER(name) LIKE ?', [$pattern])
                ->get();
            
            foreach ($categories as $cat) {
                $deletedList[] = $cat->name;
                DB::table('categories')->where('id', $cat->id)->delete();
                $deleted++;
            }
        }
        
        echo "<h2>✅ Cleanup Complete!</h2>";
        echo "<p><strong>Total deleted: {$deleted} categories</strong></p>";
        
        if (count($deletedList) > 0) {
            echo "<h3>Deleted Categories:</h3><ul>";
            foreach ($deletedList as $name) {
                echo "<li>{$name}</li>";
            }
            echo "</ul>";
        }
        
        echo "<br><a href='/'>← Back to Home</a> | <a href='/account/categories'>Go to Categories</a>";
        
        return response()->json([
            'success' => true,
            'deleted' => $deleted,
            'list' => $deletedList
        ]);
        
    } catch (\Exception $e) {
        return response("<h2>Error!</h2><p>{$e->getMessage()}</p>");
    }
    
})->middleware('auth');