<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\Dashboard\BrandController;
use App\Http\Controllers\MerchantController;
use App\Http\Controllers\TransactionController;
use App\Http\Controllers\FrontendController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\WalletSettingController;
use App\Http\Controllers\BkashController;
use App\Http\Controllers\Dashboard\DeviceController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\FundsController;
use App\Http\Controllers\InvoiceController;
use App\Http\Middleware\AdminMiddleware;
use App\Http\Middleware\PreventBackHistory;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\App;

/**
 * Localized routes
 */
/**
 * Localized routes
 */
Route::group([
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => [ 'localizationRedirect', 'localeViewPath' ]
], function()
{
    // Public localized routes
    Route::get('/', [FrontendController::class, 'home'])->name('home');
    Route::get('/about', [FrontendController::class, 'about'])->name('about');
    Route::get('/contact', [FrontendController::class, 'contact'])->name('contact');
    Route::get('/pricing', [FrontendController::class, 'pricing'])->name('pricing');
    Route::get('/payment', [FrontendController::class, 'payment'])->name('payment');

});

// Guest routes
// Route::get('/payment-pin', [PaymentController::class, 'showPinForm'])->name('payment.pin');

// Language Switcher Route
// This route handles setting the locale and redirecting back to the appropriate page
Route::get('lang/{locale}', function ($locale) {
    // Set the locale using Laravel's App facade.
    if (!in_array($locale, ['en', 'bn'])) {
        abort(400);
    }

    // LaravelLocalization's middleware (localeSessionRedirect) will pick this up
    // and store it in the session automatically.
    App::setLocale($locale);

    // Get the intended redirect URL from the query string.
    // The `back()` helper provides a sensible fallback.
    $redirectUrl = request('redirect_url', url()->previous());
    
    // If the redirect URL is the base URL, get the localized version of the home route.
    if ($redirectUrl === url('/')) {
        return redirect(LaravelLocalization::getLocalizedURL($locale, route('home')));
    }
    
    return redirect(LaravelLocalization::getLocalizedURL($locale, $redirectUrl));

})->name('lang.switch');

// Public registration route with optional referral code
Route::get('/register/{referral_code?}', [\App\Http\Controllers\Auth\RegisteredUserController::class, 'create'])->name('register.referral')->middleware('guest');

// bKash Client-Side Routes (must be public for guest checkout)
Route::post('/payment/client/create', [PaymentController::class, 'createBkashPayment'])->name('payment.client.create');
Route::post('/payment/client/execute', [PaymentController::class, 'clientSideBkashExecute'])->name('payment.client.execute');

// Public routes that need localization but are for guests
Route::group([
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => [ 'localizationRedirect', 'localeViewPath' ]
], function() {
    // Public Payment Routes (should be accessible without auth)
    Route::post('/payment-verify', [PaymentController::class, 'verifyTransaction'])->name('payment.verify');
    Route::post('/payment/gateway/initiate', [PaymentController::class, 'initiateGatewayPayment'])->name('payment.gateway.initiate');
    Route::post('/payment/redirect', [PaymentController::class, 'redirectToGateway'])->name('payment.redirect');
    Route::get('/payment/callback', [PaymentController::class, 'handleGatewayCallback'])->name('payment.callback');

    // Public success/failure pages
    Route::get('/payment-success', [PaymentController::class, 'paymentSuccess'])->name('payment.success');
    Route::get('/payment-failed', [PaymentController::class, 'paymentFailed'])->name('payment.failed');

    // Public Invoice Route
    Route::get('/invoice/{invoice:invoice_number}', [InvoiceController::class, 'publicShow'])->name('invoice.public.show');
});

// Auth routes
Route::middleware(['auth'])->group(function () {
    // API Payment Routes (protected)
    Route::post('/payment/initiate', [PaymentController::class, 'initiateApiPayment'])->name('payment.initiate');
    Route::post('/payment/pending', [PaymentController::class, 'createPendingTransaction'])->name('payment.pending');
    Route::post('/payment/process', [PaymentController::class, 'process'])->name('payment.process');

    // Protected bKash routes (for logged-in users)
    Route::get('/bkash/query', [PaymentController::class, 'queryPayment'])->name('bkash.query');

    // Profile routes
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

// User-specific routes
Route::middleware(['auth', 'verified', PreventBackHistory::class])->prefix('user')->name('user.')->group(function () {
    // Dashboard Routes
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/payment', [DashboardController::class, 'payment'])->name('payment');
    Route::get('/affiliates', [DashboardController::class, 'affiliates'])->name('affiliates');
    Route::get('/stored-data', [DashboardController::class, 'storedData'])->name('stored-data');

    // Wallet Routes
    Route::get('/wallets', function () {
        return redirect()->route('user.wallets.settings', ['wallet' => 'bkash']);
    })->name('wallets');
    Route::get('/wallets/{wallet}', [WalletSettingController::class, 'show'])->name('wallets.settings')->where('wallet', '[a-z]+');
    Route::post('/wallets/{wallet}', [WalletSettingController::class, 'update'])->name('wallets.update')->where('wallet', '[a-z]+');

    // Brand Routes
    Route::get('/brands', [BrandController::class, 'index'])->name('brands.index');
    Route::post('/brands', [BrandController::class, 'store'])->name('brands.store');
    Route::get('/brands/{brand}/edit', [BrandController::class, 'edit'])->name('brands.edit');
    Route::put('/brands/{brand}', [BrandController::class, 'update'])->name('brands.update');
    Route::delete('/brands/{brand}', [BrandController::class, 'destroy'])->name('brands.destroy');
    Route::post('/brands/change-status', [BrandController::class, 'changeStatus'])->name('brands.change-status');
    Route::post('/brands/reset-key/{brand}', [BrandController::class, 'resetKey'])->name('brands.reset-key');

    // Add Funds Route
    Route::post('/add-funds', [FundsController::class, 'store'])->name('funds.store');

    // Device Routes
    Route::get('/devices', [DeviceController::class, 'index'])->name('devices');
    Route::post('/devices/add', [DeviceController::class, 'addCurrentDevice'])->name('devices.add');
    Route::delete('/devices/{id}', [DeviceController::class, 'revoke'])->name('devices.revoke');
    Route::patch('/devices/{id}', [DeviceController::class, 'update'])->name('devices.update');

    // Invoice Routes (Accessible by Users)
    Route::get('/invoices', [InvoiceController::class, 'index'])->name('invoices.index');
    Route::get('/invoices/create', [InvoiceController::class, 'create'])->name('invoices.create');
    Route::post('/invoices', [InvoiceController::class, 'store'])->name('invoices.store');
    Route::get('/invoices/{invoice}', [InvoiceController::class, 'show'])->name('invoices.show');
    Route::get('/invoices/{invoice}/edit', [InvoiceController::class, 'edit'])->name('invoices.edit');
    Route::put('/invoices/{invoice}', [InvoiceController::class, 'update'])->name('invoices.update');
    Route::delete('/invoices/{invoice}', [InvoiceController::class, 'destroy'])->name('invoices.destroy');
    Route::post('/invoices/toggle-status', [InvoiceController::class, 'toggleStatus'])->name('invoices.toggleStatus');

    // Transaction Routes for Users
    Route::resource('transactions', TransactionController::class)->only(['index', 'show']);
});

// Admin Routes
Route::middleware(['auth', 'verified', AdminMiddleware::class, PreventBackHistory::class])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/', function () {
            return redirect()->route('admin.dashboard');
        })->name('index');

        Route::get('/dashboard', [AdminController::class, 'index'])->name('dashboard');
        Route::get('/affiliates', [DashboardController::class, 'affiliates'])->name('affiliates');
        Route::get('/stored-data', [DashboardController::class, 'storedData'])->name('stored-data');
        
        // Brand Routes
        Route::get('/brands', [BrandController::class, 'index'])->name('brands.index');
        Route::post('/brands', [BrandController::class, 'store'])->name('brands.store');
        Route::get('/brands/{brand}/edit', [BrandController::class, 'edit'])->name('brands.edit');
        Route::put('/brands/{brand}', [BrandController::class, 'update'])->name('brands.update');
        Route::delete('/brands/{brand}', [BrandController::class, 'destroy'])->name('brands.destroy');
        Route::post('/brands/change-status', [BrandController::class, 'changeStatus'])->name('brands.change-status');
        Route::post('/brands/reset-key/{brand}', [BrandController::class, 'resetKey'])->name('brands.reset-key');

        // Invoice Routes
        Route::get('/invoices', [InvoiceController::class, 'index'])->name('invoices.index');
        Route::get('/invoices/create', [InvoiceController::class, 'create'])->name('invoices.create');
        Route::post('/invoices', [InvoiceController::class, 'store'])->name('invoices.store');
        Route::get('/invoices/{invoice}', [InvoiceController::class, 'show'])->name('invoices.show');
        Route::get('/invoices/{invoice}/edit', [InvoiceController::class, 'edit'])->name('invoices.edit');
        Route::put('/invoices/{invoice}', [InvoiceController::class, 'update'])->name('invoices.update');
        Route::delete('/invoices/{invoice}', [InvoiceController::class, 'destroy'])->name('invoices.destroy');
        Route::post('/invoices/toggle-status', [InvoiceController::class, 'toggleStatus'])->name('invoices.toggleStatus');

        // Add Funds Route
        Route::post('/add-funds', [FundsController::class, 'store'])->name('funds.store');

        // Device Routes
        Route::get('/devices', [DeviceController::class, 'index'])->name('devices');
        Route::post('/devices/add', [DeviceController::class, 'addCurrentDevice'])->name('devices.add');
        Route::delete('/devices/{id}', [DeviceController::class, 'revoke'])->name('devices.revoke');
        Route::patch('/devices/{id}', [DeviceController::class, 'update'])->name('devices.update');

        // Merchant and Transaction Routes
        Route::resource('merchants', MerchantController::class);
        Route::resource('transactions', TransactionController::class);

        // Wallet Routes
        Route::get('/wallets', function () {
            return redirect()->route('admin.wallets.settings', ['wallet' => 'bkash']);
        })->name('wallets');
        Route::get('/wallets/{wallet}', [WalletSettingController::class, 'show'])->name('wallets.settings')->where('wallet', '[a-z]+');
        Route::post('/wallets/{wallet}', [WalletSettingController::class, 'update'])->name('wallets.update')->where('wallet', '[a-z]+');
    });

// Auth routes
require __DIR__.'/auth.php';