<?php

use App\Http\Controllers\InstallerController;
use App\Http\Controllers\Admin\AddonProductsController;
use App\Http\Controllers\Admin\ApiKeysController;
use App\Http\Controllers\Admin\BannersController;
use App\Http\Controllers\Admin\PosDataController;
use App\Http\Controllers\Admin\BackupsController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\DevicesController;
use App\Http\Controllers\Admin\NewsletterController as AdminNewsletterController;
use App\Http\Controllers\Admin\NotificationTemplatesController;
use App\Http\Controllers\Admin\PaymentsController;
use App\Http\Controllers\Admin\SettingsController;
use App\Http\Controllers\Admin\StorageController;
use App\Http\Controllers\Admin\SubscriptionsController;
use App\Http\Controllers\Admin\SyncLogsController;
use App\Http\Controllers\Admin\UsersController;
use App\Http\Controllers\Admin\UserStaffController;
use App\Http\Controllers\Admin\VouchersController;
use App\Http\Controllers\Admin\WebhookEventsController;
use App\Http\Controllers\Admin\WebsiteController as AdminWebsiteController;
use App\Http\Controllers\ContactInquiryController;
use App\Http\Controllers\NewsletterController;
use App\Http\Controllers\SitemapController;
use App\Http\Controllers\WebsiteController;
use Illuminate\Support\Facades\Route;

// ─── Installer ───────────────────────────────────────────────────────────────
Route::prefix('install')->name('install.')->controller(InstallerController::class)->group(function () {
    Route::get('/',                'welcome')->name('welcome');
    Route::get('/requirements',    'requirements')->name('requirements');
    Route::get('/purchase-code',   'purchaseCode')->name('purchase-code');
    Route::post('/purchase-code',  'verifyPurchaseCode')->name('verify-purchase-code');
    Route::get('/database',        'database')->name('database');
    Route::post('/database',       'databaseSave')->name('database-save');
    Route::get('/migrate',         'migrate')->name('migrate');
    Route::post('/migrate',        'migrate');
    Route::get('/admin',           'admin')->name('admin');
    Route::post('/admin',          'adminSave')->name('admin-save');
    Route::get('/complete',        'complete')->name('complete');
});

// ─── Marketing Website ────────────────────────────────────────────────────────
Route::controller(WebsiteController::class)->group(function () {
    Route::get('/', 'home')->name('website.home');
    Route::get('/privacy', 'privacy')->name('website.privacy');
    Route::get('/terms', 'terms')->name('website.terms');
    Route::get('/contact', 'contact')->name('website.contact');
});
Route::post('/contact', [ContactInquiryController::class, 'store'])->name('website.contact.store');
Route::post('/newsletter', [NewsletterController::class, 'store'])->name('newsletter.store');
Route::get('/sitemap.xml', [SitemapController::class, 'index'])->name('sitemap');

// ─── Admin Auth ───────────────────────────────────────────────────────────────
Route::get('/admin/login', fn() => view('auth.admin-login'))->name('admin.login');
Route::post('/admin/login', function (\Illuminate\Http\Request $request) {
    $credentials = $request->validate([
        'email'    => 'required|email',
        'password' => 'required',
    ]);
    if (\Illuminate\Support\Facades\Auth::attempt($credentials, $request->boolean('remember'))) {
        if (!\Illuminate\Support\Facades\Auth::user()->is_admin) {
            \Illuminate\Support\Facades\Auth::logout();
            return back()->withErrors(['email' => 'Not an admin account.']);
        }
        $request->session()->regenerate();
        return redirect()->intended(route('admin.dashboard'));
    }
    return back()->withErrors(['email' => 'Invalid credentials.'])->withInput();
})->name('admin.login.post');

Route::post('/admin/logout', function () {
    \Illuminate\Support\Facades\Auth::logout();
    request()->session()->invalidate();
    request()->session()->regenerateToken();
    return redirect()->route('admin.login');
})->name('admin.logout');

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

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

        // Users
        Route::prefix('users')->name('users.')->controller(UsersController::class)->group(function () {
            Route::get('/', 'index')->name('index');
            Route::get('/{user}', 'show')->name('show');
            Route::post('/{user}/ban', 'ban')->name('ban');
            Route::post('/{user}/unban', 'unban')->name('unban');
            Route::post('/{user}/plan', 'setPlan')->name('set-plan');
            Route::delete('/{user}', 'destroy')->name('destroy');
        });

        // Staff management per user
        Route::prefix('users/{user}/staff')->name('users.staff.')
            ->controller(UserStaffController::class)
            ->group(function () {
                Route::post('/',          'store'  )->name('store');
                Route::put('/{staff}',   'update' )->name('update');
                Route::delete('/{staff}','destroy')->name('destroy');
            });

        // Subscriptions
        Route::get('/subscriptions', [SubscriptionsController::class, 'index'])->name('subscriptions.index');
        Route::post('/subscriptions/{subscription}/approve-crypto', [SubscriptionsController::class, 'approveCrypto'])->name('subscriptions.approve-crypto');
        Route::post('/subscriptions/{subscription}/reject-crypto', [SubscriptionsController::class, 'rejectCrypto'])->name('subscriptions.reject-crypto');
        Route::post('/subscriptions/{subscription}/cancel', [SubscriptionsController::class, 'cancelSubscription'])->name('subscriptions.cancel');

        // Payments
        Route::get('/payments', [PaymentsController::class, 'index'])->name('payments.index');

        // Add-on Products
        Route::prefix('addons')->name('addons.')->controller(AddonProductsController::class)->group(function () {
            Route::get('/', 'index')->name('index');
            Route::get('/purchases', 'purchases')->name('purchases');
            Route::get('/create', 'create')->name('create');
            Route::post('/', 'store')->name('store');
            Route::get('/{addon}/edit', 'edit')->name('edit');
            Route::put('/{addon}', 'update')->name('update');
            Route::post('/{addon}/toggle', 'toggle')->name('toggle');
            Route::delete('/{addon}', 'destroy')->name('destroy');
        });

        // API Keys
        Route::get('/api-keys', [ApiKeysController::class, 'index'])->name('api-keys.index');
        Route::post('/api-keys/{apiKey}/revoke', [ApiKeysController::class, 'revoke'])->name('api-keys.revoke');

        // Banners
        Route::prefix('banners')->name('banners.')->controller(BannersController::class)->group(function () {
            Route::get('/', 'index')->name('index');
            Route::post('/', 'store')->name('store');
            Route::put('/{banner}', 'update')->name('update');
            Route::delete('/{banner}', 'destroy')->name('destroy');
        });

        // Vouchers
        Route::prefix('vouchers')->name('vouchers.')->controller(VouchersController::class)->group(function () {
            Route::get('/', 'index')->name('index');
            Route::get('/create', 'create')->name('create');
            Route::post('/', 'store')->name('store');
            Route::post('/{voucher}/toggle', 'toggle')->name('toggle');
            Route::post('/{voucher}/send-push', 'sendPush')->name('sendPush');
            Route::get('/{voucher}/get-devices', 'getDevices')->name('getDevices');
            Route::delete('/{voucher}', 'destroy')->name('destroy');
        });

        // Devices
        Route::prefix('devices')->name('devices.')->controller(DevicesController::class)->group(function () {
            Route::get('/', 'index')->name('index');
            Route::post('/{device}/revoke', 'revoke')->name('revoke');
        });

        // Sync Logs
        Route::get('/sync-logs', [SyncLogsController::class, 'index'])->name('sync-logs.index');
        Route::get('/sync-logs/{userId}', [SyncLogsController::class, 'show'])->name('sync-logs.show');

        // Backups
        Route::get('/backups', [BackupsController::class, 'index'])->name('backups.index');
        Route::get('/backups/{userId}', [BackupsController::class, 'show'])->name('backups.show');

        // Storage
        Route::get('/storage', [StorageController::class, 'index'])->name('storage.index');

        // Settings
        Route::get('/settings', [SettingsController::class, 'index'])->name('settings.index');
        Route::post('/settings/integrations', [SettingsController::class, 'updateIntegrations'])->name('settings.integrations');
        Route::post('/settings/firebase', [SettingsController::class, 'updateFirebase'])->name('settings.firebase');
        Route::post('/settings/mail', [SettingsController::class, 'updateMail'])->name('settings.mail');
        Route::post('/settings/payments', [SettingsController::class, 'updatePayments'])->name('settings.payments');
        Route::post('/settings/test-email', [SettingsController::class, 'testEmail'])->name('settings.test-email');
        Route::post('/settings/test-notification', [SettingsController::class, 'testNotification'])->name('settings.test-notification');
        Route::post('/settings/password', [SettingsController::class, 'updatePassword'])->name('settings.password');
        Route::post('/settings/clear-cache', [SettingsController::class, 'clearCache'])->name('settings.clear-cache');
        Route::post('/settings/app-config', [SettingsController::class, 'updateAppConfig'])->name('settings.app-config');
        Route::post('/settings/license', [SettingsController::class, 'updateLicense'])->name('settings.license');
        Route::post('/settings/license/remove', [SettingsController::class, 'removeLicense'])->name('settings.license.remove');
        Route::post('/settings/seo', [SettingsController::class, 'updateSeo'])->name('settings.seo');
        Route::post('/settings/seo/ping', [SettingsController::class, 'pingSitemapEngines'])->name('settings.seo.ping');

        // Webhook Events
        Route::get('/webhooks', [WebhookEventsController::class, 'index'])->name('webhooks.index');

        // Website CMS
        Route::get('/website', [AdminWebsiteController::class, 'index'])->name('website.index');
        Route::post('/website', [AdminWebsiteController::class, 'update'])->name('website.update');
        Route::post('/website/upload-image', [AdminWebsiteController::class, 'uploadImage'])->name('website.upload-image');

        // Newsletter subscribers
        Route::prefix('newsletter')->name('newsletter.')->controller(AdminNewsletterController::class)->group(function () {
            Route::get('/', 'index')->name('index');
            Route::post('/{subscriber}/toggle', 'toggle')->name('toggle');
            Route::delete('/{subscriber}', 'destroy')->name('destroy');
        });

        // Push notification templates
        Route::prefix('notifications')->name('notifications.')->controller(NotificationTemplatesController::class)->group(function () {
            Route::get('/', 'index')->name('index');
            Route::put('/{template}', 'update')->name('update');
            Route::post('/{template}/toggle', 'toggle')->name('toggle');
            Route::post('/{template}/test', 'test')->name('test');
            Route::post('/send-manual', 'sendManual')->name('send-manual');
        });

        // POS Data (synced from devices)
        Route::prefix('pos')->name('pos.')->controller(PosDataController::class)->group(function () {
            Route::get('/products', 'products')->name('products');
            Route::get('/orders', 'orders')->name('orders');
            Route::get('/customers', 'customers')->name('customers');
            Route::get('/categories', 'categories')->name('categories');
            Route::get('/suppliers', 'suppliers')->name('suppliers');
            Route::get('/expenses', 'expenses')->name('expenses');
        });
    });
