<?php

use App\Http\Controllers\Auth\SteamAuthController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\UserProfileController;
use App\Http\Controllers\ForumController;
use App\Http\Controllers\NewsController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\Store\StoreController;
use App\Http\Controllers\Store\PaymentController;
use App\Http\Controllers\Store\CouponController;
use App\Http\Controllers\Store\PurchaseHistoryController;
use App\Http\Controllers\Api\PayPalOrderController;
use App\Http\Controllers\NotificationsController;
use App\Http\Controllers\UpgradeController;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;

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

// Profile routes
Route::middleware(['auth'])->group(function () {
    Route::get('/profile', [UserProfileController::class, 'show'])->name('profile.show');
    Route::get('/profile/edit', [UserProfileController::class, 'edit'])->name('profile.edit');
    Route::put('/profile', [UserProfileController::class, 'update'])->name('profile.update');
    Route::get('/profile/delete-banner', [UserProfileController::class, 'deleteBanner'])->name('profile.delete-banner');
});

// Public user profile route - accessible without authentication
Route::get('/users', [UserController::class, 'index'])->name('users.index');
Route::get('/users/{user}', [UserProfileController::class, 'show'])->name('users.show');

Route::middleware('auth')->group(function () {
    Route::get('/notifications', [NotificationsController::class, 'index'])->name('notifications.index');
    Route::get('/notifications/unread-count', [NotificationsController::class, 'unreadCount'])->name('notifications.unread-count');
    Route::get('/notifications/recent', [NotificationsController::class, 'recent'])->name('notifications.recent');
    Route::post('/notifications/{id}/read', [NotificationsController::class, 'markAsRead'])->name('notifications.read');
    Route::post('/notifications/mark-all-read', [NotificationsController::class, 'markAllAsRead'])->name('notifications.mark-all-read');
    Route::delete('/notifications/{id}', [NotificationsController::class, 'destroy'])->name('notifications.destroy');
    Route::delete('/notifications', [NotificationsController::class, 'destroyAll'])->name('notifications.destroy-all');
});

// Store routes
Route::prefix('store')->name('store.')->group(function () {
    // Public store routes
    Route::get('/', [StoreController::class, 'index'])->name('index');
    Route::get('/terms-of-service', [StoreController::class, 'tos'])->name('tos');
    
    // Auth-required store routes
    Route::middleware(['auth'])->group(function () {
        // Exact paths first
        Route::get('/purchase-history', [PurchaseHistoryController::class, 'index'])->name('purchase-history');
        
        // More specific parameterized routes first
        Route::get('/purchase/{transaction}/receipt', [PurchaseHistoryController::class, 'downloadReceipt'])->name('purchase-receipt');
        Route::get('/purchase/{transaction}', [PurchaseHistoryController::class, 'show'])->name('purchase-detail');
    });
    
    // Server switching (POST request, no conflict)
    Route::post('/switch-server/{serverId}', [StoreController::class, 'switchServer'])->name('switch-server');
    
    // Parameterized routes last (public)
    Route::get('/{slug}', [StoreController::class, 'show'])->name('show');
});

// Coupon routes
Route::prefix('coupons')->name('coupon.')->group(function () {
    Route::post('/apply', [CouponController::class, 'apply'])->name('apply');
    Route::post('/remove', [CouponController::class, 'remove'])->name('remove');
});

Route::middleware(['auth'])->group(function () {
    Route::post('/paypal/create-order', [PaymentController::class, 'createPayPalOrder'])->name('paypal.create-order');
    Route::get('/paypal/order/{orderId}', [PaymentController::class, 'getOrderDetails'])->name('paypal.order-details');
});

// Payment routes (auth required)
Route::middleware(['auth'])->group(function () {
    // Checkout routes
    Route::get('/checkout/{slug}', [PaymentController::class, 'checkout'])->name('store.payment.checkout');
    Route::post('/checkout/{slug}', [PaymentController::class, 'processPayment'])->name('payment.process');
    
    // Payment result routes
    Route::get('/payment/success/{transactionId}', [PaymentController::class, 'success'])->name('payment.success');
    Route::get('/payment/cancel/{transactionId}', [PaymentController::class, 'cancel'])->name('payment.cancel');
    
    // Stripe success route
    Route::get('/stripe/success/{transaction}', [PaymentController::class, 'stripeSuccess'])->name('stripe.success');
    
    // PayPal success route (handles both order IDs and transaction IDs)
    Route::get('/paypal/success/{orderIdOrTransactionId}', [PaymentController::class, 'paypalSuccess'])->name('paypal.success');
});

// Webhook routes (no auth, no CSRF)
Route::withoutMiddleware([\App\Http\Middleware\VerifyCsrfToken::class])->group(function () {
    // Legacy PayPal IPN (keep for backwards compatibility)
    Route::post('/payment/ipn', [PaymentController::class, 'ipn'])->name('payment.ipn');
    
    // Modern PayPal webhook
    Route::post('/paypal/webhook', [PaymentController::class, 'paypalWebhook'])->name('paypal.webhook');
    
    // Stripe webhook
    Route::post('/stripe/webhook', [PaymentController::class, 'stripeWebhook'])->name('stripe.webhook');
});
        
// News Routes
Route::get('/news', [NewsController::class, 'index'])->name('news.index');
Route::get('/news/{slug}', [NewsController::class, 'show'])->name('news.show');

// Static pages
Route::get('/map', function() {
    return view('map');
})->name('map');

Route::get('/privacy-policy', [HomeController::class, 'privacy'])->name('privacy.policy');

// Forum routes
Route::prefix('forum')->name('forum.')->group(function () {
    // Forum index (categories and boards)
    Route::get('/', [ForumController::class, 'index'])->name('index');
    
    // View board with threads
    Route::get('/board/{slug}', [ForumController::class, 'board'])->name('board');
    
    // Thread creation (requires auth)
    Route::middleware('auth')->group(function () {
        Route::get('/board/{slug}/create-thread', [ForumController::class, 'createThread'])->name('create-thread');
        Route::post('/board/{slug}/create-thread', [ForumController::class, 'storeThread'])->name('store-thread');
    });
    
    // View thread with posts
    Route::get('/board/{boardSlug}/thread/{threadSlug}', [ForumController::class, 'thread'])->name('thread');
    
    // Create post in thread (requires auth)
    Route::middleware('auth')->group(function () {
        Route::post('/board/{boardSlug}/thread/{threadSlug}/post', [ForumController::class, 'storePost'])->name('store-post');
        
        // Reactions
        Route::post('/post/reaction', [ForumController::class, 'toggleReaction'])->name('toggle-reaction');
        Route::post('/thread/reaction', [ForumController::class, 'toggleThreadReaction'])->name('toggle-thread-reaction');
    });

    // Thread moderation
    Route::get('/forum/{boardSlug}/{threadSlug}/edit', [ForumController::class, 'editThread'])->name('edit-thread');
    Route::put('/forum/{boardSlug}/{threadSlug}', [ForumController::class, 'updateThread'])->name('update-thread');
    Route::delete('/forum/{boardSlug}/{threadSlug}', [ForumController::class, 'deleteThread'])->name('delete-thread');
    Route::post('/forum/{boardSlug}/{threadSlug}/lock', [ForumController::class, 'toggleLockThread'])->name('toggle-lock-thread');
    Route::post('/forum/{boardSlug}/{threadSlug}/pin', [ForumController::class, 'togglePinThread'])->name('toggle-pin-thread');

    // Post moderation
    Route::get('/forum/{boardSlug}/{threadSlug}/post/{postId}/edit', [ForumController::class, 'editPost'])->name('edit-post');
    Route::put('/forum/{boardSlug}/{threadSlug}/post/{postId}', [ForumController::class, 'updatePost'])->name('update-post');
    Route::delete('/forum/{boardSlug}/{threadSlug}/post/{postId}', [ForumController::class, 'deletePost'])->name('delete-post');
});

// Steam auth routes
Route::get('/login/steam', [SteamAuthController::class, 'redirect'])->name('login.steam');
Route::get('/login/steam/callback', [SteamAuthController::class, 'callback'])->name('login.steam.callback');
Route::post('/logout', [SteamAuthController::class, 'logout'])->name('logout');

Route::get('/loading', function (Request $request) {
    $steamId = $request->query('steamid', '');
    $map = $request->query('map', '');
    $settings = \App\Models\LoadingScreenSettings::getSettings();
    
    return view('loading', [
        'steamId' => $steamId,
        'map' => $map,
        'settings' => $settings
    ]);
})->name('gmod.loading');


Route::get('/test-paypal-detailed', function() {
    $service = new \App\Services\PayPalService();
    
    $clientId = config_value('store_paypal_client_id', '');
    $clientSecret = config_value('store_paypal_client_secret', '');
    $sandbox = config_value('store_sandbox', true);
    
    $result = [
        'configured' => $service->isConfigured(),
        'client_id_length' => strlen($clientId),
        'client_secret_length' => strlen($clientSecret),
        'sandbox_mode' => $sandbox,
        'base_url' => $sandbox ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com',
        'can_get_token' => false,
        'token_error' => null
    ];
    
    // Try to get token and capture any errors
    try {
        $token = $service->getAccessToken();
        $result['can_get_token'] = $token !== null;
        if ($token) {
            $result['token_preview'] = substr($token, 0, 20) . '...';
        }
    } catch (\Exception $e) {
        $result['token_error'] = $e->getMessage();
    }
    
    return response()->json($result);
});

Route::prefix('upgrade')->name('upgrade.')->middleware(['auth', 'upgrade.access'])->group(function () {
    Route::get('/', [UpgradeController::class, 'index'])->name('index');
    Route::post('/upload', [UpgradeController::class, 'upload'])->name('upload');
    Route::get('/verify', [UpgradeController::class, 'verify'])->name('verify');
    Route::post('/backup', [UpgradeController::class, 'backup'])->name('backup');
    Route::get('/process', [UpgradeController::class, 'process'])->name('process');
    Route::post('/do-upgrade', [UpgradeController::class, 'doUpgrade'])->name('do_upgrade');
    Route::get('/rollback', [UpgradeController::class, 'rollback'])->name('rollback');
    Route::post('/do-rollback', [UpgradeController::class, 'doRollback'])->name('do_rollback');
    Route::get('/complete', [UpgradeController::class, 'complete'])->name('complete');
    Route::get('/progress', [UpgradeController::class, 'getProgress'])->name('progress');
});