<?php

declare(strict_types=1);

use App\Enums\UserActions;
use App\Http\Controllers\Helpers\Permissions\UserPermissions;
use App\Http\Controllers\Market\CartController;
use App\Http\Controllers\Market\ProductController;
use App\Http\Controllers\Market\StoreController;
use App\Http\Controllers\Market\ShipmentController;
use App\Http\Controllers\Market\FarmerController;
use App\Http\Controllers\Pages\AccountSettingsPageController;
use App\Http\Controllers\Pages\TransferMyCreditPageController;
use App\Http\Controllers\Pages\UserModifyAdminPageController;
use App\Http\Controllers\Pages\UserListPageController;
use App\Http\Controllers\Photos\PhotoGallery;
use App\Http\Controllers\UserManagement\CreateUserControllerUltimate;
use App\Models\Market\Store;
use Hyperf\Codec\Json;
use Hypervel\Support\Facades\Route;
use Hypervel\Support\Facades\Auth;
use App\Http\Controllers\LoginController;

use App\Models\User;

use Hypervel\Support\Facades\Cache;

use Hypervel\Support\Facades\Config;

use Hypervel\Support\Facades\Response;

use App\Enums\UserTypes;

use Hyperf\Redis\RedisFactory;
use Hypervel\Support\Facades\Storage;
use Psr\Http\Message\ResponseInterface;

use Hypervel\Support\Facades\Session;

use Hypervel\Http\Request;
use App\Http\Controllers\viewHelperController;

use Hypervel\Support\Facades\File;
use App\Http\Controllers\PageMemoryController;
use App\Http\Controllers\FilesMainController;

use App\Models\FileContent;
use routes\Market\Web_stores;
use routes\Web_debug;
use routes\Web_files;
use App\Http\Controllers\Support\Inertia;
use App\Http\Controllers\Support\VueRouteMap;
use App\Http\Controllers\Support\AnnouncementController;
use App\Http\Controllers\Support\SSEController;
use App\Http\Controllers\Property\PropertyManagementController;
use App\Http\Controllers\Accounting\AccountingController;
use App\Http\Controllers\Subscription\SubscriptionPlanController;
use App\Http\Controllers\Subscription\SubscriptionController;

VueRouteMap::registerRoutes();

Route::get('/health', function () {
    $checks = [];
    $allOk = true;

    try {
        \Hypervel\Support\Facades\DB::select('SELECT 1');
        $checks['db'] = 'ok';
    } catch (\Throwable $e) {
        $checks['db'] = 'fail: ' . $e->getMessage();
        $allOk = false;
    }

    try {
        \Hypervel\Support\Facades\Redis::ping();
        $checks['redis'] = 'ok';
    } catch (\Throwable $e) {
        $checks['redis'] = 'fail: ' . $e->getMessage();
        $allOk = false;
    }

    if ($allOk) {
        return 'OK';
    }

    return response()->json(['status' => 'degraded', 'checks' => $checks], 503);
});

Route::get('/manifest.json', [\App\Http\Controllers\PwaManifestController::class, 'manifest']);

// Route::get('/', function () {
//     return view('layouts.default');
// }, ['middleware' => 'auth']);

// Route::get('/app', function () {
//     $page = Inertia::render('Home');
//     return view('layouts.application-layout', ['page' => $page]);
// }, ['middleware' => ['web', 'auth']]);


Route::get('/home-data', function () {
    $userCount = \App\Models\User::count();
    $storeCount = \App\Models\Market\Store::where('is_active', true)->count();
    $pendingOrders = \App\Models\Market\PosSession::where('status', 'PENDING')->count();

    /** @var \App\Models\User $user */
    $user = Auth::user();
    $personalBalance = $user->total_balance ?? 0;

    $totalTransactionsNo = \App\Models\GlobalTransaction::count();
    $totalTransactionsPhp = \App\Models\GlobalTransaction::sum('amount');
    $projectedIncomeToday = \App\Models\GlobalTransaction::whereDate('created_at', today())
        ->where('flow', \App\Enums\Market\TransactionFlow::INCOME->value)
        ->sum('amount');

    // Store-scoped today metrics (for STORE_OWNER / STORE_MANAGER dashboards).
    $acctType = $user?->acct_type instanceof \App\Enums\UserTypes
        ? $user->acct_type
        : \App\Enums\UserTypes::tryFrom($user?->acct_type ?? '');
    $isBig3 = in_array($acctType, [
        \App\Enums\UserTypes::ULTIMATE,
        \App\Enums\UserTypes::SUPER_OPERATOR,
        \App\Enums\UserTypes::OPERATOR,
    ], true);

    $todayTxQuery = \App\Models\GlobalTransaction::whereDate('created_at', today());
    if (!$isBig3 && $user) {
        $storeIds = \App\Models\Market\Store::where('owner_id', $user->id)
            ->orWhereHas('managers', fn ($q) => $q->where('user_id', $user->id))
            ->pluck('id');
        $todayTxQuery->whereIn('store_id', $storeIds);
    }
    $transactionsTodayNo = (clone $todayTxQuery)->count();
    $cashFlowToday = (clone $todayTxQuery)
        ->selectRaw('COALESCE(SUM(amount * flow), 0) as net')
        ->value('net');
    $myStoresCount = !$isBig3 && $user
        ? \App\Models\Market\Store::where('owner_id', $user->id)
            ->orWhereHas('managers', fn ($q) => $q->where('user_id', $user->id))
            ->count()
        : $storeCount;

    $cooperativeTotalNo = 0;
    $cooperativeMembersNo = 0;
    $myCooperativesNo = 0;
    $pendingMembersNo = 0;
    if ($acctType === \App\Enums\UserTypes::COORDINATOR && $user) {
        $cooperativeTotalNo = \App\Models\Market\Organization::where('type', 'COOPERATIVE')->count();
        $cooperativeMembersNo = \App\Models\Market\CooperativeMember::whereHas('organization', fn ($q) => $q->where('created_by', $user->id))->count();
        $myCooperativesNo = \App\Models\Market\Organization::where('type', 'COOPERATIVE')->where('created_by', $user->id)->withCount('members')->count();
        $myCoopIds = \App\Models\Market\Organization::where('type', 'COOPERATIVE')->where('created_by', $user->id)->pluck('id');
        $pendingMembersNo = \App\Models\Market\CooperativeMember::whereIn('organization_id', $myCoopIds)->where('created_at', '>=', now()->subDays(7))->count();
    }

    // Cooperative chapter dashboards (officer / member).
    $chapterInfo = null;
    $chapterMemberCount = 0;
    $childChapterCount = 0;
    $newMembers7d = 0;
    if ($acctType === \App\Enums\UserTypes::COOP_OFFICER && $user) {
        $myChapterMember = \App\Models\ChapterMember::join('chapters', 'chapters.id', 'chapter_members.chapter_id')
            ->where('chapter_members.user_id', $user->id)->where('chapter_members.is_active', true)
            ->orderByRaw("FIELD(chapters.level,'national','region','province','city','municipal','barangay')")
            ->select('chapter_members.*', 'chapters.id as chapter_id_resolved', 'chapters.name as chapter_name', 'chapters.level as chapter_level', 'chapters.hashkey as chapter_hashkey', 'chapters.cooperative_id as chapter_coop_id')
            ->first();
        if ($myChapterMember) {
            $myChapterId = (int) $myChapterMember->chapter_id_resolved;
            $chapterMemberCount = \App\Models\ChapterMember::where('chapter_id', $myChapterId)->where('is_active', true)->count();
            $childChapterCount = \App\Models\Chapter::where('parent_id', $myChapterId)->where('is_active', true)->count();
            $newMembers7d = \App\Models\ChapterMember::where('chapter_id', $myChapterId)->where('is_active', true)->where('created_at', '>=', now()->subDays(7))->count();
            $cooperativeHash = $myChapterMember->chapter_coop_id
                ? \App\Models\Market\Organization::where('id', $myChapterMember->chapter_coop_id)->value('hashkey')
                : null;
            $chapterInfo = [
                'chapter_name'    => $myChapterMember->chapter_name,
                'chapter_level'   => $myChapterMember->chapter_level,
                'chapter_hashkey' => $myChapterMember->chapter_hashkey,
                'cooperative_hash' => $cooperativeHash,
            ];
        }
    }
    if ($acctType === \App\Enums\UserTypes::COOP_MEMBER && $user) {
        $myChapterMember = \App\Models\ChapterMember::join('chapters', 'chapters.id', 'chapter_members.chapter_id')
            ->where('chapter_members.user_id', $user->id)->where('chapter_members.is_active', true)
            ->orderByRaw("FIELD(chapters.level,'barangay','city','municipal','province','region','national')")
            ->select('chapter_members.*', 'chapters.id as chapter_id_resolved', 'chapters.name as chapter_name', 'chapters.level as chapter_level', 'chapters.cooperative_id as chapter_coop_id')
            ->first();
        if ($myChapterMember) {
            $myChapterId = (int) $myChapterMember->chapter_id_resolved;
            $chapterMemberCount = \App\Models\ChapterMember::where('chapter_id', $myChapterId)->where('is_active', true)->count();
            $cooperativeName = $myChapterMember->chapter_coop_id
                ? \App\Models\Market\Organization::where('id', $myChapterMember->chapter_coop_id)->value('name')
                : null;
            $chapterInfo = [
                'chapter_name'     => $myChapterMember->chapter_name,
                'chapter_level'    => $myChapterMember->chapter_level,
                'cooperative_name' => $cooperativeName,
                'member_count'     => $chapterMemberCount,
            ];
        }
    }

    $isOperator = $acctType === \App\Enums\UserTypes::OPERATOR;
    $operatorStoreIds = [];
    if ($isOperator && $user) {
        $operatorStoreIds = \App\Models\Market\Store::where('owner_id', $user->id)
            ->orWhereHas('managers', fn($q) => $q->where('user_id', $user->id))
            ->pluck('id')->toArray();
    }
    $activePosSessionsNo = $isOperator
        ? \App\Models\Market\PosSession::whereIn('store_id', $operatorStoreIds)->where('status', 'PENDING')->count()
        : \App\Models\Market\PosSession::where('status', 'PENDING')->count();
    $managedStoresNo = $isOperator ? count($operatorStoreIds) : $storeCount;
    $todayRevenueOperator = $isOperator
        ? \App\Models\GlobalTransaction::whereDate('created_at', today())
            ->whereIn('store_id', $operatorStoreIds)
            ->where('flow', \App\Enums\Market\TransactionFlow::INCOME->value)
            ->sum('amount')
        : $projectedIncomeToday;

    $props = [
        'props' => [
            'user' => $user,
            'stats' => [
                'total_users_no' => $userCount,
                'active_stores_no' => $storeCount,
                'pending_orders_no' => $pendingOrders,
                'total_balance_php' => number_format((float) $personalBalance, 2),
                'total_transactions_no' => $totalTransactionsNo,
                'total_transactions_php' => number_format((float) $totalTransactionsPhp, 2),
                'projected_income_today' => number_format((float) $projectedIncomeToday, 2),
                'transactions_today_no' => $transactionsTodayNo,
                'cash_flow_today_php' => number_format((float) $cashFlowToday, 2),
                'my_stores_no' => $myStoresCount,
                'cooperative_total_no' => $cooperativeTotalNo,
                'cooperative_members_no' => $cooperativeMembersNo,
                'my_cooperatives_no' => $myCooperativesNo,
                'pending_members_no' => $pendingMembersNo,
                'active_pos_sessions_no' => $activePosSessionsNo,
                'managed_stores_no' => $managedStoresNo,
                'today_revenue_php' => number_format((float) $todayRevenueOperator, 2),
                'chapter_member_count' => $chapterMemberCount,
                'child_chapter_count' => $childChapterCount,
                'new_members_7d' => $newMembers7d,
            ],
        ],
    ];

    if ($chapterInfo !== null) {
        $props['props']['chapter_info'] = $chapterInfo;
    }

    return response()->json($props);
});

// Route::get('/{page}', [viewHelperController::class, 'servePageFragment'], ['middleware' => 'auth']);




Route::get('/p/{page}/s/{data}', [viewHelperController::class, 'servePageFragmentWithTemplate'], ['middleware' => 'auth']);
Route::get('/p/{page}/s/', [viewHelperController::class, 'servePageFragmentWithTemplate'], ['middleware' => 'auth']);

Route::get('/login', function (\Hypervel\Http\Request $request) {
    if (Auth::check() && !$request->has('logged_out')) {
        return redirect('/');
    }
    $page = Inertia::render('Auth.Login', []);
    return view('layouts.application-layout', compact('page'));
}, ['middleware' => 'web']);

Route::get('/sp/login', function (\Hypervel\Http\Request $request) {
    if (Auth::check() && !$request->has('logged_out')) {
        return redirect('/');
    }
    $page = Inertia::render('Auth.Login', []);
    return view('layouts.application-layout', compact('page'));
}, ['middleware' => 'web']);

Route::get('/old/login', function () {
    return view('login');
}, ['middleware' => 'web']);

Route::get('/get/isloggedin', function () {
    $isLoggedIn = Auth::check();
    if ($isLoggedIn) {
        $user = Auth::user();
        if (!$user || !$user->active) {
            Auth::logout();
            if (session() && method_exists(session(), 'flush')) {
                session()->flush();
            }
            return Response::json(['isloggedin' => false]);
        }

        // Check Redis forced_logout flag (set by admin remote-logout)
        $hashkey = $user->hashkey ?? null;
        if ($hashkey && \Hypervel\Support\Facades\Redis::get("forced_logout:{$hashkey}")) {
            \Hypervel\Support\Facades\Redis::del("forced_logout:{$hashkey}");
            Auth::logout();
            if (session() && method_exists(session(), 'flush')) {
                session()->flush();
            }
            return Response::json(['isloggedin' => false]);
        }
    }
    return Response::json(['isloggedin' => $isLoggedIn]);
}, ['middleware' => 'web']);

Route::get('/sse/stream', [SSEController::class, 'stream'], ['middleware' => 'auth']);


Route::get('/get/user/acct-type', function () {
    $user = Auth::user();
    return Response::json([
        'acct_type' => $user->acct_type,
    ]);
}, ['middleware' => 'auth']);




Route::get('/get/isExec', function () {
    $execCommand = Auth::user()->exec_command ?? '';
    $user = User::findOrFail(Auth::id());
    $user->exec_command = '';
    $user->save();
    return Response::raw($execCommand);
}, ['middleware' => 'auth']);


Route::post('/post/loginnow', [LoginController::class, 'authenticate'], ['middleware' => 'web']);
Route::get('/session/extend', [LoginController::class, 'extendcurrentSession'], ['middleware' => 'auth']);

Route::get('/sp/listviews', function () {
    return Response::json(viewHelperController::getAllViews());
}, ['middleware' => 'ultimate']);

Route::get('/debug/asset', function () {

}, ['middleware' => 'auth']);

Route::get('/debug/assetview', function () {
    return view('adminlte');
}, ['middleware' => 'auth']);



Route::get('/account_settings/details', [AccountSettingsPageController::class, 'listDetails'], ['middleware' => ['web', 'auth']]);
Route::post('/User/Settings/Details', [AccountSettingsPageController::class, 'listSettings'], ['middleware' => ['web', 'auth']]);
Route::post('/user/changemypassword', [AccountSettingsPageController::class, 'changepassword'], ['middleware' => ['web', 'auth']]);
Route::post('/user/updatephoto', [AccountSettingsPageController::class, 'updatePhoto'], ['middleware' => ['web', 'auth']]);
Route::post('/User/Settings/Run/Scripts', [AccountSettingsPageController::class, 'listRunScripts'], ['middleware' => ['web', 'auth']]);

Route::get('/user/note/content', [AccountSettingsPageController::class, 'getUserNotes'], ['middleware' => ['web', 'auth']]);
Route::get('/user/note/dismiss', [AccountSettingsPageController::class, 'clearUserNotes'], ['middleware' => ['web', 'auth']]);

Route::get('/go/logoutnow', [AccountSettingsPageController::class, 'logoutnow'], ['middleware' => 'auth']);
Route::get('/logout', [AccountSettingsPageController::class, 'logoutnow'], ['middleware' => 'auth']);

Route::get('/admin/users/list', [UserListPageController::class, 'Response_ListChildrenofCurrentUser'], ['middleware' => 'auth']);
Route::post('/admin/user/details', [UserModifyAdminPageController::class, 'Response_UserDetails'], ['middleware' => 'auth']);
Route::post('/user/details/children', [UserModifyAdminPageController::class, 'Response_childrenofTargetUser'], ['middleware' => 'auth']);
Route::post('/admin/user/children/direct', [UserModifyAdminPageController::class, 'Response_directChildrenofTargetUser'], ['middleware' => 'auth']);


Route::post('/admin/user/disable', [UserModifyAdminPageController::class, 'Response_DisableUser'], ['middleware' => 'auth']);
Route::post('/admin/user/enable', [UserModifyAdminPageController::class, 'Response_EnableUser'], ['middleware' => 'auth']);
Route::post('/admin/user/delete', [UserModifyAdminPageController::class, 'Response_DeleteUser'], ['middleware' => 'auth']);

Route::post('/admin/user/note/content', [UserModifyAdminPageController::class, 'Response_ViewNotes'], ['middleware' => 'auth']);
Route::post('/admin/user/note/delete', [UserModifyAdminPageController::class, 'Response_DeleteNotes'], ['middleware' => 'auth']);
Route::post('/admin/user/note/update', [UserModifyAdminPageController::class, 'Response_ReplaceNotes'], ['middleware' => 'auth']);

Route::post('/admin/user/exec/content', [UserModifyAdminPageController::class, 'Response_ViewExec'], ['middleware' => 'auth']);
Route::post('/admin/user/exec/update', [UserModifyAdminPageController::class, 'Response_ReplaceExec'], ['middleware' => 'auth']);
Route::post('/admin/user/exec/delete', [UserModifyAdminPageController::class, 'Response_DeleteExec'], ['middleware' => 'auth']);


Route::post('/admin/user/details/update', [UserModifyAdminPageController::class, 'Response_UpdateUserDetails'], ['middleware' => 'auth']);
Route::post('/admin/user/password/reset', [UserModifyAdminPageController::class, 'Response_ResetUserPassword'], ['middleware' => 'auth']);
Route::post('/admin/logout/force/user', [UserModifyAdminPageController::class, 'Response_LogoutUser'], ['middleware' => 'auth']);
Route::post('/admin/user/roles/get', [UserModifyAdminPageController::class, 'Response_UserRoles'], ['middleware' => 'auth']);
Route::post('/admin/user/store/detach', [UserModifyAdminPageController::class, 'Response_DetachStore'], ['middleware' => 'auth']);
Route::post('/admin/user/roles/all', [UserModifyAdminPageController::class, 'Response_AllRoles'], ['middleware' => 'auth']);
Route::post('/admin/user/roles/change', [UserModifyAdminPageController::class, 'Response_ChangeUserRoles'], ['middleware' => 'auth']);
Route::post('/admin/user/session/extend', [UserModifyAdminPageController::class, 'Response_ExtendUserSessions'], ['middleware' => 'auth']);

Route::post('/admin/list/usertype/create', [CreateUserControllerUltimate::class, 'listAllUserTypesforSelectHTML'], ['middleware' => 'auth']);
Route::post('/admin/user/list/numbers/hash', [CreateUserControllerUltimate::class, 'listAllUsersforParentSelectHTML'], ['middleware' => 'auth']);
Route::post('/admin/user/number/exists', [CreateUserControllerUltimate::class, 'checkIfUserMobileNumberExists'], ['middleware' => 'auth']);
Route::post('/admin/user/username/exists', [CreateUserControllerUltimate::class, 'checkIfUsernameExists'], ['middleware' => 'auth']);
Route::post('/admin/user/create', [CreateUserControllerUltimate::class, 'CreateUser'], ['middleware' => 'auth']);



Route::post('/user/sendmycredit', [TransferMyCreditPageController::class, 'Response_TransferMyCredit'], ['middleware' => 'auth']);


// ── Subscriptions (user-facing) ──────────────────────────────────────────
Route::get('/subscription/plans', [SubscriptionController::class, 'listAvailablePlans'], ['middleware' => 'auth']);
Route::get('/subscription/my', [SubscriptionController::class, 'mySubscription'], ['middleware' => 'auth']);
Route::get('/subscription/invoices', [SubscriptionController::class, 'myInvoices'], ['middleware' => 'auth']);
Route::post('/subscription/pay/wallet', [SubscriptionController::class, 'payWithWallet'], ['middleware' => 'auth']);

// ── Subscription Plans (admin/ultimate only) ─────────────────────────────
Route::get('/admin/subscription/plans', [SubscriptionPlanController::class, 'listPlans'], ['middleware' => 'ult']);
Route::post('/admin/subscription/plan/create', [SubscriptionPlanController::class, 'createPlan'], ['middleware' => 'ult']);
Route::post('/admin/subscription/plan/update', [SubscriptionPlanController::class, 'updatePlan'], ['middleware' => 'ult']);
Route::post('/admin/subscription/plan/toggle', [SubscriptionPlanController::class, 'togglePlan'], ['middleware' => 'ult']);
Route::post('/admin/subscription/list', [SubscriptionPlanController::class, 'listAllSubscriptions'], ['middleware' => 'ult']);


Route::get('/test/upload', function () {
    $cache = Cache::get('querycache:5324fb1ee26f771b9d87ae56f822bd99++++85838d9513d840ff389e75c60d7c4a40');
    // $fileData = Storage::get('test/images.jpg');
    return Response::json($cache);
    // $title = 'Test FIle Now';
// $description = 'This is a test file list entry';
// $details = ['status' => 'inves', 'public' => false];
// $categories = 'product,images';
// $tags = 'test,product,images';



    // $data = FilesMainController::uploadFileList(
//     $fileData,
//     $title,
//     $filename ?? '',
//     $description,
//     $details,
//     $categories,
//     $tags
// );

    // $filelist_hash = '5ae2d383-4156-4afd-95aa-e6d0984aa118Ks6oZlcvLVKtwvPX9QkrhOE72zK0XKh7MXnZeQ81HOjUbuI6c8Q4E7noQvth5UzVSAeO8E76Y9Wdm2s3Jiiyl10BmjslkYjg7mr3';
// return FilesMainController::viewFilebyFileListHash( $filelist_hash);

    // return $data;
}, ['middleware' => 'auth']);


Route::get('/test/viewfile', function () {
    $file = FileContent::first();

    if (!$file) {
        abort(404, 'File not found');
    }
    $content = $file->content;

    if (is_resource($content)) {
        $content = stream_get_contents($content);
    }

    return Response::make($content, 200, [
        'Content-Type' => 'application/octet-stream',
        'Content-Disposition' => 'inline; filename="file.bin"',
        'Content-Length' => strlen($content),
    ]);
}, ['middleware' => 'auth']);






Route::post('/Products/Admin/New/', [
    'as' => 'admin.products.new',
    'uses' => ProductController::class . '@createNew_Admin',
    'middleware' => ['auth', 'module:products']
]);

Route::post('/Products/Admin/FuzzySearch', [
    'as' => 'admin.products.fuzzy.search',
    'uses' => ProductController::class . '@fuzzySearchByName',
    'middleware' => ['auth', 'module:products']
]);

Route::post('/Products/Admin/Edit/', [
    'as' => 'admin.products.edit',
    'uses' => ProductController::class . '@editProductAdmin',
    'middleware' => ['auth', 'module:products']
]);

Route::post('/Products/Admin/Edit/Store', [
    'as' => 'admin.products.bystore.edit',
    'uses' => ProductController::class . '@editProductAdmin',
    'middleware' => ['auth', 'module:products']
]);


Route::post('/Products/Admin/AddtoStore/', [
    'as' => 'admin.products.addtostore',
    'uses' => ProductController::class . '@AddProducttoStore',
    'middleware' => ['auth', 'module:products']
]);

Route::post('/Products/Admin/RemovefronStore/', [
    'as' => 'admin.products.removefromstore',
    'uses' => ProductController::class . '@RemoveProductFromStore',
    'middleware' => ['auth', 'module:products']
]);




Route::post('/View/Product/Details/data/withStores', [
    'as' => 'admin.products.view.data.addstore',
    'uses' => ProductController::class . '@viewProductwithAddStoreData',
    'middleware' => 'auth'
]);






Route::post('/Products/New/Category/Datalist', [
    'as' => 'admin.products.category.datalist.data',
    'uses' => ProductController::class . '@getCategories',
    'middleware' => 'auth'
]);

Route::post('/Products/New/SubCategory/Datalist', [
    'as' => 'admin.products.subcategory.datalist.data',
    'uses' => ProductController::class . '@getSubcategories',
    'middleware' => 'auth'
]);


Route::post('/View/Product/Details/data', [
    'as' => 'admin.products.view.data',
    'uses' => ProductController::class . '@viewProductDetails',
    'middleware' => 'auth'
]);

Route::post('/View/Product/Details/ByStore/data', [
    'as' => 'admin.products.bystore.view.data',
    'uses' => ProductController::class . '@viewProductDetailsByStoreEdit',
    'middleware' => 'auth'
]);



Route::post('/Market/Products/List', [
    'as' => 'products.list.data',
    'uses' => ProductController::class . '@listProductsData',
]);

Route::post('/Admin/Products/List', [
    'as' => 'admin.products.list.data',
    'uses' => ProductController::class . '@listProducts_Admin',
    'middleware' => 'auth'
]);

Route::post('/Admin/Product/Delete', [
    'as' => 'admin.product.delete',
    'uses' => ProductController::class . '@deleteProduct_Admin',
    'middleware' => 'auth'
]);

Route::post('/Admin/Product/ToggleStatus', [
    'as' => 'admin.product.toggle_status',
    'uses' => ProductController::class . '@toggleProductStatus_Admin',
    'middleware' => 'auth'
]);



Route::post('/File/Upload/{category}', [FilesMainController::class, 'UploadFilefromRequest'], ['middleware' => 'auth']);

Route::get('/api/products/photo-search', [\App\Http\Controllers\Market\ProductPhotoSearchController::class, 'search'], ['middleware' => 'auth']);
Route::post('/api/products/photo-download', [\App\Http\Controllers\Market\ProductPhotoSearchController::class, 'download'], ['middleware' => 'auth']);

Route::get('/RequestData/File/{filelist_hash}', [
    'as' => 'requestdata.file.view',
    'uses' => 'App\Http\Controllers\FilesMainController@viewFilebyFileListHash',
]);


Route::post('/Request/Photos/{type}', [
    'as' => 'request.photos',
    'uses' => PhotoGallery::class . '@handle',
    'middleware' => 'auth'
]);



Route::post('/Store/New', [StoreController::class, 'store'], ['middleware' => ['auth', 'module:stores']]);
Route::post('/Store/AutoCreate', [StoreController::class, 'autoCreate'], ['middleware' => ['auth', 'module:stores']]);
Route::post('/Store/New/Category/Datalist', [StoreController::class, 'getCategories'], ['middleware' => ['auth', 'module:stores']]);
Route::post('/Store/New/SubCategory/Datalist', [StoreController::class, 'getSubcategories'], ['middleware' => ['auth', 'module:stores']]);


Route::post('/View/Store/Details/data', [
    'as' => 'store.details',
    'uses' => StoreController::class . '@viewStoreDetails'
]);


Route::post('/Store/Edit', [StoreController::class, 'update'], ['middleware' => ['auth', 'module:stores']]);

Route::post('/Edit/Store/Details/data', [
    'as' => 'store.details.editing',
    'uses' => StoreController::class . '@editStoreDetails',
    'middleware' => ['auth', 'module:stores']
]);



Route::post('/ListStores/List/data', [
    'as' => 'stores.list.data',
    'uses' => StoreController::class . '@listStoresActiveDataAll',
    // 'middleware' => 'auth'
]);


Route::post('/ListStores/MyStores/data', [
    'as' => 'stores.my.list.data',
    'uses' => StoreController::class . '@listStoresForCurrentUser',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Admin/Stores/Selectable', [
    'as' => 'admin.stores.selectable',
    'uses' => StoreController::class . '@listSelectableStoresForAddingProduct',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Products/AssignToStore/', [
    'as' => 'products.assign.to.store',
    'uses' => ProductController::class . '@AssignProductToOwnStore',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Products/UnassignFromStore/', [
    'as' => 'products.unassign.from.store',
    'uses' => ProductController::class . '@RemoveProductFromStore',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Products/GlobalList', [
    'as' => 'products.global.list',
    'uses' => ProductController::class . '@listGlobalProductsForPicker',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Products/AssignedStores/', [
    'as' => 'products.assigned.stores',
    'uses' => ProductController::class . '@getAssignedStoresForProduct',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Admin/Stores/List', [
    'as' => 'admin.stores.list.data',
    'uses' => StoreController::class . '@listStores_Admin',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Store/Cooperatives/List', [
    'as' => 'store.cooperatives.list',
    'uses' => StoreController::class . '@listCooperativesForStore',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Admin/Store/Delete', [
    'as' => 'admin.store.delete',
    'uses' => StoreController::class . '@deleteStore_Admin',
    'middleware' => ['auth', 'module:stores']
]);

Route::post('/Admin/Store/ToggleStatus', [
    'as' => 'admin.store.toggle_status',
    'uses' => StoreController::class . '@toggleStoreStatus_Admin',
    'middleware' => ['auth', 'module:stores']
]);


Route::post('/Edit/Store/Product/remove/', [
    'as' => 'store.product.remove',
    'uses' => StoreController::class . '@removeProductfromStore',
    'middleware' => 'auth'
]);

// Announcements
Route::get('/Announcements/Latest', [AnnouncementController::class, 'latest']);
Route::post('/Admin/Announcements/List', [AnnouncementController::class, 'index'], ['middleware' => 'auth']);
Route::post('/Admin/Announcement/Store', [AnnouncementController::class, 'store'], ['middleware' => 'auth']);
Route::post('/Admin/Announcement/Update', [AnnouncementController::class, 'update'], ['middleware' => 'auth']);
Route::post('/Admin/Announcement/Delete', [AnnouncementController::class, 'destroy'], ['middleware' => 'auth']);
Route::post('/Admin/Announcement/ToggleStatus', [AnnouncementController::class, 'toggleStatus'], ['middleware' => 'auth']);



//TODO Add Route for StoreUpdate Edit

// Global Transactions
Route::post('/admin/transactions/list', [\App\Http\Controllers\GlobalTransactionController::class, 'list'], ['middleware' => ['auth', 'module:transactions']]);
Route::post('/admin/transactions/create', [\App\Http\Controllers\GlobalTransactionController::class, 'store'], ['middleware' => ['auth', 'module:transactions']]);
Route::post('/admin/transactions/types', [\App\Http\Controllers\GlobalTransactionController::class, 'getTypes'], ['middleware' => ['auth', 'module:transactions']]);


// Property Management
Route::post('/admin/properties/list', [PropertyManagementController::class, 'listProperties'], ['middleware' => ['auth', 'module:properties']]);
Route::post('/admin/properties/referrals', [PropertyManagementController::class, 'listReferrals'], ['middleware' => ['auth', 'module:properties']]);

// Accounting & Reports
Route::post('/admin/accounting/tree', [AccountingController::class, 'getAccountsTree'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/leaf', [AccountingController::class, 'getLeafAccounts'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/daily', [AccountingController::class, 'getDailyTransactions'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/daily/save', [AccountingController::class, 'saveDailyTransactions'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/transactions', [AccountingController::class, 'listTransactions'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/transactions/delete', [AccountingController::class, 'deleteTransaction'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/reports', [AccountingController::class, 'listReports'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/reports/monthly', [AccountingController::class, 'getMonthlyReport'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/accounts/create', [AccountingController::class, 'createAccount'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/accounts/update', [AccountingController::class, 'updateAccount'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/accounts/archive', [AccountingController::class, 'archiveAccount'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/accounts/restore', [AccountingController::class, 'restoreAccount'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/accounts/move', [AccountingController::class, 'moveAccount'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/theme', [AccountingController::class, 'getThemeInfo'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/theme/drift', [AccountingController::class, 'getThemeDrift'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/theme/apply', [AccountingController::class, 'applyTheme'], ['middleware' => ['auth', 'module:accounting']]);
Route::post('/admin/accounting/theme/set', [AccountingController::class, 'setTheme'], ['middleware' => ['auth', 'module:accounting']]);

// POS Routes
Route::post('/api/pos/access-keys/list', [\App\Http\Controllers\Admin\PosAccessKeyController::class, 'index'], ['middleware' => ['auth', 'module:pos']]);
Route::post('/api/pos/access-keys/create', [\App\Http\Controllers\Admin\PosAccessKeyController::class, 'store'], ['middleware' => ['auth', 'module:pos']]);
Route::post('/api/pos/access-keys/delete', [\App\Http\Controllers\Admin\PosAccessKeyController::class, 'destroy'], ['middleware' => ['auth', 'module:pos']]);
Route::post('/api/pos/access-keys/toggle', [\App\Http\Controllers\Admin\PosAccessKeyController::class, 'toggleStatus'], ['middleware' => ['auth', 'module:pos']]);

Route::post('/api/pos/start', [\App\Http\Controllers\Market\PosController::class, 'startSession'], ['middleware' => 'module:pos']); // Allow guest access via key
Route::post('/api/pos/session', [\App\Http\Controllers\Market\PosController::class, 'getSession'], ['middleware' => 'module:pos']); // Public/Guest access
Route::post('/api/pos/add-item', [\App\Http\Controllers\Market\PosController::class, 'addItem'], ['middleware' => 'module:pos']);
Route::post('/api/pos/remove-item', [\App\Http\Controllers\Market\PosController::class, 'removeItem'], ['middleware' => 'module:pos']);
Route::post('/api/pos/complete', [\App\Http\Controllers\Market\PosController::class, 'completeSession'], ['middleware' => 'module:pos']);
Route::post('/api/pos/sync-offline', [\App\Http\Controllers\Market\PosController::class, 'syncOffline'], ['middleware' => 'module:pos']);
Route::post('/api/pos/void', [\App\Http\Controllers\Market\PosController::class, 'voidSession'], ['middleware' => 'module:pos']);
Route::post('/api/pos/stats', [\App\Http\Controllers\Market\PosController::class, 'getTodayStats'], ['middleware' => 'module:pos']);
Route::post('/api/pos/get-customers', [\App\Http\Controllers\Market\PosController::class, 'getCustomers'], ['middleware' => 'module:pos']);
Route::post('/api/pos/sessions/list', [\App\Http\Controllers\Market\PosController::class, 'getPosSessions'], ['middleware' => ['auth', 'module:pos']]);


// Shipment Routes
Route::post('/Shipments/List', [ShipmentController::class, 'listShipments'], ['middleware' => ['auth', 'module:shipments']]);
Route::post('/Shipments/Create', [ShipmentController::class, 'createNewShipment'], ['middleware' => ['auth', 'module:shipments']]);
Route::post('/Shipments/Status/Update', [ShipmentController::class, 'updateShipmentStatus'], ['middleware' => ['auth', 'module:shipments']]);
Route::post('/Couriers/List', [ShipmentController::class, 'listCouriers'], ['middleware' => ['auth', 'module:shipments']]);
Route::post('/Couriers/Create', [ShipmentController::class, 'createCourier'], ['middleware' => ['auth', 'module:shipments']]);

// Farmer Management Routes
Route::post('/Farmers/Register', [FarmerController::class, 'registerFarmer'], ['middleware' => ['auth', 'module:farmers']]);
Route::post('/Farmers/List', [FarmerController::class, 'listFarmers'], ['middleware' => ['auth', 'module:farmers']]);
Route::post('/Farmers/Verify', [FarmerController::class, 'verifyFarmer'], ['middleware' => ['auth', 'module:farmers']]);
Route::post('/Organizations/List', [FarmerController::class, 'listOrganizations'], ['middleware' => ['auth', 'module:farmers']]);
Route::post('/Organizations/Create', [FarmerController::class, 'createOrganization'], ['middleware' => ['auth', 'module:farmers']]);

// UserInfo Routes
Route::post('/UserInfo/Get', [\App\Http\Controllers\Market\UserInfoController::class, 'getUserInfo'], ['middleware' => 'auth']);
Route::post('/UserInfo/Update', [\App\Http\Controllers\Market\UserInfoController::class, 'updateUserInfo'], ['middleware' => 'auth']);
Route::post('/UserInfo/SearchEmergencyContact', [\App\Http\Controllers\Market\UserInfoController::class, 'searchEmergencyContact'], ['middleware' => 'auth']);

// Cooperative Module Routes
Route::post('/Cooperatives/List', [\App\Http\Controllers\Market\CooperativeController::class, 'listCooperatives'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Get', [\App\Http\Controllers\Market\CooperativeController::class, 'getCooperative'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Join', [\App\Http\Controllers\Market\CooperativeController::class, 'joinCooperative'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Create', [\App\Http\Controllers\Market\CooperativeController::class, 'createCooperative'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Member/Add', [\App\Http\Controllers\Market\CooperativeController::class, 'addMember'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Member/Register', [\App\Http\Controllers\Market\CooperativeController::class, 'registerMember'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Member/Update', [\App\Http\Controllers\Market\CooperativeController::class, 'updateMember'], ['middleware' => ['auth', 'module:cooperatives']]);

// Governance Module Routes
Route::post('/Governance/Resolutions/List', [\App\Http\Controllers\Market\GovernanceController::class, 'listResolutions'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Governance/Resolutions/Create', [\App\Http\Controllers\Market\GovernanceController::class, 'createResolution'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Governance/Resolutions/Vote', [\App\Http\Controllers\Market\GovernanceController::class, 'castVote'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Governance/Resolutions/Status/Update', [\App\Http\Controllers\Market\GovernanceController::class, 'updateResolutionStatus'], ['middleware' => ['auth', 'module:cooperatives']]);

// Cooperative Document Routes
Route::post('/Cooperatives/Documents/List', [\App\Http\Controllers\Market\CooperativeDocumentController::class, 'listDocuments'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Documents/Upload', [\App\Http\Controllers\Market\CooperativeDocumentController::class, 'uploadDocument'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Documents/Revise', [\App\Http\Controllers\Market\CooperativeDocumentController::class, 'reviseDocument'], ['middleware' => ['auth', 'module:cooperatives']]);
Route::post('/Cooperatives/Documents/Delete', [\App\Http\Controllers\Market\CooperativeDocumentController::class, 'deleteDocument'], ['middleware' => ['auth', 'module:cooperatives']]);

// Financial & Credit Routes
Route::post('/Financial/Wallet/Get', [\App\Http\Controllers\Market\CreditController::class, 'getWalletData'], ['middleware' => ['auth', 'module:credits']]);
Route::post('/Financial/Credit/TopUp', [\App\Http\Controllers\Market\CreditController::class, 'topUp'], ['middleware' => ['auth', 'module:credits']]);
Route::post('/Financial/Credit/Transfer', [\App\Http\Controllers\Market\CreditController::class, 'transferCredit'], ['middleware' => ['auth', 'module:credits']]);
Route::post('/Financial/Credit/SearchUsers', [\App\Http\Controllers\Market\CreditController::class, 'searchUsers'], ['middleware' => ['auth', 'module:credits']]);
Route::post('/Financial/Qrph/Get', [\App\Http\Controllers\Market\CreditController::class, 'getQrphCode'], ['middleware' => 'auth']);
Route::post('/Financial/Qrph/Set', [\App\Http\Controllers\Market\CreditController::class, 'setQrphCode'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/Financial/Qrph/Decode', [\App\Http\Controllers\Market\CreditController::class, 'decodeQrph'], ['middleware' => ['auth', 'ultimate']]);

// UserSettings Routes
Route::post('/UserSettings/Get', [\App\Http\Controllers\Market\UserSettingsController::class, 'getSettings'], ['middleware' => 'auth']);
Route::post('/UserSettings/Update', [\App\Http\Controllers\Market\UserSettingsController::class, 'updateSettings'], ['middleware' => 'auth']);

// UserAdditionalDetails Routes
Route::post('/UserAdditionalDetails/Get', [\App\Http\Controllers\UserManagement\UserAdditionalDetailsController::class, 'getDetails'], ['middleware' => 'auth']);
Route::post('/UserAdditionalDetails/UpdateCooperatives', [\App\Http\Controllers\UserManagement\UserAdditionalDetailsController::class, 'updateCooperatives'], ['middleware' => 'auth']);
Route::post('/UserAdditionalDetails/SearchByCooperative', [\App\Http\Controllers\UserManagement\UserAdditionalDetailsController::class, 'searchUsersByCooperative'], ['middleware' => 'auth']);
Route::post('/UserAdditionalDetails/GetCooperatives', [\App\Http\Controllers\UserManagement\UserAdditionalDetailsController::class, 'getUserCooperatives'], ['middleware' => 'auth']);

// Cart Routes
Route::post('/cart/get', [CartController::class, 'getCart'], ['middleware' => ['auth', 'module:cart']]);
Route::post('/cart/add', [CartController::class, 'addItem'], ['middleware' => ['auth', 'module:cart']]);
Route::post('/cart/update', [CartController::class, 'updateItem'], ['middleware' => ['auth', 'module:cart']]);
Route::post('/cart/remove', [CartController::class, 'removeItem'], ['middleware' => ['auth', 'module:cart']]);
Route::post('/cart/clear', [CartController::class, 'clearCart'], ['middleware' => ['auth', 'module:cart']]);

// Public Cooperative Registration Routes
Route::get('/api/public/cooperative/{hkey}', [\App\Http\Controllers\Market\CooperativeController::class, 'publicGetCooperative']);
Route::post('/api/public/cooperative/register', [\App\Http\Controllers\Market\CooperativeController::class, 'publicRegisterMember']);
Route::post('/api/public/cooperative/complete-membership', [\App\Http\Controllers\Market\CooperativeController::class, 'publicCompleteMembership']);

// Public Chapter Registration Routes
Route::get('/api/public/chapter/{hkey}', [\App\Http\Controllers\Support\ChapterController::class, 'publicGetChapter']);
Route::post('/api/public/chapter/register', [\App\Http\Controllers\Support\ChapterController::class, 'publicRegisterToChapter']);

// Public User Self-Registration Routes
Route::post('/api/public/user/register', [\App\Http\Controllers\UserManagement\CreateUserControllerUltimate::class, 'publicRegisterUser']);
Route::post('/api/public/user/check-mobile', [\App\Http\Controllers\UserManagement\CreateUserControllerUltimate::class, 'publicCheckMobileNumber']);

// Chapter / Org Hierarchy Routes
Route::post('/Chapters/Hierarchy', [\App\Http\Controllers\Support\ChapterController::class, 'hierarchy'], ['middleware' => 'auth']);
Route::post('/Chapters/MapData', [\App\Http\Controllers\Support\ChapterController::class, 'mapData'], ['middleware' => 'auth']);
Route::post('/Chapters/OrgHierarchy', [\App\Http\Controllers\Support\ChapterController::class, 'orgHierarchy'], ['middleware' => 'auth']);
Route::post('/Chapters/OrgMapData', [\App\Http\Controllers\Support\ChapterController::class, 'orgMapData'], ['middleware' => 'auth']);
Route::post('/Chapters/Members', [\App\Http\Controllers\Support\ChapterController::class, 'members'], ['middleware' => 'auth']);
Route::post('/Chapters/Member/Assign', [\App\Http\Controllers\Support\ChapterController::class, 'assignMember'], ['middleware' => 'auth']);
Route::post('/Chapters/Member/Remove', [\App\Http\Controllers\Support\ChapterController::class, 'removeMember'], ['middleware' => 'auth']);
Route::post('/Chapters/SyncAutoAssignments', [\App\Http\Controllers\Support\ChapterController::class, 'syncAllAutoAssignments'], ['middleware' => ['auth', 'ultimate']]);
Route::get('/Chapters/Positions', [\App\Http\Controllers\Support\ChapterController::class, 'positions'], ['middleware' => 'auth']);
Route::post('/Chapters/OrgChart', [\App\Http\Controllers\Support\ChapterController::class, 'getOrgChart'], ['middleware' => 'auth']);
Route::post('/Chapters/Officer/Assign', [\App\Http\Controllers\Support\ChapterController::class, 'assignOfficer'], ['middleware' => 'auth']);
Route::post('/Chapters/Create', [\App\Http\Controllers\Support\ChapterController::class, 'createChapter'], ['middleware' => 'auth']);
Route::post('/Chapters/Members/Search', [\App\Http\Controllers\Support\ChapterController::class, 'memberSearch'], ['middleware' => 'auth']);
Route::post('/Chapters/Officer/Scope', [\App\Http\Controllers\Support\ChapterController::class, 'getOfficerScope'], ['middleware' => 'auth']);

// Landing Page Routes
Route::get('/api/public/landing-page', [\App\Http\Controllers\Admin\LandingPageController::class, 'getActiveLandingPage']);
Route::post('/admin/landing-pages/list', [\App\Http\Controllers\Admin\LandingPageController::class, 'index'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/show', [\App\Http\Controllers\Admin\LandingPageController::class, 'show'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/store', [\App\Http\Controllers\Admin\LandingPageController::class, 'store'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/set-active', [\App\Http\Controllers\Admin\LandingPageController::class, 'setActive'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/deactivate-all', [\App\Http\Controllers\Admin\LandingPageController::class, 'deactivateAll'], ['middleware' => 'auth']);
Route::post('/admin/landing-pages/delete', [\App\Http\Controllers\Admin\LandingPageController::class, 'destroy'], ['middleware' => 'auth']);

// Ultimate Console Routes
Route::post('/admin/ultimate/system-settings', [\App\Http\Controllers\Admin\SystemSettingsController::class, 'index'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/system-settings/update', [\App\Http\Controllers\Admin\SystemSettingsController::class, 'update'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/system-settings/logo', [\App\Http\Controllers\Admin\SystemSettingsController::class, 'uploadLogo'], ['middleware' => ['auth', 'ultimate']]);
Route::get('/admin/ultimate/system-settings/organizations', [\App\Http\Controllers\Admin\SystemSettingsController::class, 'listOrganizations'], ['middleware' => ['auth', 'ultimate']]);
Route::get('/admin/ultimate/modules', [\App\Http\Controllers\Admin\SystemSettingsController::class, 'getModules'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/modules/update', [\App\Http\Controllers\Admin\SystemSettingsController::class, 'updateModules'], ['middleware' => ['auth', 'ultimate']]);

// API tokens — issued from Ultimate Console
Route::get('/admin/ultimate/api-tokens/catalog', [\App\Http\Controllers\Admin\ApiTokenController::class, 'catalog'], ['middleware' => ['auth', 'ultimate']]);
Route::get('/admin/ultimate/api-tokens', [\App\Http\Controllers\Admin\ApiTokenController::class, 'index'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/api-tokens', [\App\Http\Controllers\Admin\ApiTokenController::class, 'store'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/api-tokens/{id}/revoke', [\App\Http\Controllers\Admin\ApiTokenController::class, 'revoke'], ['middleware' => ['auth', 'ultimate']]);
Route::delete('/admin/ultimate/api-tokens/{id}', [\App\Http\Controllers\Admin\ApiTokenController::class, 'destroy'], ['middleware' => ['auth', 'ultimate']]);
Route::get('/api/public/system-settings', [\App\Http\Controllers\Admin\SystemSettingsController::class, 'getPublicSettings']);
Route::get('/api/public/global-message', function () {
    $message = \Hypervel\Support\Facades\Redis::get('system:global_message');
    if ($message) {
        return response()->json(['success' => true, 'data' => json_decode($message, true)]);
    }
    return response()->json(['success' => true, 'data' => null]);
});

Route::post('/admin/ultimate/stats', [\App\Http\Controllers\Market\UltimateController::class, 'getSystemStats'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/query', [\App\Http\Controllers\Market\UltimateController::class, 'runQuery'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/maintenance/toggle', [\App\Http\Controllers\Market\UltimateController::class, 'toggleMaintenance'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/global-message', [\App\Http\Controllers\Market\UltimateController::class, 'sendGlobalMessage'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/flush', [\App\Http\Controllers\Market\UltimateController::class, 'flushData'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/test-notification', [\App\Http\Controllers\Market\UltimateController::class, 'testNotification'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/batch', [\App\Http\Controllers\Market\UltimateController::class, 'batchManage'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/command', [\App\Http\Controllers\Market\UltimateController::class, 'runCommand'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/migrate', [\App\Http\Controllers\Market\UltimateController::class, 'runMigrate'], ['middleware' => ['auth', 'ultimate']]);
Route::get('/admin/ultimate/backup/download', [\App\Http\Controllers\Market\UltimateController::class, 'downloadBackup'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/logs', [\App\Http\Controllers\Market\UltimateController::class, 'getSystemLogs'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/backups/list', [\App\Http\Controllers\Market\UltimateController::class, 'getBackups'], ['middleware' => ['auth', 'ultimate']]);
Route::get('/admin/ultimate/backup/download/hash', [\App\Http\Controllers\Market\UltimateController::class, 'downloadBackupByHash'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/backup/rename', [\App\Http\Controllers\Market\UltimateController::class, 'renameBackup'], ['middleware' => ['auth', 'ultimate']]);
Route::post('/admin/ultimate/backup/delete', [\App\Http\Controllers\Market\UltimateController::class, 'deleteBackup'], ['middleware' => ['auth', 'ultimate']]);


// Batch Creation Routes
Route::post('/admin/batch/products', [\App\Http\Controllers\Market\BatchController::class, 'batchCreateProducts'], ['middleware' => ['auth', 'module:batch']]);
Route::get('/admin/batch/products/template', [\App\Http\Controllers\Market\BatchController::class, 'downloadProductTemplate'], ['middleware' => ['auth', 'module:batch']]);
Route::post('/admin/batch/stores', [\App\Http\Controllers\Market\BatchController::class, 'batchCreateStores'], ['middleware' => ['auth', 'module:batch']]);
Route::post('/admin/batch/users', [\App\Http\Controllers\Market\BatchController::class, 'batchCreateUsers'], ['middleware' => ['auth', 'module:batch']]);
Route::post('/admin/batch/cooperatives', [\App\Http\Controllers\Market\BatchController::class, 'batchCreateCooperatives'], ['middleware' => ['auth', 'module:batch']]);
Route::post('/admin/batch/cooperative-members', [\App\Http\Controllers\Market\BatchController::class, 'batchCreateCooperativeMembers'], ['middleware' => ['auth', 'module:batch', 'module:cooperatives']]);


// Universal SPA Route - Handles all other paths by mapping them to Vue components
Route::get('/{path}', function ($path = '/') {
    return VueRouteMap::handleSpa($path);
}, [
    'where' => ['path' => '.*'],
    'middleware' => 'web'
]);


// Route::get('/data/hello/', function (\Hypervel\Http\Request $request) {
//     $file = public_path('/plugins/bootstrap/js/bootstrap.bundle.min.js');

//     if ($request->has('nocache')) {
//         return response()->file($file);
//     }

//     $cacheKey = 'file_cache:bootstrap_bundle_js';
    
//     $content = Cache::remember($cacheKey, 3600, function () use ($file) {
//         return File::get($file);
//     });

//     return Response::make($content, 200, [
//         'Content-Type' => 'application/javascript',
//         'X-Cache' => Cache::has($cacheKey) ? 'HIT' : 'MISS'
//     ]);
// });


// Route::get('logs/now', function(){
//   $dd =  Storage::get('logs/view_errors.log');

//   return Response::json(Json::decode($dd),200);
// });