<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Backoffice\AuthController;
use App\Http\Controllers\Backoffice\DashboardController;
use App\Http\Controllers\Backoffice\DepositController;
use App\Http\Controllers\Backoffice\WithdrawalController;
use App\Http\Controllers\Backoffice\FinanceGroupController;
use App\Http\Controllers\Backoffice\BankAccountController;
use App\Http\Controllers\Backoffice\CryptoAccountController;
use App\Http\Controllers\Backoffice\FinanceUserController;
use App\Http\Controllers\Backoffice\BackofficeUserController;
use App\Http\Controllers\Backoffice\PermissionGroupController;
use App\Http\Controllers\Backoffice\SettingsController;
use App\Http\Controllers\Backoffice\SiteController;
use App\Http\Controllers\Backoffice\PaymentPopupController;
use App\Http\Controllers\Backoffice\ReportsController;
use App\Http\Controllers\Backoffice\CannedResponseController;
use App\Http\Controllers\Backoffice\ActivityLogController;
use App\Http\Controllers\Backoffice\BlacklistController;
use App\Http\Controllers\Backoffice\CrmController;
use App\Http\Controllers\Backoffice\TransactionLogController;
use App\Http\Controllers\Backoffice\TwoFactorController as BackofficeTwoFactorController;
use App\Http\Controllers\Finance\AuthController as FinanceAuthController;
use App\Http\Controllers\Finance\DashboardController as FinanceDashboardController;
use App\Http\Controllers\Finance\DepositController as FinanceDepositController;
use App\Http\Controllers\Finance\WithdrawalController as FinanceWithdrawalController;
use App\Http\Controllers\Finance\BankAccountController as FinanceBankAccountController;
use App\Http\Controllers\Finance\CryptoAccountController as FinanceCryptoAccountController;
use App\Http\Controllers\Finance\TwoFactorController as FinanceTwoFactorController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\SiteAssetController;

/*
|--------------------------------------------------------------------------
| 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!
|
*/

$mainDomain = 'ai-garantipay-virtual.com';
$backofficeDomain = 'backoffice.ai-garantipay-virtual.com';
$financeDomain = 'finans.ai-garantipay-virtual.com';
$paymentDomain = 'odeme.ai-garantipay-virtual.com';

Route::domain($mainDomain)->get('/', function () {
    return redirect()->to(route('backoffice.login', [], false));
});

Route::get('site-logo/{id}', [SiteAssetController::class, 'logo'])->name('site.logo');

// Backoffice Routes (Subdomain)
Route::domain($backofficeDomain)->group(function () {
    Route::get('/', function () {
        return redirect()->to(route('backoffice.login', [], false));
    });

    Route::prefix('backoffice')->name('backoffice.')->group(function () {
        // Guest routes
        Route::middleware(['guest', 'block.login.ua'])->group(function () {
            Route::get('login', [AuthController::class, 'showLoginForm'])->name('login');
            Route::post('login', [AuthController::class, 'login']);
        });

        // 2FA challenge (after password login)
        Route::get('2fa/challenge', [BackofficeTwoFactorController::class, 'showChallenge'])->name('2fa.challenge');
        Route::post('2fa/challenge', [BackofficeTwoFactorController::class, 'verifyChallenge'])->name('2fa.challenge.verify');
        Route::get('2fa/enroll', [BackofficeTwoFactorController::class, 'showEnroll'])->name('2fa.enroll');
        Route::post('2fa/enroll', [BackofficeTwoFactorController::class, 'verifyEnroll'])->name('2fa.enroll.verify');

        // Authenticated routes
        Route::middleware(['auth', 'no.store'])->group(function () {
            Route::post('logout', [AuthController::class, 'logout'])->name('logout');
            Route::get('dashboard', [DashboardController::class, 'index'])->middleware('permission:dashboard')->name('dashboard');
            Route::get('crm', [CrmController::class, 'index'])->middleware('permission:crm')->name('crm.index');

            // 2FA settings
            Route::get('2fa', [BackofficeTwoFactorController::class, 'showSetup'])->name('2fa');
            Route::post('2fa/enable', [BackofficeTwoFactorController::class, 'enable'])->name('2fa.enable');
            Route::post('2fa/disable', [BackofficeTwoFactorController::class, 'disable'])->name('2fa.disable');

            // Deposits
            Route::prefix('deposits')->name('deposits.')->middleware('permission:deposits')->group(function () {
                Route::get('/', [DepositController::class, 'index'])->name('index');
                Route::post('/', [DepositController::class, 'store'])->middleware('permission:deposits,create')->name('store');
                Route::get('check-new', [DepositController::class, 'checkNew'])->name('check-new');
                Route::get('stats', [DepositController::class, 'stats'])->name('stats');
                Route::get('{id}', [DepositController::class, 'show'])->name('show');
                Route::post('{id}/approve', [DepositController::class, 'approve'])->middleware('permission:deposits,update')->name('approve');
                Route::post('{id}/decline', [DepositController::class, 'decline'])->middleware('permission:deposits,update')->name('decline');
            });

            // Withdrawals
            Route::prefix('withdrawals')->name('withdrawals.')->middleware('permission:withdrawals')->group(function () {
                Route::get('/', [WithdrawalController::class, 'index'])->name('index');
                Route::post('/', [WithdrawalController::class, 'store'])->middleware('permission:withdrawals,create')->name('store');
                Route::get('check-new', [WithdrawalController::class, 'checkNew'])->name('check-new');
                Route::get('stats', [WithdrawalController::class, 'stats'])->name('stats');
                Route::get('{id}', [WithdrawalController::class, 'show'])->name('show');
                Route::post('{id}/assign', [WithdrawalController::class, 'assignDetails'])->middleware('permission:withdrawals,update')->name('assign');
                Route::post('{id}/approve', [WithdrawalController::class, 'approve'])->middleware('permission:withdrawals,update')->name('approve');
                Route::post('{id}/decline', [WithdrawalController::class, 'decline'])->middleware('permission:withdrawals,update')->name('decline');
            });

            // Site scoped transaction pages (keep global pages)
            Route::prefix('sites/{site}')->name('sites.')->group(function () {
                Route::get('deposits', [DepositController::class, 'index'])
                    ->middleware('permission:deposits')
                    ->name('deposits.index');
                Route::get('withdrawals', [WithdrawalController::class, 'index'])
                    ->middleware('permission:withdrawals')
                    ->name('withdrawals.index');
            });

            // Transaction Logs
            Route::get('transaction-logs', [TransactionLogController::class, 'index'])
                ->middleware('permission:transaction_logs')
                ->name('transaction-logs.index');

            // Finance Groups
            Route::prefix('finance-groups')->name('finance-groups.')->middleware('permission:finance_groups')->group(function () {
                Route::get('/', [FinanceGroupController::class, 'index'])->name('index');
                Route::post('/', [FinanceGroupController::class, 'store'])->middleware('permission:finance_groups,create')->name('store');
                Route::get('{id}', [FinanceGroupController::class, 'show'])->name('show');
                Route::put('{id}', [FinanceGroupController::class, 'update'])->middleware('permission:finance_groups,update')->name('update');
                Route::delete('{id}', [FinanceGroupController::class, 'destroy'])->middleware('permission:finance_groups,delete')->name('destroy');
                Route::post('{id}/toggle-status', [FinanceGroupController::class, 'toggleStatus'])->middleware('permission:finance_groups,update')->name('toggle-status');
                Route::post('{id}/toggle-crypto', [FinanceGroupController::class, 'toggleCrypto'])->middleware('permission:finance_groups,update')->name('toggle-crypto');
                Route::get('{id}/site-statuses', [FinanceGroupController::class, 'siteStatuses'])->name('site-statuses');
                Route::post('{id}/site-statuses', [FinanceGroupController::class, 'updateSiteStatuses'])->middleware('permission:finance_groups,update')->name('site-statuses.update');
                Route::get('{id}/bank-accounts', [FinanceGroupController::class, 'getBankAccounts'])->name('bank-accounts');
            });

            // Bank Accounts
            Route::prefix('bank-accounts')->name('bank-accounts.')->middleware('permission:bank_accounts')->group(function () {
                Route::get('/', [BankAccountController::class, 'index'])->name('index');
                Route::post('/', [BankAccountController::class, 'store'])->middleware('permission:bank_accounts,create')->name('store');
                Route::get('{id}', [BankAccountController::class, 'show'])->name('show');
                Route::put('{id}', [BankAccountController::class, 'update'])->middleware('permission:bank_accounts,update')->name('update');
                Route::delete('{id}', [BankAccountController::class, 'destroy'])->middleware('permission:bank_accounts,delete')->name('destroy');
                Route::post('{id}/toggle-status', [BankAccountController::class, 'toggleStatus'])->middleware('permission:bank_accounts,update')->name('toggle-status');
            });

            // Crypto Accounts
            Route::prefix('crypto-accounts')->name('crypto-accounts.')->middleware('permission:crypto_accounts')->group(function () {
                Route::get('/', [CryptoAccountController::class, 'index'])->name('index');
                Route::post('/', [CryptoAccountController::class, 'store'])->middleware('permission:crypto_accounts,create')->name('store');
                Route::get('{id}', [CryptoAccountController::class, 'show'])->name('show');
                Route::put('{id}', [CryptoAccountController::class, 'update'])->middleware('permission:crypto_accounts,update')->name('update');
                Route::delete('{id}', [CryptoAccountController::class, 'destroy'])->middleware('permission:crypto_accounts,delete')->name('destroy');
                Route::post('{id}/toggle-status', [CryptoAccountController::class, 'toggleStatus'])->middleware('permission:crypto_accounts,update')->name('toggle-status');
            });

            // Finance Users
            Route::prefix('finance-users')->name('finance-users.')->middleware('permission:finance_users')->group(function () {
                Route::get('/', [FinanceUserController::class, 'index'])->name('index');
                Route::post('/', [FinanceUserController::class, 'store'])->middleware('permission:finance_users,create')->name('store');
                Route::get('{id}', [FinanceUserController::class, 'show'])->name('show');
                Route::put('{id}', [FinanceUserController::class, 'update'])->middleware('permission:finance_users,update')->name('update');
                Route::delete('{id}', [FinanceUserController::class, 'destroy'])->middleware('permission:finance_users,delete')->name('destroy');
                Route::post('{id}/toggle-status', [FinanceUserController::class, 'toggleStatus'])->middleware('permission:finance_users,update')->name('toggle-status');
            });

            // Backoffice Users
            Route::prefix('users')->name('users.')->middleware('permission:users')->group(function () {
                Route::get('/', [BackofficeUserController::class, 'index'])->name('index');
                Route::post('/', [BackofficeUserController::class, 'store'])->middleware('permission:users,create')->name('store');
                Route::get('{id}', [BackofficeUserController::class, 'show'])->name('show');
                Route::put('{id}', [BackofficeUserController::class, 'update'])->middleware('permission:users,update')->name('update');
                Route::delete('{id}', [BackofficeUserController::class, 'destroy'])->middleware('permission:users,delete')->name('destroy');
                Route::post('{id}/toggle-status', [BackofficeUserController::class, 'toggleStatus'])->middleware('permission:users,update')->name('toggle-status');
            });

            // Hazir Cevaplar
            Route::prefix('canned-responses')->name('canned-responses.')->middleware('permission:canned_responses')->group(function () {
                Route::get('/', [CannedResponseController::class, 'index'])->name('index');
                Route::post('/', [CannedResponseController::class, 'store'])->middleware('permission:canned_responses,create')->name('store');
                Route::get('{id}', [CannedResponseController::class, 'show'])->name('show');
                Route::put('{id}', [CannedResponseController::class, 'update'])->middleware('permission:canned_responses,update')->name('update');
                Route::delete('{id}', [CannedResponseController::class, 'destroy'])->middleware('permission:canned_responses,delete')->name('destroy');
            });

            // Blacklist
            Route::prefix('blacklist')->name('blacklist.')->middleware('permission:blacklist')->group(function () {
                Route::get('/', [BlacklistController::class, 'index'])->name('index');
                Route::post('/', [BlacklistController::class, 'store'])->middleware('permission:blacklist,create')->name('store');
                Route::get('{id}', [BlacklistController::class, 'show'])->name('show');
                Route::put('{id}', [BlacklistController::class, 'update'])->middleware('permission:blacklist,update')->name('update');
                Route::delete('{id}', [BlacklistController::class, 'destroy'])->middleware('permission:blacklist,delete')->name('destroy');
            });

            // Permission Groups
            Route::prefix('permissions')->name('permissions.')->middleware('permission:permissions')->group(function () {
                Route::get('/', [PermissionGroupController::class, 'index'])->name('index');
                Route::post('/', [PermissionGroupController::class, 'store'])->middleware('permission:permissions,create')->name('store');
                Route::post('{id}/clone', [PermissionGroupController::class, 'clone'])->middleware('permission:permissions,create')->name('clone');
                Route::get('{id}', [PermissionGroupController::class, 'show'])->name('show');
                Route::put('{id}', [PermissionGroupController::class, 'update'])->middleware('permission:permissions,update')->name('update');
                Route::delete('{id}', [PermissionGroupController::class, 'destroy'])->middleware('permission:permissions,delete')->name('destroy');
            });

            // Settings
            Route::get('settings', [SettingsController::class, 'index'])->middleware('permission:settings')->name('settings');
            Route::post('settings', [SettingsController::class, 'update'])->middleware('permission:settings,update')->name('settings.update');
            Route::post('settings/advanced-security/verify', [SettingsController::class, 'verifyAdvancedSecurityPassword'])->middleware('permission:settings,update')->name('settings.advanced-security.verify');
            Route::post('settings/advanced-security', [SettingsController::class, 'updateAdvancedSecurity'])->middleware('permission:settings,update')->name('settings.advanced-security.update');
            Route::post('settings/crypto-coins', [SettingsController::class, 'storeCryptoCoin'])->middleware('permission:settings,update')->name('settings.crypto-coins.store');
            Route::put('settings/crypto-coins/{id}', [SettingsController::class, 'updateCryptoCoin'])->middleware('permission:settings,update')->name('settings.crypto-coins.update');
            Route::delete('settings/crypto-coins/{id}', [SettingsController::class, 'destroyCryptoCoin'])->middleware('permission:settings,update')->name('settings.crypto-coins.destroy');

            // Sites
            Route::prefix('sites')->name('sites.')->middleware('permission:sites')->group(function () {
                Route::get('/', [SiteController::class, 'index'])->name('index');
                Route::post('/', [SiteController::class, 'store'])->middleware('permission:sites,create')->name('store');
                Route::get('{id}', [SiteController::class, 'show'])->name('show');
                Route::put('{id}', [SiteController::class, 'update'])->middleware('permission:sites,update')->name('update');
                Route::post('{id}/toggle-status', [SiteController::class, 'toggleStatus'])->middleware('permission:sites,update')->name('toggle-status');
                Route::delete('{id}', [SiteController::class, 'destroy'])->middleware('permission:sites,delete')->name('destroy');
            });

            // Payment popups (site based)
            Route::prefix('payment-popups')->name('payment-popups.')->middleware('permission:payment_popups')->group(function () {
                Route::get('/', [PaymentPopupController::class, 'index'])->name('index');
                Route::post('{site}/update', [PaymentPopupController::class, 'update'])->middleware('permission:payment_popups,update')->name('update');
            });

            // Reports
            Route::get('reports', [ReportsController::class, 'index'])->middleware('permission:reports')->name('reports');
            Route::get('reports/export', [ReportsController::class, 'export'])->middleware('permission:reports')->name('reports.export');

            // Activity Logs
            Route::get('activity-logs', [ActivityLogController::class, 'index'])->middleware('permission:activity_logs')->name('activity-logs.index');
        });
    });
});

// Finance Portal Routes (Subdomain)
Route::domain($financeDomain)->group(function () {
    Route::get('/', function () {
        return auth()->guard('finance')->check()
            ? redirect()->to(route('finance.dashboard', [], false))
            : redirect()->to(route('finance.login', [], false));
    })->name('finance.home');

    Route::prefix('finance')->name('finance.')->group(function () {
        Route::get('/', function () {
            return auth()->guard('finance')->check()
                ? redirect()->to(route('finance.dashboard', [], false))
                : redirect()->to(route('finance.login', [], false));
        })->name('home');

        // Guest routes
        Route::middleware(['guest:finance', 'block.login.ua'])->group(function () {
            Route::get('login', [FinanceAuthController::class, 'showLoginForm'])->name('login');
            Route::post('login', [FinanceAuthController::class, 'login']);
        });

        // 2FA challenge (after password login)
        Route::get('2fa/challenge', [FinanceTwoFactorController::class, 'showChallenge'])->name('2fa.challenge');
        Route::post('2fa/challenge', [FinanceTwoFactorController::class, 'verifyChallenge'])->name('2fa.challenge.verify');
        Route::get('2fa/enroll', [FinanceTwoFactorController::class, 'showEnroll'])->name('2fa.enroll');
        Route::post('2fa/enroll', [FinanceTwoFactorController::class, 'verifyEnroll'])->name('2fa.enroll.verify');

        // Authenticated routes
        Route::middleware(['auth:finance', 'no.store'])->group(function () {
            Route::post('logout', [FinanceAuthController::class, 'logout'])->name('logout');
            Route::get('dashboard', [FinanceDashboardController::class, 'index'])->name('dashboard');
            Route::get('dashboard/check-new', [FinanceDashboardController::class, 'checkNew'])->name('dashboard.check-new');

            // 2FA settings
            Route::get('2fa', [FinanceTwoFactorController::class, 'showSetup'])->name('2fa');
            Route::post('2fa/enable', [FinanceTwoFactorController::class, 'enable'])->name('2fa.enable');
            Route::post('2fa/disable', [FinanceTwoFactorController::class, 'disable'])->name('2fa.disable');

            // Finance Deposits
            Route::prefix('deposits')->name('deposits.')->group(function () {
                Route::get('/', [FinanceDepositController::class, 'index'])->name('index');
                Route::post('/', [FinanceDepositController::class, 'store'])->name('store');
                Route::get('check-new', [FinanceDepositController::class, 'checkNew'])->name('check-new');
                Route::get('stats', [FinanceDepositController::class, 'stats'])->name('stats');
                Route::get('{id}', [FinanceDepositController::class, 'show'])->name('show');
                Route::post('{id}/update-amount', [FinanceDepositController::class, 'updateAmount'])->name('update-amount');
                Route::post('{id}/approve', [FinanceDepositController::class, 'approve'])->name('approve');
                Route::post('{id}/decline', [FinanceDepositController::class, 'decline'])->name('decline');
            });

            // Finance Withdrawals
            Route::prefix('withdrawals')->name('withdrawals.')->group(function () {
                Route::get('/', [FinanceWithdrawalController::class, 'index'])->name('index');
                Route::post('/', [FinanceWithdrawalController::class, 'store'])->name('store');
                Route::get('check-new', [FinanceWithdrawalController::class, 'checkNew'])->name('check-new');
                Route::get('stats', [FinanceWithdrawalController::class, 'stats'])->name('stats');
                Route::get('{id}', [FinanceWithdrawalController::class, 'show'])->name('show');
                Route::post('{id}/approve', [FinanceWithdrawalController::class, 'approve'])->name('approve');
                Route::post('{id}/decline', [FinanceWithdrawalController::class, 'decline'])->name('decline');
            });

            // Site scoped finance pages (keep global pages)
            Route::prefix('sites/{site}')->name('sites.')->group(function () {
                Route::get('deposits', [FinanceDepositController::class, 'index'])->name('deposits.index');
                Route::get('withdrawals', [FinanceWithdrawalController::class, 'index'])->name('withdrawals.index');
                Route::get('bank-accounts', [FinanceBankAccountController::class, 'index'])->name('bank-accounts.index');
            });

            // Finance Bank Accounts
            Route::prefix('bank-accounts')->name('bank-accounts.')->group(function () {
                Route::get('/', [FinanceBankAccountController::class, 'index'])->name('index');
                Route::post('/', [FinanceBankAccountController::class, 'store'])->name('store');
                Route::get('{id}', [FinanceBankAccountController::class, 'show'])->name('show');
                Route::put('{id}', [FinanceBankAccountController::class, 'update'])->name('update');
                Route::delete('{id}', [FinanceBankAccountController::class, 'destroy'])->name('destroy');
                Route::post('{id}/toggle-status', [FinanceBankAccountController::class, 'toggleStatus'])->name('toggle-status');
                Route::post('{id}/block', [FinanceBankAccountController::class, 'block'])->name('block');
                Route::get('{id}/site-statuses', [FinanceBankAccountController::class, 'siteStatuses'])->name('site-statuses');
                Route::post('{id}/site-statuses', [FinanceBankAccountController::class, 'updateSiteStatuses'])->name('site-statuses.update');
            });

            // Finance Crypto Accounts
            Route::prefix('crypto-accounts')->name('crypto-accounts.')->group(function () {
                Route::get('/', [FinanceCryptoAccountController::class, 'index'])->name('index');
                Route::post('/', [FinanceCryptoAccountController::class, 'store'])->name('store');
                Route::get('{id}', [FinanceCryptoAccountController::class, 'show'])->name('show');
                Route::put('{id}', [FinanceCryptoAccountController::class, 'update'])->name('update');
                Route::delete('{id}', [FinanceCryptoAccountController::class, 'destroy'])->name('destroy');
                Route::post('{id}/toggle-status', [FinanceCryptoAccountController::class, 'toggleStatus'])->name('toggle-status');
            });

            Route::get('finance-groups/{id}/bank-accounts', [FinanceBankAccountController::class, 'getByGroup'])->name('finance-groups.bank-accounts');
        });
    });
});

// Public Payment Routes (Subdomain)
Route::domain($paymentDomain)->group(function () {
    Route::get('/', function () {
        return redirect()->to(route('payment.deposit', [], false));
    });

    Route::prefix('payment')->name('payment.')->group(function () {
        Route::get('deposit', [PaymentController::class, 'showDepositForm'])->name('deposit');
        Route::post('deposit/initialize', [PaymentController::class, 'initializeDepositPreview'])
            ->middleware('throttle:payment-initialize')
            ->name('deposit.initialize');
        Route::post('deposit/confirm', [PaymentController::class, 'confirmDepositPreview'])
            ->middleware('throttle:payment-confirm')
            ->name('deposit.confirm');

        // Backward-compatible aliases for legacy preview URLs
        Route::get('deposit-preview', [PaymentController::class, 'showDepositFormPreview'])->name('deposit.preview');
        Route::post('deposit-preview/initialize', [PaymentController::class, 'initializeDepositPreview'])
            ->middleware('throttle:payment-initialize')
            ->name('deposit.preview.initialize');
        Route::post('deposit-preview/confirm', [PaymentController::class, 'confirmDepositPreview'])
            ->middleware('throttle:payment-confirm')
            ->name('deposit.preview.confirm');
    });
});
