<?php

use App\Http\Controllers\Frontend\ProfileController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Frontend\ContactUsController;
use App\Http\Controllers\Frontend\OrderController;
use App\Http\Controllers\Frontend\SupportTicketController;
use App\Http\Controllers\Frontend\DashboardController;
use App\Http\Controllers\Frontend\NotificationController;
use App\Http\Controllers\Frontend\TodoController;
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Frontend\WalletTransactionController;
use App\Http\Controllers\Frontend\TwoFAControllerCentral;
use App\Http\Controllers\Frontend\ManageTeamController;
use App\Http\Controllers\Frontend\MyWalletsController;
use App\Http\Controllers\AjaxCallApiController;
use App\Http\Controllers\Frontend\BonusPurchasePoolController;
use App\Http\Controllers\Frontend\DepositController;
use App\Http\Controllers\Frontend\EarningsTransactionController;
use App\Http\Controllers\Frontend\IdentityVerificationController;
use App\Http\Controllers\Frontend\WithdrawalController;
use App\Http\Controllers\Frontend\MyCareerDashboardController;

Route::get('/clear-cache', function () {
    clearCache();
    return redirect()->back()->with(['success' => 'Cache cleared successfully']);
});

//otp verification
Route::get('auth-password', [DashboardController::class, 'authPassword'])->name('authPassword');
Route::post('password-validation', [DashboardController::class, 'passwordValidation'])->name('passwordValidation');
Route::post('get-state', [ProfileController::class, 'GetState']);
Route::post('get-city', [ProfileController::class, 'GetCity']);
Route::get('refresh-csrf', function () {
    return csrf_token();
});

//Get user public ip
Route::post('/set-user-ip', function (\Illuminate\Http\Request $request) {
    session(['user_ip' => $request->ip]);
});

Route::get('/keep-alive', function () {
    // Touch the session to keep it alive
    return response()->noContent();
});
Route::middleware(['remember','check.cookie'])->group(function () {
    Route::get('/dashboard', function () {
        return redirect('member/dashboard');
    });


    Route::get('/', function () {
        return view('landing_pages.welcome');
    })->name('welcome');

    Route::get('/faq', function () {
        return view('landing_pages.faq');
    });

    Route::get('/help', function () {
        return view('frontend.help');
    });

    Route::get('/clear', function () {
        Artisan::call('cache:clear');
        Artisan::call('config:clear');
        Artisan::call('view:clear');
        return "Cleared!";
    });

    /*COMMON ROUTES END HERE*/
    Route::get('/change-email-address/{action_type}/{token}/{email?}', [DashboardController::class, 'doChangeEmailAddress'])->name('doChangeEmailAddress');
    Route::get('/change-email/{key}', [DashboardController::class, 'changeEmail'])->name('changeEmail');

    Route::middleware(['auth', 'web', 'member', '2fa', 'verified'])->controller(ProfileController::class)->group(function () {
        Route::get('security', 'securityIndex')->name('security');
        Route::get('profile', 'profile')->name('profile');
        Route::post('switch-role', 'switchRole')->name('switchRole');
        Route::post('profile/{user}/update', 'update')->name('profileUpdate');
        Route::post('user-company/update', 'updateUserCompany')->name('updateUserCompany');
        Route::post('check-email-password', 'checkEmailPassword')->name('checkEmailPassword');

        Route::prefix('profile/change-email')->name('change-email.')->group(function (){
            Route::post('', 'changeEmail')->name('request');
            Route::get('resend-link', 'changeEmailResendLink')->name('ResendLink');
            Route::get('request-cancel', 'changeEmailRequestCancel')->name('RequestCancel');
        });

        Route::prefix('profile/change-password')->name('change-password.')->group(function (){
            Route::post('', 'changePassword')->name('request');
        });

        Route::prefix('profile/one-time-passcode')->name('one-time-passcode.')->group(function () {
            Route::get('index', 'OneTimePasscodeIndex')->name('OneTimePasscodeIndex');
            Route::post('enable', 'OneTimePasscodeEnable')->name('enable');
            Route::post('enable/store', 'OneTimePasscodeEnableStore')->name('enableStore');
        });

        Route::post('preferences/update', 'updatePreference')->name('preferencesUpdate');
    });

    Route::controller(ProfileController::class)->group(function () {
        Route::get('export-data-post', 'exportDataPost');
        Route::get('export', 'exportData');
    });

    Route::prefix('/support')->name('support-ticket.')->group(function () {
        Route::get('/ticket', [ContactUsController::class, 'supportTicket'])->name('index');
        Route::post('validate-ticket-information', [SupportTicketController::class, 'validateInformation'])->name('validateInformation');
        Route::post('create', [SupportTicketController::class, 'create'])->name('create');
    });
    Route::get('/history', [SupportTicketController::class, 'history'])->name('history');


    // LaraCast notification ajax
    Route::get('/notify-flash', [Controller::class, 'ajaxFlash'])->name('flashNotifications');

    Route::post('user/reset/', [DashboardController::class, 'reset'])->name('usersManagementReset');

    Route::get('logout-clear', function () {
        saveLog((Auth::user()->details->first_name ?? '')." ".(Auth::user()->details->last_name ?? '') . " is  Logout", Auth::user(), [], "Logout");
        Session::flush();
        Auth::logout();
        return redirect('/login');
    })->middleware('auth');

    Route::controller(ContactUsController::class)->group(function () {
        Route::get('support/ticket', 'supportTicket');
        Route::post('/about/store', 'aboutStore')->name('aboutStore');
        Route::get('get-category/{platform}', 'getCategory');
        Route::post('/upload/editor/image', 'uploadImage')->name('uploadEditorImage');
    });

    Route::resource('/contact-us', ContactUsController::class);
    Route::get('files/{foldername}/{filename}', [ProfileController::class, 'downloadLink']);
});

// ajax call start
Route::controller(AjaxCallApiController::class)->group(function () {
    Route::post('main', 'mainAjax')->name('mainAjax');

    Route::post('/get-provider', 'getProvider')->name('getProvider');
    Route::post('/check-customer-status', 'checkCustomerStatus')->name('checkCustomerStatus');
    Route::post('/get-batch-info', 'getBatchInfo')->name('getBatchInfo');
    Route::post('/get-date-columns', 'getDateColumns')->name('getDateColumns');
    Route::get('/get-countries', 'getCountries')->name('getCountries');
    Route::post('/generate-encryption-key', 'generateEncryptionKey')->name('generateEncryptionKey');
    // ajax call end
});

Route::controller(HomeController::class)->group(function () {
    Route::get('locale/{locale}', 'localeChange')->name('localeChange');

    Route::get('languages/all', 'getAllLanguages')->name('getAllLanguages');
    Route::get('languages/pages/all', 'getAllPageLanguages')->name('getAllLanguagesStatus');
});

Route::fallback(function () {
    return abort(404);
});

/*---- START for member ----*/
Route::group(['prefix' => 'member', 'as' => 'member.', 'middleware' => ['auth', '2fa', 'member', 'verified']], function () {
    Route::prefix('todo')->as('todo.')->controller(TodoController::class)->group(function (){
        Route::get('assigned-list', 'AssignedListIndex')->name('assignedList');
        Route::get('get-assigned-list', 'getAssignedList')->name('getAssignedList');
    });

    Route::prefix('notification')->as('notification.')->controller(NotificationController::class)->group(function (){
        Route::get('get-list', 'getList')->name('getList');
        Route::get('destroy/all', 'destroyAll')->name('destroyAll');
        Route::get('destroy/{id}', 'destroy')->name('destroy');
    });

    Route::controller(OrderController::class)->group(function () {
        Route::get('gift-codes', 'myGiftCode')->name('GiftCodes');
        Route::post('cancel-gift-code', 'cancelGiftCode')->name('cancelGiftCode');
        Route::post('transfer-gift-code', 'transferGiftCode')->name('transferGiftCode');
        Route::get('get-searched-members', 'getSearchedMembers')->name('getSearchedMembers');
        Route::get('check-downline-user/{user_id}', 'checkDownlineUser')->name('checkDownlineUser');
        Route::get('my-gift-code-all', 'myGiftCodeAll')->name('myGiftCodeAll');
        Route::get('redeem-gift-code/{id}', 'redeemGiftCode')->name('redeemGiftCode');
        Route::post('redeem-gift-voucher', 'redeemGiftVoucher')->name('redeemGiftVoucher');
        Route::get('redeem-gift-codes', 'redeemCode')->name('redeemCode');
        Route::post('check-redeem-code', 'checkRedeemCode')->name('checkRedeemCode');
        Route::get('redemptions', 'redeemedGiftCode')->name('redeemedGiftCode');
        Route::get('redeemed-gift-code-all', 'redeemedGiftCodeAll')->name('redeemedGiftCodeAll');

        Route::prefix('/shop')->name('shop.')->group(function () {
            Route::get('/', 'index')->name('index');
            Route::post('add-to-cart', 'addToCart')->name('addToCart');
            Route::get('cart-detail', 'cartDetail')->name('cartDetail');
            Route::get('cart-all', 'cartAll')->name('cartAll');
            Route::get('confirm-your-order', 'confirmYourOrder')->name('confirmYourOrder');
            Route::delete('remove-cart-product', 'removeCartProduct')->name('removeCartProduct');
            Route::post('place-order', 'placeOrder')->name('placeOrder');
            Route::get('order-success', 'orderSuccess')->name('orderSuccess')->middleware('signed');
            Route::get('check-cash-amount', 'checkCashAmount')->name('checkCashAmount');
            Route::post('update-product-quantity', 'updateProductQuantity')->name('updateProductQuantity');
        });

        Route::prefix('/invoices')->name('invoices.')->group(function () {
            Route::get('/', 'invoicesIndex')->name('invoicesIndex');
            Route::get('list/all', 'invoicesListAll')->name('invoicesListAll');
        });
    });

    /* DASHBOARD */
    Route::controller(DashboardController::class)->group(function () {
        Route::get('dashboard', 'index')->name('dashboard');
        Route::post('dashboard/infinity-star-bonus-sum', 'InfinityStarBonusSum')->name('dashboard.chartData.InfinityStarBonusSum');
        Route::post('dashboard/chart-data', 'chartData')->name('dashboard.chartData');
        Route::post('dashboard/chart-data/monthly-bonus', 'chartDataMonthlyBonus')->name('dashboard.chartData.monthlyBonus');
        Route::get('my-logs', 'myLogs')->name('myLogs');
        Route::get('logs-serverside', 'logsServerside')->name('logsServerside');
        Route::get('get-all-members', 'getAllMembers')->name('getAllMembers');
        Route::post('transferAmount', 'transferAmount')->name('transferAmount');
        Route::get('get-notice-detail', 'getNoticeDetails')->name('getNoticeDetails');
        Route::post('update-notice-details', 'updateNoticeDetails')->name('updateNoticeDetails');
        Route::get('/show-invoice/{invoice_no}', 'showInvoice')->name('showInvoice');
        Route::get('header-date-time','headerDateTime');
    });

    Route::prefix('transactions')->name('transactions.')->controller(WalletTransactionController::class)->group(function () {
        Route::get('/', 'memberTransactions')->name('memberTransactions');
        Route::get('list/all', 'memberGetAllTransaction')->name('memberGetAllTransaction');
        Route::get('sub-transactions', 'memberGetSubTransaction')->name('memberGetSubTransaction');
    });

    Route::prefix('my-team')->name('my-team.')->controller(ManageTeamController::class)->group(function () {
        Route::get('', 'index')->name('index');
        Route::get('member-detail/{id}', 'memberDetail')->name('memberDetail');
        Route::get('list/all', 'all')->name('all');
        Route::post('store', 'store')->name('store');
        Route::get('hierarchy/users', 'hierarchyUsers')->name('hierarchyUsers');
        Route::get('network-chart', 'networkChartIndex')->name('networkChartIndex');
        Route::post('network-chart/data', 'networkChartData')->name('networkChartData');
    });

    Route::prefix('my-career')->name('my-career.')->controller(MyCareerDashboardController::class)->group(function () {
        Route::get('', 'index')->name('index');
    });

    Route::prefix('my-wallets')->as('my-wallets.')->controller(MyWalletsController::class)->group(function () {
        Route::get('/', 'index')->name('index');
    });

    Route::prefix('earnings')->name('earnings.')->controller(EarningsTransactionController::class)->group(function () {
        Route::get('/', 'memberEarningsTransactions')->name('memberEarningsTransactions');
        Route::get('list/all', 'memberEarningsGetAllTransaction')->name('memberEarningsGetAllTransaction');
        Route::get('weekly-statement/{data}', 'downloadWeeklyStatement')->name('downloadWeeklyStatement');
    });

    /* Deposit */
    Route::prefix('deposit')->name('deposit.')->controller(DepositController::class)->group(function () {
        Route::get('/deposits-list', 'index')->name('index');
        Route::get('/deposits-index', 'depositIndex')->name('depositIndex');
        Route::get('/currency/{currency_id}', 'getCurrency')->name('getCurrency');
        Route::get('/currency-guideline/{currency_id}', 'currencyGuideLine')->name('currencyGuideLine');
        Route::get('/deposit-option/{currency_id}', 'getDepositOption')->name('getDepositOption');
        Route::get('/deposit-address/{blockchain}', 'getDepositAddress')->name('getDepositAddress');
        Route::post('/crypto-data', 'verifyCryptoData')->name('verifyCryptoData');
        Route::get('/list', 'allDeposit')->name('allDeposit');
        Route::get('create', 'create')->name('createDeposit');
        Route::post('store', 'store')->name('store');
        Route::post('/fiat-deposit', 'verifyFiatDeposit')->name('verifyFiatDeposit');
        Route::get('/limocoin-deposit-option', 'getLimoCoinDepositOption')->name('getLimoCoinDepositOption');
    });

    /* Withdrawal */
    Route::prefix('withdrawal')->name('withdrawal.')->controller(WithdrawalController::class)->group(function () {
        Route::get('/withdrawals-list', 'index')->name('index');
        Route::get('/currency/{currency_id}', 'getCurrency')->name('getCurrency');
        Route::get('/currency-guideline/{currency_id}', 'currencyGuideLine')->name('currencyGuideLine');
        Route::get('/blockchain/{currency_id}', 'getBlockchain')->name('getBlockchain');
        Route::get('/list', 'allWithdrawal')->name('allWithdrawal');
        Route::get('create', 'create')->name('createWithdrawal');
        Route::post('store', 'store')->name('store');
        Route::post('/duplicate-withdrawal-data', 'getDuplicateWithdrawal')->name('getDuplicateWithdrawal');
    });

    /* Identity Verification */
    Route::prefix('identity-verification')->name('identity-verification.')->controller(IdentityVerificationController::class)->group(function () {
        Route::get('/', 'identityVerification')->name('identityVerification');
        Route::post('identity-verification-store', 'identityVerificationStore')->name('identityVerificationStore');
        Route::get('/identity-verification-status/{id}', 'showVerificationStatus')->name('showVerificationStatus');
    });

    /* Bonus Purchase Pool */
    Route::prefix('bonus-purchase-pool')->name('bonus-purchase-pool.')->group(function () {
        Route::get('/', [BonusPurchasePoolController::class, 'index'])->name('index');
        Route::post('/bonus-purchase-pool-store', [BonusPurchasePoolController::class, 'bonusPurchasePoolStore'])->name('bonusPurchasePoolStore');
    });
});

// csrlive end

Route::get('sponsor/{username}', [DashboardController::class, 'sponsor'])->name('sponsor');

Route::controller(TwoFAControllerCentral::class)->group(function (){
    Route::get('profile-two-fa-index', 'profileTwoFaIndex');
    Route::get('validate/2fa', 'validateTwoFa');
    Route::post('validate/2fa', 'validateTwoFa');
    Route::post('otp-request', 'OTPRequest');
});

Route::middleware(['auth'])->group(function () {
        Route::prefix('2fa')->controller(TwoFAControllerCentral::class)->group(function () {
                Route::get('', 'index');
                Route::post('', 'store');
                Route::post('verify', 'verify');
            }
        );
        Route::match(['get'], 'change-role/{role}', [DashboardController::class, 'changeRole']);
    }
);

