<?php

use Illuminate\Support\Facades\Route;
use App\Services\BusinessCentralService;
use App\Services\InventoryBC;
use App\Http\Controllers\BusinessCentralController;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Session;
use App\Http\Controllers\AzureAuthController;
use SocialiteProviders\Manager\SocialiteWasCalled;
use Illuminate\Support\Facades\Event;
use SocialiteProviders\Microsoft\MicrosoftExtendSocialite;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use App\Http\Controllers\OneDriveController;
use App\Http\Controllers\ItemRequestController;
use App\Http\Controllers\ApprovalController;
use App\Http\Controllers\ApprovalWebController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\ItemRequestCommentController;
use App\Http\Controllers\VendorController;
use App\Http\Controllers\ActivityLogController;
use App\Http\Controllers\UserRequestController;
use App\Http\Controllers\TransferHeaderController;

Event::listen(SocialiteWasCalled::class, function ($event) {
    $event->extendSocialite('microsoft', \SocialiteProviders\Microsoft\Provider::class);
});
Route::get('/', function () {
    return redirect()->route('login');
});
Route::get('/csrf/refresh', fn() => response()->json(['token' => csrf_token()]))->name('csrf.refresh');
Route::get('/login', [AzureAuthController::class, 'redirectToProvider'])->name('login');
Route::get('/auth/callback', [AzureAuthController::class, 'handleProviderCallback']);
Route::get('/logout', [AzureAuthController::class, 'logout'])->name('logout');

Route::middleware(['bc.auth','admin.only'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/item-requests/{id}/peek', [ApprovalWebController::class, 'peek'])->name('approvals.peek');

        Route::get('/', [AdminController::class, 'index'])->name('index');
        Route::post('/flows',          [AdminController::class, 'storeFlow'])->name('flows.store');
        Route::post('/flows/{flow}/toggle', [AdminController::class, 'toggleFlow'])->name('flows.toggle');
        Route::delete('/flows/{flow}', [AdminController::class, 'destroyFlow'])->name('flows.destroy');

        Route::post('/flows/{flow}/steps', [AdminController::class, 'storeStep'])->name('steps.store');
        Route::delete('/steps/{step}',      [AdminController::class, 'destroyStep'])->name('steps.destroy');

        Route::post('/users/{user}/role', [AdminController::class, 'updateUserRole'])->name('users.updateRole');
        Route::patch('/admin/users/{user}', [AdminController::class,'updateUser'])->name('users.update');
        Route::get('/instances', [AdminController::class, 'instances'])->name('instances');
        Route::get('/requests',  [AdminController::class, 'requests'])->name('requests');
        Route::post('/users', [AdminController::class, 'storeUser'])->name('users.store');
        Route::delete('/users/{user}', [AdminController::class, 'destroyUser'])->name('users.destroy');
        Route::post('/requests/{id}/reset',   [AdminController::class, 'requestResetDraft'])->name('requests.reset');
        Route::post('/requests/{id}/jump',    [AdminController::class, 'requestJumpStep'])->name('requests.jump');
        Route::post('/requests/{id}/approve', [AdminController::class, 'requestForceApprove'])->name('requests.forceApprove');
        Route::post('/requests/{id}/reject',  [AdminController::class, 'requestForceReject'])->name('requests.forceReject');
        Route::delete('/requests/{id}',       [AdminController::class, 'requestDestroy'])->name('requests.destroy');
        Route::post('/roles', [AdminController::class, 'storeRole'])->name('roles.store');
        Route::delete('/roles/{role}', [AdminController::class, 'destroyRole'])->name('roles.destroy');
    });

Route::middleware('bc.auth')->group(function () {
    Route::get('/transfer/items', [TransferHeaderController::class, 'showItems'])->name('transfer.items'); 
    Route::get('/transfer/all-with-lines', [BusinessCentralService::class, 'getAllTransferWithLines'])->name('bc.transfer.with-lines');
    Route::post('/assembly-header', [BusinessCentralController::class, 'createAssemblyHeader'])->name('bc.assembly-header.create');
    Route::get('/bc/bom-with-stock', [BusinessCentralController::class, 'getCombinedBOMWithStock'])->name('bc.bom-with-stock');
    Route::get('/combined-stock', [BusinessCentralController::class, 'getCombinedStock'])->name('bc.combined-stock');
    Route::get('/transfer-lines', [BusinessCentralService::class, 'getAllTransferLines']);
    Route::get('/stock-v2', [BusinessCentralService::class, 'getStockV2']);
    Route::get('/bill-of-material', [BusinessCentralService::class, 'billOfMaterial']);
    Route::get('/test-item-card-excel', [BusinessCentralService::class, 'getItemCardExcelRaw']);
    Route::get('/get/assembly-order', [BusinessCentralService::class, 'getAllAssemblyOrder']);
    Route::get('/transfer', [BusinessCentralService::class, 'getAllTransferHeaders']);
    Route::get('/noseries', fn(BusinessCentralService $bc) => $bc->getNoSeries());
    Route::get('/pastry/create-transfer-head', [TransferHeaderController::class, 'createTransferLine'])->name('bc.create-transfer');
    Route::post('/pastry/store-transfer-head', [BusinessCentralController::class, 'storeTransferLine'])->name('bc.store-transfer');
    Route::post('/mbc/create-vendor', [BusinessCentralController::class, 'createVendor'])->name('mbc.create-vendor');
    Route::get('/user-request/create', [UserRequestController::class, 'create'])->name('user-request.create');
    Route::post('/user-request/store', [UserRequestController::class, 'store'])->name('user-request.store');
    Route::post('/mbc/create-items', [BusinessCentralController::class, 'createItems'])
     ->name('mbc.create.items');
    Route::post('/item-request/create-price', [BusinessCentralController::class, 'createPrice'])
    ->name('bc.create.price');
    Route::post('/item-request/patch-price', [BusinessCentralController::class, 'patchPrice'])
    ->name('update.price');
    Route::post('/item-request/create-extdate', [BusinessCentralController::class, 'createExtDate'])
    ->name('bc.create.extdate');
    Route::post('/item-request/patch-ending-date', [BusinessCentralController::class, 'patchEndingDate'])
    ->name('item-request.patch-ending-date');
    Route::get('/item-request/items', [ItemRequestController::class, 'getItems'])
    ->name('item-request.items');
    Route::get('/activity-logs', [ActivityLogController::class, 'index'])
    ->name('activity.logs');
    Route::get('/vendors/new', [VendorController::class, 'create'])->name('vendors.create');
    Route::post('/vendors', [VendorController::class, 'store'])->name('vendors.store'); // untuk simpan nanti
    Route::get('/vendors/{item_request}/edit', [VendorController::class, 'edit'])->name('vendors.edit');
    Route::put('/vendors/{item_request}', [VendorController::class, 'update'])->name('vendors.update');
    Route::get('/approvals/search', [App\Http\Controllers\ApprovalWebController::class, 'search'])
    ->name('approvals.search');
    Route::get('/approvals/all', [\App\Http\Controllers\ApprovalWebController::class, 'all'])
    ->name('approvals.all');
    Route::delete('/approvals/{id}', [\App\Http\Controllers\ApprovalWebController::class, 'destroyDraft'])
    ->name('approvals.destroy');
    Route::get('/approvals/{id}/print', [\App\Http\Controllers\ApprovalWebController::class, 'print'])
    ->name('approvals.print');
    Route::get('/approvals/{req}/attachments/{att}/download',
        [\App\Http\Controllers\ApprovalWebController::class,'downloadAttachment']
    )->name('approvals.attachments.download');
    Route::get('/approvals/{req}/attachments/{att}/preview', [ApprovalWebController::class, 'previewAttachment'])
    ->name('approvals.attachments.preview');
    Route::get('/notifications', [\App\Http\Controllers\NotificationController::class,'index'])
    ->name('notifications.index');
    Route::post('/notifications/{id}/read', [\App\Http\Controllers\NotificationController::class,'markOne'])
        ->name('notifications.read');
    Route::post('/notifications/read-all', [\App\Http\Controllers\NotificationController::class,'markAll'])
        ->name('notifications.readAll');
    Route::post('/approvals/{id}/duplicate', [\App\Http\Controllers\ApprovalWebController::class, 'duplicate'])
    ->name('approvals.web.duplicate');
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/approvals/inbox', [ApprovalWebController::class, 'inbox'])->name('approvals.inbox');
    Route::get('/approvals/new',   [ItemRequestController::class, 'create'])->name('approvals.new');
    Route::post('/approvals/new',  [ItemRequestController::class, 'store'])->name('approvals.store');   // posts the form to create draft
    Route::get('/approvals/my-forms', [ApprovalWebController::class, 'myForms'])->name('approvals.mine');
    Route::post('/approvals/{id}/submit', [ApprovalWebController::class, 'submit'])->name('approvals.web.submit');
    Route::get('/approvals/{id}',  [ApprovalWebController::class, 'show'])->name('approvals.show');
    Route::post('/approvals/{id}/approve', [ApprovalWebController::class, 'approve'])->name('approvals.web.approve');
    Route::post('/approvals/{id}/reject',  [ApprovalWebController::class, 'reject'])->name('approvals.web.reject');
    Route::get('/item-requests/{id}/edit',  [ApprovalWebController::class,'edit'])->name('approvals.edit');
    Route::put('/item-requests/{id}',       [ApprovalWebController::class,'update'])->name('approvals.update');
    Route::post('/approvals/{id}/cancel', [\App\Http\Controllers\ApprovalWebController::class, 'cancel'])
    ->name('approvals.web.cancel');
     Route::post('/approvals/{id}/comments', [ItemRequestCommentController::class, 'store'])
        ->name('approvals.comments.store');
    Route::post('/item-requests', [ItemRequestController::class,'store']);
    Route::post('/item-requests/{id}/submit', [ApprovalController::class,'submit']);
    Route::post('/item-requests/{id}/approve', [ApprovalController::class,'approve']);
    Route::post('/item-requests/{id}/reject', [ApprovalController::class,'reject']);
    Route::get('/bc-transfer-lines', fn(BusinessCentralService $bc) => $bc->getTransferLinesFromBC());
    Route::get('/bc-purchase-lines', fn(BusinessCentralService $bc) => $bc->getPurchaseLineFromBC());
    Route::get('/bc-price_list', fn(BusinessCentralService $bc) => $bc->getAllPurchasePrices());
    Route::get('/bc-stockkeeping', fn(BusinessCentralService $bc) => $bc->getStockkeepingFromBC());
    Route::get('/bc-PO-qty', fn(BusinessCentralService $bc) => $bc->getPurchaseQtyByItemAndLocation('BV.0006', 'CI.1010'));
    Route::get('/bc-get_PO', fn(BusinessCentralService $bc) => $bc->getPOFromBC());
    Route::get('/bc-get_meta', fn(BusinessCentralService $bc) => $bc->getMetadata());
    Route::get('/bc-get-vendor', fn(BusinessCentralService $bc) => $bc->getVendor());
    Route::get('/itemUoM', fn(BusinessCentralService $bc) => $bc->itemUoM());
    Route::get('/po-suggestions', [BusinessCentralController::class, 'showPoSuggestions'])->name('po-suggestions');
    Route::post('/create-po', [BusinessCentralController::class, 'create'])->name('create-po');
    Route::get('/bc-get-itemledger', fn(InventoryBC $inv) => $inv->getItemLedger());
    Route::get('/bc-get-skumap', fn(InventoryBC $inv) => $inv->getSKUMapping());
    Route::post('/update-sku', [BusinessCentralController::class, 'updateSku'])->name('sku.update');
    Route::post('/upload-Stockkeeping', [BusinessCentralController::class, 'updateStockkeeping'])->name('api.stockkeeping.upload');
    Route::get('/min-max-suggestions', [BusinessCentralController::class, 'viewSkuMapping'])->name('sku-mapping');
    Route::get('/bc-get-SKULedger', fn(InventoryBC $inv) => $inv->getItemLedgerAndSkuMappingAsync());
    Route::get('/export-missing-vendor', [BusinessCentralController::class, 'exportMissingVendor'])->name('export.missing.vendor');
    Route::get('/bc-get-SKUImport', fn(InventoryBC $inv) => $inv->getSKUImport());
    Route::get('/bc-get-getItemInvenLoc', fn(InventoryBC $inv) => $inv->getItemInvenLoc());
    Route::post('/po-suggestions/refresh', [BusinessCentralController::class, 'refreshPoSuggestions'])->name('refresh.po.suggestions');
    Route::post('/min-max-suggestions/refresh', [BusinessCentralController::class, 'refreshMinMaxSuggestions'])->name('refresh.MinMax.suggestions');
    Route::patch('/bc-update-item', [BusinessCentralController::class, 'patchItemField']);
    Route::get('/export-po-lines', [BusinessCentralController::class, 'exportPoLines'])->name('export.po_lines');
    Route::get('/export-po-lines-visible', [BusinessCentralController::class, 'exportPoLinesVisible'])
     ->name('export.po_lines_visible');
    Route::get('/onedrive/try-download', [OneDriveTryController::class, 'tryDownload']);
    Route::get('/onedrive/try-list', [OneDriveController::class, 'tryList']);
    Route::get('/onedrive/test-download', function (\Illuminate\Http\Request $req) {
        $access = session('graph.access_token') ?? abort(401, 'Sign in with Microsoft first.');
        $svc = app(\App\Services\OneDriveService::class);
        $shareUrl = 'https://citbi-my.sharepoint.com/personal/adminbc_citbi_onmicrosoft_com/Documents/Bali%20Canggu/history_forecast(HIC).txt';
        $fileName  = 'history_forecast(HIC).txt';
        $savePath  = 'onedrive/' . $fileName; 

        $contents = $svc->downloadByShareUrl($access, $shareUrl, $fileName);
        //Storage::disk('private')->put($savePath, $contents);
        //$relative = 'onedrive/history_forecast(HIC).txt';
        return response()->json([
            'message' => 'File saved into hosting server',
            'path'    => Storage::disk('private')->path($savePath),
            'url'     => asset('storage/' . $savePath),
            'sharedUrl' => $shareUrl,
            'contents' => $contents
        ]);
    });
    Route::get('/sku-mapping/export', [BusinessCentralController::class, 'exportSkuMapping'])
    ->name('sku.mapping.export');
    Route::get('/check-env', function () {
        dd([
            'AZURE_CLIENT_ID' => env('AZURE_CLIENT_ID'),
            'AZURE_CLIENT_SECRET' => env('AZURE_CLIENT_SECRET'),
            'AZURE_TENANT_ID' => env('AZURE_TENANT_ID'),
        ]);
    });
    Route::get('/switch-company/{type}', function ($type) {
        $role = session('user')['role'] ?? null;
        $email = session('user')['email'] ?? null;
    
        if ($role === 'Regent' && $type !== 'Regent') {
            abort(403, 'Unauthorized');
        }
        if ($role === 'HIN' && $type !== 'HIN') {
            abort(403, 'Unauthorized');
        }
    
        session(['current_company_name' => $type]);
    
        if ($email) {
            $cacheKey = 'po_suggestions_' . md5($email);
            Cache::forget($cacheKey);
            
        }
        
        $skuCacheKey = 'sku_mapping_cache';
        if (Cache::has($skuCacheKey)) {
            Cache::forget($skuCacheKey);
        }
        
        Session::forget(['po_items', 'vendor_map']);

        $prev = url()->previous();
        $prevRouteName = null;
        try {
            $prevRouteName = app('router')
                ->getRoutes()
                ->match(Request::create($prev))
                ->getName();
        } catch (\Throwable $e) {

        }

        $msg = "Switched to {$type} environment and cleared caches.";

        if (in_array($prevRouteName, ['approvals.show', 'approvals.edit'], true)) {
            return redirect()->route('approvals.mine')->with('success', $msg);
        }
    
        return redirect()
        ->back()
        ->with('success', "Switched to {$type} environment and cleared caches.");
    })->name('switch-company');
    //getItemInvenLoc
}); 
