<?php

use App\Http\Controllers\ArbitrageController;
use App\Http\Controllers\PagesController;
use App\Nexus\Http\Controllers\NexusAuthController;
use App\Nexus\Http\Controllers\NexusDashboardController;
use App\Nexus\Http\Controllers\NexusApiController;
use App\Http\Controllers\Admin\AdminController;
use App\Http\Controllers\Admin\MailController;
use App\Http\Controllers\KNotificationController;
use App\Services\ChartService;
use App\Services\DummyChartService;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use App\Models\Plan;
use App\Models\Blog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

//Admin
Route::prefix('admin')->name('admin.')->group(function () {

    Route::middleware(['guest:admin', 'PreventBackHistory'])->group(function () {
        Route::get('/login', [AdminController::class, 'login'])->name('login');
        Route::post('/check', [AdminController::class, 'check'])->name('check');
    });

    Route::middleware(['auth:admin', 'PreventBackHistory'])->group(function () {
        Route::get('/dashboard', [AdminController::class, 'dashboard'])->name('dashboard');
        Route::get('/users', [AdminController::class, 'users_show'])->name('users.show');
        Route::get('/user_info/{user}', [AdminController::class, 'user_info'])->name('user_info');

        // bulk user action
        Route::post('/users/bulk-ban', [AdminController::class, 'bulkBan'])
            ->name('users.bulk-ban');

        Route::post('/users/bulk-delete', [AdminController::class, 'bulkDelete'])
            ->name('users.bulk-delete');

        Route::get('/unconfirmed-users', [AdminController::class, 'unconfirmed'])->name('unconfirmed');
        Route::post('/approve-unconfirmed/{user}', [AdminController::class, 'approveUnconfirmed'])->name('approve-unconfirmed');
        Route::post('/store-setup/{user}', [AdminController::class, 'storeSetup'])->name('store-setup');
        Route::get('/kyc-requests', [AdminController::class, 'kyc'])->name('kyc');
        Route::get('/kyc-info/{user}', [AdminController::class, 'kycInfo'])->name('kyc_info');
        Route::post('/kyc-update/{user}', [AdminController::class, 'kycUpdate'])->name('kyc_update');
        Route::post('/marketing-variables', [AdminController::class, 'marketingVariables'])->name('marketing_variables');
        Route::get('/edit{user}', [AdminController::class, 'users_edit'])->name('user.edit');
        Route::get('/investments', [AdminController::class, 'investment'])->name('investments');
        Route::get('/investment_info/{investment}', [AdminController::class, 'investment_info'])->name('investment.show');
        Route::post('/investment_f_profit_update/{id}', [AdminController::class, 'investment_f_profit_update'])->name('investment_f_profit_update');
        Route::get('/requests', [AdminController::class, 'requests'])->name('requests');
        Route::get('/request_info{deposit}', [AdminController::class, 'request_info'])->name('request_info');
        Route::get('/withdrawals', [AdminController::class, 'withdrawals'])->name('withdrawals');
        Route::get('/site_details', [AdminController::class, 'site_details'])->name('site_details');
        Route::post('/site_update', [AdminController::class, 'site_update'])->name('site_update');
        Route::get('/company_details', [AdminController::class, 'company_details'])->name('company_details');
        Route::patch('/company_update', [AdminController::class, 'company_update'])->name('company_update');
        Route::patch('/support_update', [AdminController::class, 'support_update'])->name('support_update');
        Route::get('/create_package', [AdminController::class, 'create_package'])->name('create_package');
        Route::post('/add_package', [AdminController::class, 'add_package'])->name('add_package');
        Route::get('/packages', [AdminController::class, 'packages'])->name('packages');
        Route::get('/mails', [AdminController::class, 'mails'])->name('mails.show');
        Route::get('/plan_edit{plan}', [AdminController::class, 'plan_edit'])->name('plan_edit');
        Route::patch('/plan_update{plan}', [AdminController::class, 'plan_update'])->name('plan_update');
        Route::delete('/plan_destroy{plan}', [AdminController::class, 'plan_destroy'])->name('plan_destroy');
        Route::patch('/update{user}', [AdminController::class, 'users_update'])->name('user.update');
        Route::post('/chartData{user}', [AdminController::class, 'chartData'])->name('user.chartData');
        Route::delete('/remove_user{user}', [AdminController::class, 'users_destroy'])->name('user.destroy');
        Route::delete('/multi_remove_users', [AdminController::class, 'multi_users_destroy'])->name('multi.user.destroy');
        Route::delete('/multi_all_remove_users', [AdminController::class, 'multi_all_users_destroy'])->name('multi.all.user.destroy');
        Route::post('/ban{user}', [AdminController::class, 'ban'])->name('ban');
        Route::get('/ban_page{user}', [AdminController::class, 'ban_page'])->name('ban_page');
        Route::post('/unban{user}', [AdminController::class, 'unban'])->name('unban');
        Route::patch('/approve_withdrawal{withdrawal}', [AdminController::class, 'withdraw_approve'])->name('withdraw_approve');
        Route::patch('/decline_withdrawal{withdrawal}', [AdminController::class, 'withdraw_decline'])->name('withdraw_decline');

        Route::get('/board-of-directors', [AdminController::class, 'bod'])->name('bod');
        Route::get('/add-board-of-directors', [AdminController::class, 'add_bod'])->name('add_bod');
        Route::post('/create-board-of-director', [AdminController::class, 'create_bod'])->name('create_bod');
        Route::get('/edit-board-of-director/{director}', [AdminController::class, 'edit_bod'])->name('edit_bod');
        Route::patch('/update-board-of-director/{director}', [AdminController::class, 'update_bod'])->name('update_bod');
        Route::delete('/destroy-board-of-director{director}', [AdminController::class, 'destroy_bod'])->name('destroy_bod');

        Route::get('/testimonials', [AdminController::class, 'testimonials'])->name('testimonials');
        Route::get('/add-testimonial', [AdminController::class, 'add_testimonial'])->name('add_testimonial');
        Route::get('/testimonial_edit/{testimonial}', [AdminController::class, 'testimonial_edit'])->name('testimonial_edit');
        Route::patch('/testimonial_update/{testimonial}', [AdminController::class, 'testimonial_update'])->name('testimonial_update');
        Route::post('/create-testimonial', [AdminController::class, 'create_testimonial'])->name('create_testimonial');
        Route::delete('/testimonial_destroy{testimonial}', [AdminController::class, 'testimonial_destroy'])->name('testimonial_destroy');

        Route::get('/change-password', [AdminController::class, 'password'])->name('password');

        Route::post('/change-current-password', [AdminController::class, 'changePassword'])->name('password.update');

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

        #email  route
        Route::post('/mailing', [MailController::class, 'sendEmail'])->name('mailing');

        //New Functionalities
        Route::get('/markets', [AdminController::class, 'markets'])->name('markets');

        Route::get('/create-market', [AdminController::class, 'createMarket'])->name('create-market');

        Route::post('/add-market', [AdminController::class, 'addMarket'])->name('add-market');

        Route::get('/edit-market/{market}', [AdminController::class, 'editMarket'])->name('edit-market');

        Route::post('/update-market/{market}', [AdminController::class, 'updateMarket'])->name('update-market');

        Route::delete('/market-delete{market}', [AdminController::class, 'marketDestroy'])->name('market-destroy');


        Route::get('/products', [AdminController::class, 'products'])->name('products');

        Route::get('/create-product', [AdminController::class, 'createProduct'])->name('create-product');

        Route::post('/add-product', [AdminController::class, 'addProduct'])->name('add-product');

        Route::get('/edit-product/{product}', [AdminController::class, 'editProduct'])->name('edit-product');

        Route::post('/update-product/{product}', [AdminController::class, 'updateProduct'])->name('update-product');

        Route::delete('/product-delete{product}', [AdminController::class, 'productDestroy'])->name('product-destroy');

        Route::get('/vendor-requests', [AdminController::class, 'appliedVendors'])->name('vendor-requests');

        Route::get('/vendor-request-details/{vendor}', [AdminController::class, 'vendorRequestDetails'])->name('vendor-request-details');

        Route::post('/vendor-request-decision/{vendor}', [AdminController::class, 'vendorRequestDecision'])->name('vendor-request-decision');

        Route::get('/pending-products', [AdminController::class, 'pendingProducts'])->name('pending-products');

        Route::get('/pending-product-details/{product}', [AdminController::class, 'pendingProductDetails'])->name('pending-product-details');

        Route::post('/pending-product-decision/{product}', [AdminController::class, 'pendingProductDecision'])->name('pending-product-decision');

        Route::get('/create-bid/{product}', [AdminController::class, 'createBid'])->name('create-bid');

        Route::post('/add-bid/{product}', [AdminController::class, 'addBid'])->name('add-bid');

        Route::get('/agent-requests', [AdminController::class, 'agentRequests'])->name('agent-requests');

        Route::get('/agent-request-details/{request}', [AdminController::class, 'agentRequestDetails'])->name('agent-request-details');

        Route::post('/request-seen/{request}', [AdminController::class, 'requestSeen'])->name('request-seen');

        Route::get('/grants', [AdminController::class, 'grants'])->name('grants');

        Route::get('/grant-details/{grant}', [AdminController::class, 'grantDetails'])->name('grant-details');

        Route::post('/grant-seen/{grant}', [AdminController::class, 'grantSeen'])->name('grant-seen');

        Route::get('/blogs', [AdminController::class, 'blogs'])->name('blogs');

        Route::get('/create-blog', [AdminController::class, 'createBlog'])->name('create-blog');

        Route::post('/add-blog', [AdminController::class, 'addBlog'])->name('add-blog');

        Route::get('/edit-blog/{blog}', [AdminController::class, 'editBlog'])->name('edit-blog');

        Route::post('/update-blog/{blog}', [AdminController::class, 'updateBlog'])->name('update-blog');

        Route::post('/delete-blog/{blog}', [AdminController::class, 'deleteBlog'])->name('delete-blog');

        Route::get('/agent-withdrawals', [AdminController::class, 'agentWithdrawals'])->name('agent-withdrawals');
        Route::patch('/approve-agent-withdrawal{withdrawal}', [AdminController::class, 'agentWithdrawApprove'])->name('agent.withdraw_approve');
        Route::patch('/decline-agent-withdrawal{withdrawal}', [AdminController::class, 'agentWithdrawDecline'])->name('agent.withdraw_decline');


        // Agent Dashboard
        Route::get('/agent-dashboard', [AdminController::class, 'agentDashboard'])->name('agent.dashboard');
        Route::get('/all-users', [AdminController::class, 'agentUsers'])->name('agent.users');
        Route::get('/user-details/{user}', [AdminController::class, 'agentUserInfo'])->name('agent.user_info');
        Route::get('/withdrawal-wallet', [AdminController::class, 'wallet'])->name('agent.wallet');
        Route::post('/add-wallet', [AdminController::class, 'addWallet'])->name('agent.add-wallet');
        Route::get('/withdraw-funds', [AdminController::class, 'withdraw'])->name('agent.withdraw');
        Route::post('/request-withdrawal', [AdminController::class, 'requestWithdrawal'])->name('agent.request-withdrawal');

        // Pause Bot
        Route::post('/bot/{id}/toggle-bot', [AdminController::class, 'toggleBotStatus'])->name('toggle_bot_status');

        // new
        Route::get('/ownership/{ownership}/edit', [AdminController::class, 'editOwnership'])->name('ownership.edit');
        Route::put('/ownership/{ownership}', [AdminController::class, 'updateOwnership'])->name('ownership.update');
        Route::delete('/ownership/{ownership}', [AdminController::class, 'deleteOwnership'])->name('ownership.delete');
        Route::get('/users/quick-search', [AdminController::class, 'usersQuickSearch'])->name('users.quick-search');
        Route::post('/ownership/{user}/store',   [AdminController::class, 'storeOwnership'])->name('ownership.store');

        // coupons
        Route::get('/coupons', [AdminController::class, 'coupons'])->name('coupons');
        Route::get('/coupons/create', [AdminController::class, 'createCoupon'])->name('coupons.create');
        Route::post('/coupons', [AdminController::class, 'storeCoupon'])->name('coupons.store');
        Route::get('/coupons/{coupon}/edit', [AdminController::class, 'editCoupon'])->name('coupons.edit');
        Route::put('/coupons/{coupon}', [AdminController::class, 'updateCoupon'])->name('coupons.update');
        Route::delete('/coupons/{coupon}', [AdminController::class, 'destroyCoupon'])->name('coupons.destroy');
        Route::get('/coupons/{coupon}/redemptions', [AdminController::class, 'couponRedemptions'])->name('coupons.redemptions');
    });
});



//Guest
Route::get('/', [PagesController::class, 'welcome'])->name('welcome');

Route::get('/com-soon', function () {
    return view('coming-soon');
})->name('coming-soon');

Route::get('/about-us', function () {
    return view('about');
})->name('about');

Route::get('/contact-us', function () {
    return view('contact');
})->name('contact');

Route::get('/privacy-policy', function () {
    return view('privacy-policy');
})->name('privacy-policy');

Route::get('/terms-of-use', function () {
    return view('terms-of-use');
})->name('terms-of-service');

Route::get('/community-guidelines', function () {
    return view('community-guidelines');
})->name('community-guidelines');


Route::get('/blog', function () {
    $blogs = Blog::orderBy('id', 'desc')->paginate(9);

    return view('blog', compact('blogs'));
})->name('blog');

Route::get('/blog-details/{blog}', function ($blog) {

    $blog = Blog::where('slug', $blog)->first();
    $recentBlogs = null;

    if ($blog) {
        $blog->increment('views');

        $recentBlogs = Blog::where('id', '!=', $blog->id)
            ->orderBy('id', 'desc') // Order by id in descending order to get the most recent first
            ->take(3) // Adjust the number of recent blogs you want to retrieve
            ->get();
    } else {
        return back();
    }


    return view('blog-details', compact('blog', 'recentBlogs'));
})->name('blog-details');

Auth::routes();


//User
Route::middleware(['auth', 'PreventBackHistory'])->group(function () {

    Route::get('/manual-sales', [ChartService::class, 'getManualSalesData'])->name('manualSalesData');

    Route::get('/dummy-sales', [DummyChartService::class, 'getDummySalesData'])->name('dummySalesData');

    Route::get('/banned', [App\Http\Controllers\ProfilePageController::class, 'banned'])->name('banned');

    Route::get('/setup-2fa-authentication', [App\Http\Controllers\ProfilePageController::class, 'twofaPage'])->name('twofaPage');

    Route::post('/2fa-decision', [App\Http\Controllers\ProfilePageController::class, 'twofaDecision'])->name('twofaDecision');

    Route::get('/2fa-authentication', [App\Http\Controllers\ProfilePageController::class, 'twoFaVerification'])->name('2fa.verification');

    Route::post('/resend-2fa-token', [App\Http\Controllers\ProfilePageController::class, 'resendTwoFaMail'])->name('2fa.resend-token');

    Route::post('/2fa-verify', [App\Http\Controllers\ProfilePageController::class, 'verifyTwoFa'])->name('2fa.verify');

    Route::get('/add-store', [App\Http\Controllers\PagesController::class, 'addStore'])->name('add-store');

    Route::post('/create-store', [App\Http\Controllers\UserController::class, 'createStore'])->name('create-store');

    Route::get('/your-earning-expectation', [App\Http\Controllers\PagesController::class, 'expectation'])->name('expectation');

    Route::post('/add-expectation', [App\Http\Controllers\UserController::class, 'addExpectation'])->name('add-expectation');

    Route::get('/store-setup', [App\Http\Controllers\PagesController::class, 'storeSetup'])->name('store-setup');

    Route::post('/setup-payment', [App\Http\Controllers\PagesController::class, 'setupPayment'])->name('setup-payment');

    Route::get('/setup-info/{deposit}', [App\Http\Controllers\PagesController::class, 'setupInfo'])->name('setup-info');

    Route::get('/setup-made/{deposit}', [App\Http\Controllers\PagesController::class, 'setupMade'])->name('setup_made');

    Route::get('/complete-kyc', [App\Http\Controllers\PagesController::class, 'kyc'])->name('kyc');

    Route::post('/add-kyc-details', [App\Http\Controllers\UserController::class, 'addKyc'])->name('add-kyc');

    Route::middleware(['verified'])->get('/profile-photo', function () {
        return view('profile_photo');
    })->name('profile_photo');

    Route::post('/add-profile-photo', [App\Http\Controllers\UserController::class, 'profile_photo'])->name('store.profile_photo');

    Route::post('/account_submit', [App\Http\Controllers\UserController::class, 'account_details'])->name('account.submit');

    Route::post('/withdrawal-plan-submit', [App\Http\Controllers\UserController::class, 'withdrawal_plan'])->name('withdrawal_plan.submit');

    Route::get('/home', [App\Http\Controllers\ProfilePageController::class, 'index'])->name('home');

    Route::get('/my-profile', [App\Http\Controllers\ProfilePageController::class, 'profile'])->name('profile');

    Route::get('/deposit-funds', [App\Http\Controllers\ProfilePageController::class, 'deposit'])->name('deposit');
    
    Route::get('/deposit-funds-alt', [App\Http\Controllers\ProfilePageController::class, 'depositAlt'])->name('deposit-alt');
    
    Route::post('/deposit/confirm', [App\Http\Controllers\DepositConfirmController::class, 'confirm'])->name('deposit.confirm');

    Route::get('/deposit-fds', [App\Http\Controllers\ProfilePageController::class, 'dep'])->name('dep');

    Route::get('/first-generation', [App\Http\Controllers\ProfilePageController::class, 'firstGen'])->name('first_gen');

    Route::get('/second-generation', [App\Http\Controllers\ProfilePageController::class, 'secondGen'])->name('second_gen');

    Route::get('/third-generation', [App\Http\Controllers\ProfilePageController::class, 'thirdGen'])->name('third_gen');

    Route::get('/withdrawal-wallet', [App\Http\Controllers\ProfilePageController::class, 'wallet'])->name('wallet');

    Route::post('/update-wallet', [App\Http\Controllers\UserController::class, 'walletUpdate'])->name('wallet_update');

    // Route::get('/investment-history', [App\Http\Controllers\InvestmentHistoryController::class, 'index'])->name('investment_history');

    // Route::get('/investment{id}', [App\Http\Controllers\InvestmentHistoryController::class, 'investment'])->name('investment_profile');

    Route::post('/clear-balance', [App\Http\Controllers\ProfilePageController::class, 'clear_balance'])->name('user.clear_balance');

    Route::get('/withdraw', [App\Http\Controllers\UserController::class, 'withdraw_index'])->name('index.withdraw');

    Route::get('/team-rebates-balance', [App\Http\Controllers\UserController::class, 'teamRebates'])->name('team_rebates');

    Route::post('/withdraw-main', [App\Http\Controllers\UserController::class, 'withdrawMain'])->name('withdraw_main');

    Route::post('/withdraw-rebates', [App\Http\Controllers\UserController::class, 'withdrawRebates'])->name('withdraw_rebates');

    Route::post('/rebate-to-balance', [App\Http\Controllers\UserController::class, 'rebateToBalance'])->name('rebate_to_balance');

    Route::post('/store-setup-bonus-to-balance', [App\Http\Controllers\UserController::class, 'storeToBalance'])->name('store_to_balance');

    Route::post('/ai-bonus-to-balance', [App\Http\Controllers\UserController::class, 'aiToBalance'])->name('ai_to_balance');

    Route::post('/loyalty-bonus-to-balance', [App\Http\Controllers\UserController::class, 'loyaltyToBalance'])->name('loyalty_to_balance');

    Route::post('/payment', [App\Http\Controllers\UserController::class, 'payment'])->name('submit.payment');

    Route::get('/payment-info/{deposit}', [App\Http\Controllers\UserController::class, 'paymentInfo'])->name('payment_info');

    Route::get('/payment-made/{deposit}', [App\Http\Controllers\UserController::class, 'paymentMade'])->name('payment_made');

    Route::get('/sales-bot', [App\Http\Controllers\UserController::class, 'tradingBot'])->name('trading_bot');

    Route::post('/trade', [App\Http\Controllers\UserController::class, 'invest'])->name('trade');

    Route::post('/move-to-balance', [App\Http\Controllers\UserController::class, 'moveToBalance'])->name('move_to_balance');

    Route::get('/trading-history/{plan}', [App\Http\Controllers\UserController::class, 'tradingHistory'])->name('trading_history');

    // Main marketer dashboard
    Route::get('/marketer-dashboard', [App\Http\Controllers\MarketerController::class, 'marketer'])->name('marketer');

    // Member detail page
    Route::get('/member/{username}', [App\Http\Controllers\MarketerController::class, 'member'])->name('member');

    // Email verification status pages (NEW)
    Route::get('/marketer/email-verified', [App\Http\Controllers\MarketerController::class, 'emailVerified'])->name('marketer.email-verified');
    Route::get('/marketer/email-unverified', [App\Http\Controllers\MarketerController::class, 'emailUnverified'])->name('marketer.email-unverified');

    // KYC verification status pages (NEW)
    Route::get('/marketer/kyc-verified', [App\Http\Controllers\MarketerController::class, 'kycVerified'])->name('marketer.kyc-verified');
    Route::get('/marketer/kyc-unverified', [App\Http\Controllers\MarketerController::class, 'kycUnverified'])->name('marketer.kyc-unverified');

    // Cache clearing endpoint
    Route::get('/marketer/clear-cache', [App\Http\Controllers\MarketerController::class, 'clearCache'])->name('marketer.clear-cache');


    Route::get('/support', [App\Http\Controllers\UserController::class, 'support'])->name('support');

    Route::get('/change-password', function () {
        return view('change_password');
    })->name('change_pass');

    Route::post('/change-current-password', [App\Http\Controllers\UserController::class, 'changePassword'])->name('password.change');

    //New Functionalities

    Route::get('/bid-marketplace', [App\Http\Controllers\PagesController::class, 'bidMarkets'])->name('bid-markets');

    Route::get('/sell-off-marketplace/{ownership}', [App\Http\Controllers\PagesController::class, 'sellMarkets'])->name('sell-markets');

    Route::get('/sell-off-details/{ownership}/{market}', [App\Http\Controllers\PagesController::class, 'sellDetails'])->name('sell-details');

    Route::get('/marketplace/{slug}/{market}', [App\Http\Controllers\PagesController::class, 'marketplace'])->name('marketplace');

    Route::get('/product-details/{slug}', [App\Http\Controllers\PagesController::class, 'productDetails'])->name('product-details');

    Route::get('/category/{category}', [App\Http\Controllers\PagesController::class, 'category'])->name('category');

    Route::post('/place-bid/{product}', [App\Http\Controllers\ArbitrageController::class, 'placeBid'])->name('place-bid');

    Route::post('/sell-item/{ownership}/{market}', [App\Http\Controllers\ArbitrageController::class, 'sellItem'])->name('sell-item');

    Route::get('/ai-bot-plans', [App\Http\Controllers\PagesController::class, 'aiPlans'])->name('ai-plans');

    Route::get('/ai-purchase-plan/{plan}', [App\Http\Controllers\PagesController::class, 'aiPurchase'])->name('ai-purchase');

    Route::post('/ai-buy-plan/{plan}', [App\Http\Controllers\ArbitrageController::class, 'aiBuy'])->name('ai-buy');

    Route::get('/ai-dashboard', [App\Http\Controllers\PagesController::class, 'aiDashboard'])->name('ai-dashboard');

    Route::get('/ai-activity/{investment}/{name}', [App\Http\Controllers\PagesController::class, 'aiActivity'])->name('ai-activity');

    Route::get('/fund-ai/{investment}', [App\Http\Controllers\PagesController::class, 'aiFund'])->name('fund-ai');

    Route::post('/ai-fund/{investment}', [App\Http\Controllers\ArbitrageController::class, 'aiFund'])->name('ai-fund');

    Route::get('/withdraw-from-ai/{investment}', [App\Http\Controllers\PagesController::class, 'aiWithdraw'])->name('withdraw-ai');

    Route::post('/ai-withdraw/{investment}', [App\Http\Controllers\ArbitrageController::class, 'aiWithdraw'])->name('ai-withdraw');

    Route::get('/affiliate-vendor-application', [App\Http\Controllers\PagesController::class, 'vendorApply'])->name('vendor-apply');

    Route::post('/vendor-applied', [App\Http\Controllers\ArbitrageController::class, 'vendorApplied'])->name('vendor-applied');

    Route::get('/affiliate-vendor-dashboard', [App\Http\Controllers\PagesController::class, 'vendorDashboard'])->name('vendor-dashboard');

    Route::get('/add-vendor-products', [App\Http\Controllers\PagesController::class, 'addVendorProducts'])->name('add-vendor-products');

    Route::get('/affiliate-product-details/{slug}', [App\Http\Controllers\PagesController::class, 'affiliateProductDetails'])->name('affiliate-product-details');

    Route::get('/send-through-agent', [App\Http\Controllers\PagesController::class, 'agentForm'])->name('agent-form');

    Route::post('/agent-send', [App\Http\Controllers\ArbitrageController::class, 'agentSend'])->name('agent-send');

    Route::get('/send-product-form/{product}', [App\Http\Controllers\PagesController::class, 'sendProduct'])->name('send-product-form');

    Route::post('/send-product/{product}', [App\Http\Controllers\ArbitrageController::class, 'sendProduct'])->name('send-product');

    // Route::get('/blog-details/{blog}', [App\Http\Controllers\PagesController::class, 'blogDetails'])->name('blog-details');

    Route::get('/apply-for-grant', [App\Http\Controllers\PagesController::class, 'grantApply'])->name('grant-apply');

    Route::post('/grant-application', [App\Http\Controllers\ArbitrageController::class, 'grantApplication'])->name('grant-application');

    Route::get('/grant-history', [App\Http\Controllers\PagesController::class, 'grants'])->name('grants');

    //// COUPON ///////
    Route::get('/redeem-coupon', [App\Http\Controllers\CouponController::class, 'showRedeemPage'])->name('coupon.redeem.page');
    Route::post('/coupon/redeem', [App\Http\Controllers\CouponController::class, 'redeem'])->name('coupon.redeem');


    //// Account Deletion Route ////
    Route::post('/account/delete', [App\Http\Controllers\AccountDeletionController::class, 'deleteAccount'])->name('account.delete');

    //// ICTP ////
    Route::get('/ictp-withdrawal', [PagesController::class, 'ictpWithdrawPage'])->name('ictp_withdraw_page');
    Route::post('/ictp-to-balance', [ArbitrageController::class, 'ictpToBalance'])->name('ictp_to_balance');
});

// Route::get('/admin/kyc/notify-all', [KNotificationController::class, 'notifyAllVerified'])
//     ->name('kyc.notify-all');

// Route::get('/kyc-cleanup-temp', function () {
//     // 🔒 Optional safety key (recommended)
//     if (request('key') !== 'mySuperSecretKey123') {
//         abort(403);
//     }

//     // 1. Get every file currently in the images directory
//     $allFiles = Storage::disk('public')->files('images');

//     if (empty($allFiles)) {
//       return 'No files found in images directory.';
//     }

//     // 2. Pull all filenames referenced in the DB (approved, pending, whoever)
//     $referencedFiles = App\Models\User::whereNotNull('avatar')
//         ->orWhereNotNull('dl_front')
//         ->orWhereNotNull('dl_back')
//         ->get(['avatar', 'dl_front', 'dl_back'])
//         ->flatMap(fn($user) => [$user->avatar, $user->dl_front, $user->dl_back])
//         ->filter()
//         ->map(fn($filename) => "images/{$filename}")
//         ->values()
//         ->toArray();

//     // 3. Anything not in the DB is an orphan — delete it
//     $orphans = array_diff($allFiles, $referencedFiles);

//     if (empty($orphans)) {
//         return 'No orphaned files found. Storage is clean!';
//     }

//     foreach ($orphans as $file) {
//         Storage::disk('public')->delete($file);
//     }

//     return count($orphans) . ' orphaned files deleted successfully.';
// });

// Route::get('/kyc-cleanup-temp', function () {
//     if (request('key') !== 'mySuperSecretKey123') {
//         abort(403);
//     }

//     $users = App\Models\User::where('kyc_status', 1)
//         ->where(function ($q) {
//             $q->whereNotNull('avatar')
//               ->orWhereNotNull('dl_front')
//               ->orWhereNotNull('dl_back');
//         })
//         ->get(['id', 'dl_front', 'dl_back']);

//     if ($users->isEmpty()) {
//         return 'No files to delete.';
//     } 

//     $deleted = 0;

//     foreach ($users as $user) {
//         foreach (['dl_front', 'dl_back'] as $field) {
//             if ($user->$field) {
//                 $path = "images/{$user->$field}";
//                 if (Storage::disk('public')->exists($path)) {
//                     Storage::disk('public')->delete($path);
//                     $deleted++;
//                 }
//             }
//         }

//         // Null out the columns
//         // App\Models\User::where('id', $user->id)->update([
//         //     'dl_front' => null,
//         //     'dl_back'  => null,
//         // ]);
//     }

//     return "{$deleted} files deleted across {$users->count()} users.";
// });

// Route::get('/kyc-cleanup-temp', function () {
//     $pendingUsers = App\Models\User::where('kyc_status', 2)
//         ->whereNotNull('dl_front')
//         ->orWhereNotNull('dl_back')
//         ->get();

//     if ($pendingUsers->isEmpty()) {
//         return "No pending KYC requests found.";
//     }

//     $settings = App\Models\SiteDetail::whereIn('title', [
//         'is_kyc_promo', 'kyc_promo_amount', 'num_of_reff_per_bonus',
//         'reff_bonus_amount', 'promo_start_date'
//     ])->pluck('description', 'title');

//     foreach ($pendingUsers as $user) {
//         DB::transaction(function () use ($user, $settings) {
//             // 1. Approve
//             $user->update(['kyc_status' => 1]);

//             // 2. Grant Submitter Bonus
//             if (filter_var($settings->get('is_kyc_promo'), FILTER_VALIDATE_BOOLEAN)) {
//                 $promoAmount = (float) $settings->get('kyc_promo_amount', 0);
//                 if ($promoAmount > 0) {
//                     $user->increment('balance', $promoAmount);
//                     App\Models\Transaction::create([
//                         'user_id' => $user->id,
//                         'amount'  => $promoAmount,
//                         'type'    => 'kyc_promo',
//                         'status'  => 1,
//                     ]);
//                 }
//             }

//             // 3. Referrer Bonus
//             $threshold    = (int) $settings->get('num_of_reff_per_bonus', 0);
//             $bonusAmount  = (float) $settings->get('reff_bonus_amount', 0);

//             if ($user->referrer_id && $threshold > 0 && $bonusAmount > 0 && $user->type == 'normal') {
//                 $referrer  = $user->referrer;
//                 $startDate = Carbon::parse($settings->get('promo_start_date', '2025-12-14'));

//                 $eligibleReferrals = $referrer->referrals()
//                     ->where('kyc_status', 1)
//                     ->whereNull('referral_bonus_processed_at')
//                     ->where('created_at', '>=', $startDate)
//                     ->get();

//                 if ($eligibleReferrals->count() > 0) {
//                     $count      = $eligibleReferrals->count();
//                     $totalBonus = $bonusAmount * $count;
//                     $now        = now();

//                     App\Models\User::whereIn('id', $eligibleReferrals->pluck('id'))->update([
//                         'referral_bonus_processed_at' => $now,
//                     ]);

//                     $referrer->increment('loyalty_bonus', $totalBonus);

//                     App\Models\Transaction::create([
//                         'user_id' => $referrer->id,
//                         'amount'  => $totalBonus,
//                         'type'    => 'loyalty_bonus',
//                         'status'  => 1,
//                         'notes'   => "Loyalty bonus ({$count} users). Processed at {$now}.",
//                     ]);
//                 }
//             }

//             // 4. Delete dl_front and dl_back only
//             foreach (['dl_front', 'dl_back'] as $field) {
//                 if ($user->$field && Storage::disk('public')->exists("images/{$user->$field}")) {
//                     Storage::disk('public')->delete("images/{$user->$field}");
//                 }
//             }
//         });
//     }

//     return "{$pendingUsers->count()} KYC requests approved successfully.";
// });

//Email verification
Route::get('/email/verify', function () {

    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');

Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
    $request->fulfill();

    return redirect('/home');
})->middleware(['auth', 'signed'])->name('verification.verify');

Route::post('/email/verification-notification', function (Request $request) {
    $request->user()->sendEmailVerificationNotification();

    return back()->with('message', 'A fresh verification link has been sent to your email address.');
})->middleware(['auth', 'throttle:1,2'])->name('verification.resend');

// Route::get('/publish-notifications', function () {
//     // Run the vendor:publish command for notifications
//     Artisan::call('vendor:publish', [
//         '--provider' => 'Illuminate\\Auth\\AuthServiceProvider',
//         '--tag' => 'notifications',
//     ]);

//     return 'Vendor files for notifications published!';
// });

// Route::get('/publish-queue-migration', function () {
//     $exitCode = Artisan::call('queue:table');
//     return response()->json([
//         'message' => 'Queue migration published successfully!',
//         'exit_code' => $exitCode
//     ]);
// });

Route::get('/cache-clear', function () {
    Artisan::call('view:clear');
    // //     Artisan::call('config:cache');
    // //     Artisan::call('config:clear');
    // //     Artisan::call('event:cache');
    // //     Artisan::call('event:clear');
    // //     Artisan::call('cache:clear');

    //     // Artisan::call('optimize:clear');
    return response()->json([
        'message' => 'Ran successfully!'
    ]);
})->middleware('auth:admin');

// Route::get('/cron-jjobs', function () {
//     // $cronJobs = shell_exec('crontab -l');
//     $cronJobs = shell_exec('php -v');
//     dd($cronJobs);
// });


// NEXUS � Public auth routes
Route::prefix('nexus')->name('nexus.')->group(function () {
    Route::get('/login', [NexusAuthController::class, 'showLogin'])->name('login');
    Route::post('/login', [NexusAuthController::class, 'login'])->name('login.submit');
    Route::post('/logout', [NexusAuthController::class, 'logout'])->name('logout');
});

// NEXUS � Protected routes (Phase 5 will fill this out)
Route::get('/nexus/overview', function () {
    return view('nexus.overview');
})->middleware('nexus.admin')->name('nexus.overview');

// NEXUS -- Protected dashboard and API routes
Route::prefix('nexus')->name('nexus.')->middleware('nexus.admin')->group(function () {

    // Dashboard pages
    Route::get('/dashboard',  [NexusDashboardController::class, 'overview'])->name('dashboard');
    Route::get('/users',      [NexusDashboardController::class, 'users'])->name('users');
    Route::get('/markets',    [NexusDashboardController::class, 'markets'])->name('markets');
    Route::get('/controls',   [NexusDashboardController::class, 'controls'])->name('controls');
    Route::get('/bots',       [NexusDashboardController::class, 'bots'])->name('bots');
    Route::get('/audit',      [NexusDashboardController::class, 'audit'])->name('audit');
    Route::get('/terminal',   function () {
        return view('nexus.terminal');
    })->name('terminal');

    // JSON API
    Route::prefix('api')->name('api.')->group(function () {
        Route::get('/session-status',    [NexusApiController::class, 'sessionStatus'])->name('session-status');
        Route::get('/economy',           [NexusApiController::class, 'economyHealth'])->name('economy');
        Route::get('/top-bidders',       [NexusApiController::class, 'topBidders'])->name('top-bidders');
        Route::get('/pending-sells',     [NexusApiController::class, 'pendingSells'])->name('pending-sells');
        Route::get('/audit-log',         [NexusApiController::class, 'auditLog'])->name('audit-log');
        Route::post('/config',           [NexusApiController::class, 'updateConfig'])->name('config');
        Route::post('/emergency-pause',  [NexusApiController::class, 'toggleEmergencyPause'])->name('emergency-pause');
        Route::post('/plan-ranges',      [NexusApiController::class, 'updatePlanRanges'])->name('plan-ranges');

        // Phase 6.5 -- Session History & Detail
        Route::get('/session-detail/{id}',      [NexusApiController::class, 'sessionDetail'])->name('session-detail');
        Route::get('/sessions/export',           [NexusApiController::class, 'sessionExport'])->name('sessions-export');

        // Phase 6.5 -- Interactive Users Table (AJAX)
        Route::get('/users',                     [NexusApiController::class, 'usersTable'])->name('users-table');
        Route::get('/users/export',              [NexusApiController::class, 'usersExport'])->name('users-export');

        // Phase 6.5 -- Market Exports
        Route::get('/markets/win-rates/export',  [NexusApiController::class, 'marketWinRatesExport'])->name('market-win-rates-export');
        Route::get('/markets/categories/export', [NexusApiController::class, 'categoryActivityExport'])->name('category-activity-export');

        // Phase 6.5 -- Month Selector Data
        Route::get('/available-months',          [NexusApiController::class, 'availableMonths'])->name('available-months');
        // Phase 8 -- Bot Governance
        Route::get('/bots/table',                [NexusApiController::class, 'botsTable'])->name('bots-table');
        Route::get('/bots/export',               [NexusApiController::class, 'botsExport'])->name('bots-export');
        // Terminal
        Route::get('/terminal/stream',           [NexusApiController::class, 'terminalStream'])->name('api.terminal-stream');
    });
});

// User-facing live terminal API (outside nexus group -- regular user auth only)
Route::middleware(['auth'])->group(function () {
    Route::get('/api/terminal/live', [\App\Nexus\Http\Controllers\NexusApiController::class, 'terminalPublic'])->name('api.terminal-live');
});

Route::middleware(['auth'])->group(function () {
    Route::get('/live', function () {
        return view('live-terminal');
    })->name('live-terminal');
});