<?php

use App\Http\Controllers\Admin;
use App\Http\Controllers\Customer;
use Illuminate\Support\Facades\Route;

Route::get('/', fn() => view('welcome'))->name('home');

// ── Public API Documentation (no auth required) ───────────────────────────────
Route::get('/docs', fn() => view('docs.api', ['baseUrl' => rtrim(config('app.url'), '/')]))->name('docs');
Route::get('/dashboard', fn() => redirect('/customer/dashboard'))->middleware(['auth'])->name('dashboard');

require __DIR__ . '/auth.php';

// ── Admin Auth ────────────────────────────────────────────────────────────────
Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('/login',   [Admin\AuthController::class, 'showLogin'])->name('login');
    Route::post('/login',  [Admin\AuthController::class, 'login'])->name('login.submit');
    Route::post('/logout', [Admin\AuthController::class, 'logout'])->name('logout');
});

// ── Admin Docs ────────────────────────────────────────────────────────────────
Route::middleware([\App\Http\Middleware\AdminMiddleware::class])
    ->get('/admin/docs', fn() => view('admin.docs.index', ['baseUrl' => rtrim(config('app.url'), '/')])
    )->name('admin.docs');

// ── Admin Profile ─────────────────────────────────────────────────────────────
Route::middleware([\App\Http\Middleware\AdminMiddleware::class])
    ->prefix('admin')->name('admin.')->group(function () {
    Route::get('/profile',           [Admin\ProfileController::class, 'show'])->name('profile');
    Route::patch('/profile/info',    [Admin\ProfileController::class, 'updateInfo'])->name('profile.update-info');
    Route::patch('/profile/password',[Admin\ProfileController::class, 'updatePassword'])->name('profile.update-password');
});

// ── Customer Portal ───────────────────────────────────────────────────────────
Route::middleware(['auth'])->prefix('customer')->name('customer.')->group(function () {

    Route::get('/dashboard',  [Customer\DashboardController::class, 'index'])->name('dashboard');

    // Bulletin
    Route::get('/bulletin',                        [Customer\BulletinController::class, 'index'])->name('bulletin');
    Route::get('/bulletin/{bulletin}',             [Customer\BulletinController::class, 'show'])->name('bulletin.show');
    Route::post('/bulletin/{bulletin}/comment',    [Customer\BulletinController::class, 'comment'])->name('bulletin.comment');

    // Licenses
    Route::prefix('licenses')->name('licenses.')->group(function () {
        Route::get('/',                                        [Customer\LicenseController::class, 'index'])->name('index');
        Route::get('/{license}',                              [Customer\LicenseController::class, 'show'])->name('show');
        Route::get('/{license}/credentials',                  [Customer\LicenseController::class, 'apiCredentials'])->name('credentials');
        Route::delete('/{license}/activations/{activation}',  [Customer\LicenseController::class, 'deactivateActivation'])->name('deactivate-activation');
    });

    // Market
    Route::get('/market',         [Customer\MarketController::class, 'index'])->name('market');
    Route::get('/market/{product}', [Customer\MarketController::class, 'show'])->name('market.show');

    // Downloads
    Route::get('/downloads',             [Customer\DownloadsController::class, 'index'])->name('downloads');
    Route::get('/downloads/{license}/get', [Customer\DownloadsController::class, 'download'])->name('downloads.get');

    // Services
    Route::get('/services',  [Customer\ServicesController::class, 'index'])->name('services');

    // Profile
    Route::get('/profile',                [Customer\ProfileController::class, 'show'])->name('profile');
    Route::post('/profile/info',          [Customer\ProfileController::class, 'updateInfo'])->name('profile.info');
    Route::post('/profile/password',      [Customer\ProfileController::class, 'updatePassword'])->name('profile.password');

    // Checkout — specific named routes BEFORE the wildcard show route
    Route::get('/checkout/paypal/success', [Customer\CheckoutController::class, 'paypalSuccess'])->name('checkout.paypal.success');
    Route::get('/checkout/paypal/cancel',  [Customer\CheckoutController::class, 'paypalCancel'])->name('checkout.paypal.cancel');
    Route::get('/checkout/stripe/success',   [Customer\CheckoutController::class, 'stripeSuccess'])->name('checkout.stripe.success');
    Route::get('/checkout/stripe/cancel',    [Customer\CheckoutController::class, 'stripeCancel'])->name('checkout.stripe.cancel');
    Route::post('/checkout/razorpay/success',[Customer\CheckoutController::class, 'razorpaySuccess'])->name('checkout.razorpay.success');
    Route::get('/checkout/cashfree/success', [Customer\CheckoutController::class, 'cashfreeSuccess'])->name('checkout.cashfree.success');
    Route::get('/checkout/manual/{order}', [Customer\CheckoutController::class, 'manualConfirm'])->name('checkout.manual');
    Route::get('/checkout/{product}',      [Customer\CheckoutController::class, 'show'])->name('checkout.show');
    Route::post('/checkout/{product}',     [Customer\CheckoutController::class, 'initiate'])->name('checkout.initiate');

    // Currency preference
    Route::post('/currency/{code}', [Customer\CurrencyController::class, 'set'])->name('currency.set');

    // Support Tickets
    Route::prefix('support')->name('support.')->group(function () {
        Route::get('/',                          [Customer\SupportController::class, 'index'])->name('index');
        Route::get('/create',                    [Customer\SupportController::class, 'create'])->name('create');
        Route::post('/',                         [Customer\SupportController::class, 'store'])->name('store');
        Route::get('/{ticket}',                  [Customer\SupportController::class, 'show'])->name('show');
        Route::post('/{ticket}/reply',           [Customer\SupportController::class, 'reply'])->name('reply');
        Route::post('/{ticket}/close',           [Customer\SupportController::class, 'close'])->name('close');
    });
});

// ── Admin Panel ───────────────────────────────────────────────────────────────
Route::middleware([\App\Http\Middleware\AdminMiddleware::class])
    ->prefix('admin')->name('admin.')
    ->group(function () {

    Route::get('/dashboard', [Admin\DashboardController::class, 'index'])->name('dashboard');

    // Bulletin
    Route::resource('bulletin', Admin\BulletinController::class)->except(['show'])->parameters(['bulletin'=>'bulletin']);
    Route::get('/bulletin/{bulletin}',        [Admin\BulletinController::class, 'show'])->name('bulletin.show');
    Route::post('/bulletin/{bulletin}/publish',  [Admin\BulletinController::class, 'publish'])->name('bulletin.publish');
    Route::post('/bulletin/{bulletin}/unpublish',[Admin\BulletinController::class, 'unpublish'])->name('bulletin.unpublish');
    Route::post('/bulletin/{bulletin}/pin',      [Admin\BulletinController::class, 'pin'])->name('bulletin.pin');

    Route::resource('products', Admin\ProductController::class);
    Route::post('/products/{product}/versions', [Admin\ProductController::class, 'storeVersion'])->name('products.versions.store');

    Route::resource('licenses', Admin\LicenseController::class)->except(['edit', 'update', 'destroy']);
    Route::post('/licenses/{license}/suspend',    [Admin\LicenseController::class, 'suspend'])->name('licenses.suspend');
    Route::post('/licenses/{license}/reinstate',  [Admin\LicenseController::class, 'reinstate'])->name('licenses.reinstate');
    Route::post('/licenses/{license}/revoke',     [Admin\LicenseController::class, 'revoke'])->name('licenses.revoke');
    Route::post('/licenses/{license}/extend',     [Admin\LicenseController::class, 'extendExpiry'])->name('licenses.extend');
    Route::post('/licenses/{license}/rotate-key',            [Admin\LicenseController::class, 'rotateKey'])->name('licenses.rotate-key');
    Route::post('/licenses/{license}/register-activation',  [Admin\LicenseController::class, 'registerActivation'])->name('licenses.register-activation');
    Route::delete('/licenses/{license}/activations/{activation}', [Admin\LicenseController::class, 'removeActivation'])->name('licenses.deactivate-activation');

    Route::resource('customers', Admin\CustomerController::class)->only(['index', 'show']);
    Route::post('/customers/{customer}/suspend',  [Admin\CustomerController::class, 'suspend'])->name('customers.suspend');
    Route::post('/customers/{customer}/activate', [Admin\CustomerController::class, 'activate'])->name('customers.activate');

    Route::resource('orders', Admin\OrderController::class)->only(['index', 'show', 'create', 'store']);
    Route::post('/orders/{order}/mark-paid', [Admin\OrderController::class, 'markPaid'])->name('orders.mark-paid');

    // Support
    Route::prefix('support')->name('support.')->group(function () {
        Route::get('/',                       [Admin\SupportController::class, 'index'])->name('index');
        Route::get('/{ticket}',               [Admin\SupportController::class, 'show'])->name('show');
        Route::post('/{ticket}/reply',        [Admin\SupportController::class, 'reply'])->name('reply');
        Route::patch('/{ticket}/status',      [Admin\SupportController::class, 'updateStatus'])->name('status');
        Route::patch('/{ticket}/assign',      [Admin\SupportController::class, 'assign'])->name('assign');
    });

    // Settings (specific routes MUST come before {group} wildcard)
    Route::get('/settings',                    [Admin\SettingsController::class, 'index'])->name('settings.index');
    Route::post('/settings/email/test',        [Admin\SettingsController::class, 'testEmail'])->name('settings.test-email');
    Route::get('/settings/{group}',            [Admin\SettingsController::class, 'show'])->name('settings.group');
    Route::post('/settings/{group}',           [Admin\SettingsController::class, 'update'])->name('settings.update');

    // Tax
    Route::get('/tax',                            [Admin\TaxController::class, 'index'])->name('tax.index');
    Route::post('/tax/settings',                  [Admin\TaxController::class, 'saveSettings'])->name('tax.settings');
    Route::post('/tax/simulate',                  [Admin\TaxController::class, 'simulate'])->name('tax.simulate');
    Route::post('/tax/rules',                     [Admin\TaxController::class, 'storeRule'])->name('tax.rules.store');
    Route::post('/tax/rules/{rule}/rate',         [Admin\TaxController::class, 'updateRule'])->name('tax.rules.update');
    Route::post('/tax/rules/{rule}/duplicate',    [Admin\TaxController::class, 'duplicateRule'])->name('tax.rules.duplicate');
    Route::delete('/tax/rules/{rule}',            [Admin\TaxController::class, 'destroyRule'])->name('tax.rules.destroy');

    // Payment Gateways
    Route::get('/payment-gateways',  [Admin\PaymentGatewayController::class, 'index'])->name('payment-gateways.index');
    Route::post('/payment-gateways', [Admin\PaymentGatewayController::class, 'update'])->name('payment-gateways.update');

    // Currencies
    Route::get('/currencies',                              [Admin\CurrencyController::class, 'index'])->name('currencies.index');
    Route::post('/currencies',                             [Admin\CurrencyController::class, 'store'])->name('currencies.store');
    Route::post('/currencies/update-rates',                [Admin\CurrencyController::class, 'updateLiveRates'])->name('currencies.update-rates');
    Route::post('/currencies/recalculate-pricing',         [Admin\CurrencyController::class, 'recalculatePricing'])->name('currencies.recalculate');
    Route::post('/currencies/{currency}/rate',             [Admin\CurrencyController::class, 'updateRate'])->name('currencies.update-rate');
    Route::post('/currencies/{currency}/set-default',      [Admin\CurrencyController::class, 'setDefault'])->name('currencies.set-default');
    Route::post('/currencies/{currency}/set-base',         [Admin\CurrencyController::class, 'setBase'])->name('currencies.set-base');
    Route::post('/currencies/{currency}/toggle',           [Admin\CurrencyController::class, 'toggle'])->name('currencies.toggle');
    Route::delete('/currencies/{currency}',                [Admin\CurrencyController::class, 'destroy'])->name('currencies.destroy');

    Route::get('/security/events',                  [Admin\SecurityController::class, 'events'])->name('security.events');
    Route::post('/security/events/{event}/resolve', [Admin\SecurityController::class, 'resolveEvent'])->name('security.events.resolve');
    Route::get('/security/audit',                   [Admin\SecurityController::class, 'auditLog'])->name('security.audit');
    Route::get('/security/api-monitor',             [Admin\SecurityController::class, 'apiMonitor'])->name('security.api-monitor');
});
