<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use App\Models\Ticket;
use App\Models\License;

// ============================================================================
// CONTROLLERS IMPORTS
// ============================================================================

use App\Http\Controllers\HomeController;
use App\Http\Controllers\ReportsController;
use App\Http\Controllers\LicenseStatusController;

// User Controllers
use App\Http\Controllers\User\DashboardController as UserDashboardController;
use App\Http\Controllers\User\ProfileController as UserProfileController;
use App\Http\Controllers\User\TicketController as UserTicketController;
use App\Http\Controllers\User\EnvatoController as UserEnvatoController;
use App\Http\Controllers\User\InvoiceController as UserInvoiceController;

// Admin Controllers
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\TicketController as AdminTicketController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\ProductCategoryController;
use App\Http\Controllers\Admin\TicketCategoryController;
use App\Http\Controllers\Admin\ProgrammingLanguageController;
use App\Http\Controllers\Admin\InvoiceController as AdminInvoiceController;
use App\Http\Controllers\Admin\EmailTemplateController;

// API Controllers
use App\Http\Controllers\Api\LicenseApiController;

// Legacy Controllers (to be reviewed)
use App\Http\Controllers\LicenseController;
use App\Http\Controllers\LicenseDomainController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\EnvatoController;
use App\Http\Controllers\KbCategoryController;
use App\Http\Controllers\KbArticleController;

// ============================================================================
// PUBLIC ROUTES (No Authentication Required)
// ============================================================================

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

// Language Switcher
Route::get('lang/{locale}', function (string $locale) {
    // Get available languages dynamically from lang directory
    $availableLanguages = [];
    $langPath = resource_path('lang');
    
    if (is_dir($langPath)) {
        $directories = array_diff(scandir($langPath), ['.', '..']);
        foreach ($directories as $dir) {
            if (is_dir($langPath . DIRECTORY_SEPARATOR . $dir)) {
                $availableLanguages[] = $dir;
            }
        }
    }
    
    // If no languages found, fallback to default languages
    if (empty($availableLanguages)) {
        $availableLanguages = ['en', 'ar'];
    }
    
    if (in_array($locale, $availableLanguages)) {
        session(['locale' => $locale]);
    }
    return back();
})->name('lang.switch');

// ============================================================================
// PUBLIC FEATURES (License Status, KB, Products)
// ============================================================================

// License Status Check (Public Access)
Route::prefix('license-status')->group(function () {
    Route::get('/', [LicenseStatusController::class, 'index'])->name('license.status');
    Route::get('/status', [LicenseStatusController::class, 'index'])->name('license-status');
    Route::post('/check', [LicenseStatusController::class, 'check'])->name('license.status.check');
    Route::post('/history', [LicenseStatusController::class, 'history'])->name('license.status.history');
});

// Public Knowledge Base
Route::prefix('kb')->group(function () {
    Route::get('/', [\App\Http\Controllers\KbPublicController::class, 'index'])->name('kb.index');
    Route::get('/category/{slug}', [\App\Http\Controllers\KbPublicController::class, 'category'])->name('kb.category');
    Route::get('/article/{slug}', [\App\Http\Controllers\KbPublicController::class, 'article'])->name('kb.article');
    Route::get('/search', [\App\Http\Controllers\KbPublicController::class, 'search'])->name('kb.search');
});

// Public Support Tickets
Route::get('/support/create', [\App\Http\Controllers\User\TicketController::class, 'create'])->name('support.tickets.create');
Route::post('/support/store', [\App\Http\Controllers\User\TicketController::class, 'store'])->name('support.tickets.store');
Route::get('/support/ticket/{ticket}', [\App\Http\Controllers\User\TicketController::class, 'show'])->name('support.tickets.show');

// Verify purchase code for ticket creation (web route for XAMPP compatibility)
Route::get('/verify-purchase-code/{purchaseCode}', [\App\Http\Controllers\Api\TicketApiController::class, 'verifyPurchaseCode'])
    ->name('verify-purchase-code');

// Public Products
Route::prefix('products')->group(function () {
    Route::get('/', [\App\Http\Controllers\ProductController::class, 'publicIndex'])->name('public.products.index');
    Route::get('/{slug}', [\App\Http\Controllers\ProductController::class, 'publicShow'])->name('public.products.show');
});

// ============================================================================
// AUTHENTICATED USER ROUTES
// ============================================================================

Route::middleware(['auth', 'user', 'verified'])->group(function () {
    // User Dashboard
    Route::get('/dashboard', [UserDashboardController::class, 'index'])->name('dashboard');
    Route::get('/user/dashboard', [UserDashboardController::class, 'index'])->name('user.dashboard');

    // User Tickets
    Route::resource('user/tickets', UserTicketController::class, ['as' => 'user']);
    Route::post('user/tickets/{ticket}/reply', [UserTicketController::class, 'reply'])->name('user.tickets.reply');

    // User Licenses
    Route::get('licenses', [\App\Http\Controllers\User\LicenseController::class, 'index'])->name('user.licenses.index');
    Route::get('licenses/{license}', [\App\Http\Controllers\User\LicenseController::class, 'show'])->name('user.licenses.show');

    // User Products
    Route::get('user/products', [\App\Http\Controllers\ProductController::class, 'index'])->name('user.products.index');
    Route::get('user/products/{product}', [\App\Http\Controllers\ProductController::class, 'show'])->name('user.products.show');
    
    // User Product Files
    Route::get('user/products/{product}/files', [\App\Http\Controllers\User\ProductFileController::class, 'index'])->name('user.products.files.index');
    Route::get('user/products/{product}/files/download-all', [\App\Http\Controllers\User\ProductFileController::class, 'downloadAll'])->name('user.products.files.download-all');
    Route::get('user/product-files/{file}/download', [\App\Http\Controllers\User\ProductFileController::class, 'download'])
        ->middleware(\App\Http\Middleware\ProductFileSecurityMiddleware::class)
        ->name('user.product-files.download');

    // User Invoices (use user/ prefix and 'user.' name prefix so views can call user.invoices.*)
    Route::resource('user/invoices', \App\Http\Controllers\User\InvoiceController::class, ['as' => 'user']);

    // Envato Integration
    Route::prefix('envato')->group(function () {
        Route::post('/verify', [UserEnvatoController::class, 'verify'])->name('envato.verify');
        Route::post('/verify-user-purchase', [UserEnvatoController::class, 'verifyUserPurchase'])->name('envato.verify-user-purchase');
        Route::get('/link', [UserEnvatoController::class, 'linkEnvatoAccount'])->name('envato.link');
    });
});

// ============================================================================
// ADMIN ROUTES
// ============================================================================

Route::middleware(['auth', 'admin', 'verified'])->prefix('admin')->name('admin.')->group(function () {
    
    // Product data endpoint for license forms
    Route::get('products/{product}/data', [\App\Http\Controllers\Admin\ProductController::class, 'getProductData'])->name('products.data');
    // Admin Dashboard
    Route::get('/', [DashboardController::class, 'index'])->name('dashboard');
    Route::post('/clear-cache', [DashboardController::class, 'clearCache'])->name('clear-cache');

    // Dashboard AJAX endpoints
    Route::prefix('dashboard')->group(function () {
        Route::get('/stats', [DashboardController::class, 'getStats'])->name('dashboard.stats');
        Route::get('/system-overview', [DashboardController::class, 'getSystemOverviewData'])->name('dashboard.system-overview');
        Route::get('/license-distribution', [DashboardController::class, 'getLicenseDistributionData'])->name('dashboard.license-distribution');
        Route::get('/revenue', [DashboardController::class, 'getRevenueData'])->name('dashboard.revenue');
        Route::get('/activity-timeline', [DashboardController::class, 'getActivityTimelineData'])->name('dashboard.activity-timeline');
        Route::get('/api-requests', [DashboardController::class, 'getApiRequestsData'])->name('dashboard.api-requests');
        Route::get('/api-performance', [DashboardController::class, 'getApiPerformanceData'])->name('dashboard.api-performance');
    });

    // Products Management
    Route::resource('products', \App\Http\Controllers\Admin\ProductController::class);
    Route::prefix('products')->group(function () {
        Route::get('/envato/items', [\App\Http\Controllers\Admin\ProductController::class, 'getEnvatoUserItems'])->name('products.envato.items');
        Route::get('/envato/item-data', [\App\Http\Controllers\Admin\ProductController::class, 'getEnvatoProductData'])->name('products.envato.item-data');
    });
    Route::prefix('products/{product}')->group(function () {
        Route::get('/download-integration', [\App\Http\Controllers\Admin\ProductController::class, 'downloadIntegration'])->name('products.download-integration');
        Route::post('/regenerate-integration', [\App\Http\Controllers\Admin\ProductController::class, 'regenerateIntegration'])->name('products.regenerate-integration');
        Route::post('/generate-license', [\App\Http\Controllers\Admin\ProductController::class, 'generateTestLicense'])->name('products.generate-license');
        Route::get('/logs', [\App\Http\Controllers\Admin\ProductController::class, 'logs'])->name('products.logs');
        Route::get('/kb-data', [\App\Http\Controllers\Admin\ProductController::class, 'getKbData'])->name('products.kb-data');
        Route::get('/kb-articles/{categoryId}', [\App\Http\Controllers\Admin\ProductController::class, 'getKbArticles'])->name('products.kb-articles');
    });

    // Product Files Management
    Route::prefix('products/{product}/files')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\ProductFileController::class, 'index'])->name('products.files.index');
        Route::post('/', [\App\Http\Controllers\Admin\ProductFileController::class, 'store'])->name('products.files.store');
        Route::get('/statistics', [\App\Http\Controllers\Admin\ProductFileController::class, 'statistics'])->name('products.files.statistics');
    });
    Route::prefix('product-files/{file}')->group(function () {
        Route::get('/download', [\App\Http\Controllers\Admin\ProductFileController::class, 'download'])
            ->middleware(\App\Http\Middleware\ProductFileSecurityMiddleware::class)
            ->name('product-files.download');
        Route::put('/', [\App\Http\Controllers\Admin\ProductFileController::class, 'update'])->name('product-files.update');
        Route::delete('/', [\App\Http\Controllers\Admin\ProductFileController::class, 'destroy'])->name('product-files.destroy');
    });

    // Categories
    Route::resource('product-categories', ProductCategoryController::class);
    Route::resource('ticket-categories', TicketCategoryController::class);

    // Programming Languages
    Route::get('programming-languages/license-file/{language}', [ProgrammingLanguageController::class, 'getLicenseFileContent'])
        ->middleware('web')
        ->name('programming-languages.license-file');
    Route::get('programming-languages/export', [ProgrammingLanguageController::class, 'export'])->name('programming-languages.export');
    Route::get('programming-languages/available-templates', [ProgrammingLanguageController::class, 'getAvailableTemplates'])->name('programming-languages.available-templates');
    Route::post('programming-languages/validate-templates', [ProgrammingLanguageController::class, 'validateTemplates'])->name('programming-languages.validate-templates');
    Route::resource('programming-languages', ProgrammingLanguageController::class);
    Route::prefix('programming-languages/{programming_language}')->group(function () {
        Route::post('/toggle', [ProgrammingLanguageController::class, 'toggle'])->name('programming-languages.toggle');
        Route::get('/template-info', [ProgrammingLanguageController::class, 'getTemplateInfo'])->name('programming-languages.template-info');
        Route::get('/template-content', [ProgrammingLanguageController::class, 'getTemplateContent'])->name('programming-languages.template-content');
        Route::post('/upload-template', [ProgrammingLanguageController::class, 'uploadTemplate'])->name('programming-languages.upload-template');
        Route::post('/create-template-file', [ProgrammingLanguageController::class, 'createTemplateFile'])->name('programming-languages.create-template-file');
    });

    // Knowledge Base
    Route::resource('kb-categories', KbCategoryController::class);
    Route::resource('kb-articles', KbArticleController::class);

    // Support System
    Route::resource('tickets', AdminTicketController::class);
    Route::prefix('tickets/{ticket}')->group(function () {
        Route::post('/reply', [AdminTicketController::class, 'reply'])->name('tickets.reply');
        Route::patch('/update-status', [AdminTicketController::class, 'updateStatus'])->name('tickets.update-status');
    });

    // User Management
    Route::resource('users', UserController::class);
    Route::prefix('users/{user}')->group(function () {
        Route::post('/toggle-admin', [UserController::class, 'toggleAdmin'])->name('users.toggle-admin');
        Route::post('/send-password-reset', [UserController::class, 'sendPasswordReset'])->name('users.send-password-reset');
    });

    // License Management
    Route::resource('licenses', \App\Http\Controllers\Admin\LicenseController::class);
    Route::resource('license-domains', LicenseDomainController::class);

    // Invoice Management
    Route::resource('invoices', \App\Http\Controllers\Admin\InvoiceController::class);
    Route::prefix('invoices/{invoice}')->group(function () {
        Route::post('/mark-paid', [\App\Http\Controllers\Admin\InvoiceController::class, 'markAsPaid'])->name('invoices.mark-paid');
        Route::post('/cancel', [\App\Http\Controllers\Admin\InvoiceController::class, 'cancel'])->name('invoices.cancel');
    });

    // Invoice API
    Route::prefix('api')->group(function () {
        Route::get('/user/{user}/licenses', [\App\Http\Controllers\Admin\InvoiceController::class, 'getUserLicenses'])->name('api.user.licenses');
    });

    // System Settings
    Route::prefix('settings')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\SettingController::class, 'index'])->name('settings.index');
        Route::put('/', [\App\Http\Controllers\Admin\SettingController::class, 'update'])->name('settings.update');
        Route::post('/test-api', [\App\Http\Controllers\Admin\SettingController::class, 'testApi'])->name('settings.test-api');
    });

    // License Verification Guide
    Route::get('/license-verification-guide', [\App\Http\Controllers\Admin\LicenseVerificationGuideController::class, 'index'])->name('license-verification-guide.index');

    Route::prefix('profile')->name('profile.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\ProfileController::class, 'edit'])->name('edit');
        Route::patch('/', [\App\Http\Controllers\Admin\ProfileController::class, 'update'])->name('update');
        Route::patch('/password', [\App\Http\Controllers\Admin\ProfileController::class, 'updatePassword'])->name('update-password');
        Route::post('/connect-envato', [\App\Http\Controllers\Admin\ProfileController::class, 'connectEnvato'])->name('connect-envato');
        Route::post('/disconnect-envato', [\App\Http\Controllers\Admin\ProfileController::class, 'disconnectEnvato'])->name('disconnect-envato');
    });

    // Email Templates
    Route::resource('email-templates', \App\Http\Controllers\Admin\EmailTemplateController::class);
    Route::post('email-templates/{emailTemplate}/toggle', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'toggle'])->name('email-templates.toggle');
    Route::get('email-templates/{emailTemplate}/test', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'test'])->name('email-templates.test');
    Route::post('email-templates/{emailTemplate}/send-test', [\App\Http\Controllers\Admin\EmailTemplateController::class, 'sendTest'])->name('email-templates.send-test');

    
    // Reports & Analytics
    Route::prefix('reports')->name('reports.')->group(function () {
        Route::get('/', [ReportsController::class, 'index'])->name('index');
        Route::get('/license-data', [ReportsController::class, 'getLicenseData'])->name('license-data');
        Route::get('/api-status-data', [ReportsController::class, 'getApiStatusData'])->name('api-status-data');
        Route::get('/export', [ReportsController::class, 'export'])->name('export');
    });

    // License Verification Logs
    Route::prefix('license-verification-logs')->name('license-verification-logs.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\LicenseVerificationLogController::class, 'index'])->name('index');
        Route::get('/{log}', [\App\Http\Controllers\Admin\LicenseVerificationLogController::class, 'show'])->name('show');
        Route::get('/stats/data', [\App\Http\Controllers\Admin\LicenseVerificationLogController::class, 'getStats'])->name('stats');
        Route::get('/suspicious-activity/data', [\App\Http\Controllers\Admin\LicenseVerificationLogController::class, 'getSuspiciousActivity'])->name('suspicious-activity');
        Route::post('/clean-old', [\App\Http\Controllers\Admin\LicenseVerificationLogController::class, 'cleanOldLogs'])->name('clean-old');
        Route::get('/export/csv', [\App\Http\Controllers\Admin\LicenseVerificationLogController::class, 'export'])->name('export');
    });

    // Guides & Help
    Route::get('envato-guide', [\App\Http\Controllers\Admin\SettingController::class, 'envatoGuide'])->name('envato-guide');
});

// ============================================================================
// API ROUTES
// ============================================================================

// License Verification API - moved to api.php to avoid conflicts
// Route::prefix('api')->group(function () {
//     Route::post('/license/verify', [LicenseApiController::class, 'verify'])->middleware('throttle:30,1');
//     Route::post('/license/generate-integration', [LicenseController::class, 'generateIntegrationFile']);
// });

// ============================================================================
// OAUTH ROUTES
// ============================================================================

Route::prefix('auth/envato')->group(function () {
    Route::get('/', [UserEnvatoController::class, 'redirectToEnvato'])->name('auth.envato');
    Route::get('/callback', [UserEnvatoController::class, 'handleEnvatoCallback'])->name('auth.envato.callback');
});

// ============================================================================
// AUTHENTICATED USER PROFILE ROUTES
// ============================================================================

Route::middleware(['auth', 'user'])->group(function () {
    Route::get('/profile', [UserProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [UserProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [UserProfileController::class, 'destroy'])->name('profile.destroy');
    Route::post('/profile/unlink-envato', [UserProfileController::class, 'unlinkEnvato'])->name('profile.unlink-envato');
});

// ============================================================================
// AUTH ROUTES (Laravel Breeze/Jetstream)
// ============================================================================

require __DIR__.'/auth.php';

// ============================================================================
// INSTALLATION ROUTES
// ============================================================================

use App\Http\Controllers\InstallController;

Route::prefix('install')->name('install.')->middleware(['web', \App\Http\Middleware\CheckInstallation::class])->group(function () {
    // Welcome page
    Route::get('/', [InstallController::class, 'welcome'])->name('welcome');
    
    // License verification
    Route::get('/license', [InstallController::class, 'license'])->name('license');
    Route::post('/license', [InstallController::class, 'licenseStore'])->name('license.store');
    
    // Requirements check
    Route::get('/requirements', [InstallController::class, 'requirements'])->name('requirements');
    
    // Database configuration
    Route::get('/database', [InstallController::class, 'database'])->name('database');
    Route::post('/database', [InstallController::class, 'databaseStore'])->name('database.store');
    
    // Admin account creation
    Route::get('/admin', [InstallController::class, 'admin'])->name('admin');
    Route::post('/admin', [InstallController::class, 'adminStore'])->name('admin.store');
    
    // System settings
    Route::get('/settings', [InstallController::class, 'settings'])->name('settings');
    Route::post('/settings', [InstallController::class, 'settingsStore'])->name('settings.store');
    
    // Installation process
    Route::get('/install', [InstallController::class, 'install'])->name('install');
    Route::post('/process', [InstallController::class, 'installProcess'])->name('process');
    
    // Installation completion
    Route::get('/completion', [InstallController::class, 'completion'])->name('completion');
    
    // Test database connection
    Route::post('/test-database', [InstallController::class, 'testDatabase'])->name('install.test-database');
});

// ============================================================================
// UPDATE ROUTES
// Simple web updater: shows page to upload an update package (zip) and run migrations.
// WARNING: This is a convenience tool for local/dev updates. Use with caution in production.
// ============================================================================
Route::prefix('update')->name('update.')->middleware(['web', 'auth', \App\Http\Middleware\EnsureAdmin::class])->group(function () {
    Route::get('/', [\App\Http\Controllers\UpdateController::class, 'index'])->name('index');
    Route::post('/run', [\App\Http\Controllers\UpdateController::class, 'run'])->name('run');
    Route::get('/backups', [\App\Http\Controllers\UpdateController::class, 'backups'])->name('backups');
    Route::post('/backups/restore', [\App\Http\Controllers\UpdateController::class, 'restoreBackup'])->name('backups.restore');
});
