<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Setting;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use LicenseProtection\LicenseVerifier;

class InstallController extends Controller
{
    /**
     * Show installation welcome page
     */
    public function welcome(Request $request)
    {
        // Handle language switching
        if ($request->has('lang')) {
            $locale = $request->get('lang');
            if (in_array($locale, ['en', 'ar'])) {
                app()->setLocale($locale);
                session(['locale' => $locale]);
            }
        }

        return view('install.welcome', ['step' => 1, 'progressWidth' => 20]);
    }



    /**
     * Show license verification form
     */
    public function license()
    {
        return view('install.license', ['step' => 2, 'progressWidth' => 40]);
    }

    /**
     * Process license verification
     */
    public function licenseStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'purchase_code' => 'required|string|min:5|max:100',
        ], [
            'purchase_code.required' => 'Purchase code is required',
            'purchase_code.min' => 'Purchase code must be at least 5 characters long.',
            'purchase_code.max' => 'Purchase code must not exceed 100 characters.',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first('purchase_code')
                ], 422);
            }

            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        try {
            $licenseVerifier = new LicenseVerifier();
            $domain = $request->getHost();
            $result = $licenseVerifier->verifyLicense($request->purchase_code, $domain);

            if ($result['valid']) {
                // Store license information in session
                session([
                    'install.license' => [
                        'purchase_code' => $request->purchase_code,
                        'domain' => $domain,
                        'verified_at' => $result['verified_at'],
                        'product' => $result['product']
                    ]
                ]);

                if ($request->ajax()) {
                    return response()->json([
                        'success' => true,
                        'message' => 'License verified successfully!',
                        'redirect' => route('install.requirements')
                    ]);
                }

                return redirect()->route('install.requirements')
                    ->with('success', 'License verified successfully!');
            } else {
                // We now prioritize showing the human-readable message instead of the raw error_code
                $humanMessage = $result['message'] ?? 'License verification failed.';
                $errorCode = $result['error_code'] ?? $this->extractCodeFromMessage($humanMessage);

                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'error_code' => $errorCode,
                        // Return the message for UI display
                        'message' => $humanMessage
                    ], 400);
                }
                return redirect()->back()
                    ->withErrors(['license' => $humanMessage])
                    ->withInput();
            }

        } catch (\Exception $e) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'License verification failed: ' . $e->getMessage()
                ], 500);
            }

            return redirect()->back()
                ->withErrors(['license' => 'License verification failed: ' . $e->getMessage()])
                ->withInput();
        }
    }

    /**
     * Attempt to extract an UPPER_SNAKE_CASE code from a message (fallback)
     */
    private function extractCodeFromMessage(string $message): string
    {
        // Common known fragments mapping to codes
        $map = [
            'suspended' => 'LICENSE_SUSPENDED',
            'invalid purchase code' => 'INVALID_PURCHASE_CODE',
            'not found' => 'LICENSE_NOT_FOUND',
            'expired' => 'LICENSE_EXPIRED',
            'domain' => 'DOMAIN_UNAUTHORIZED',
            'too many' => 'RATE_LIMIT',
            'unauthorized' => 'UNAUTHORIZED',
        ];
        $lower = strtolower($message);
        foreach ($map as $frag => $code) {
            if (str_contains($lower, $frag)) {
                return $code;
            }
        }
        // If message already resembles a code
        if (preg_match('/[A-Z0-9_]{6,}/', $message, $m)) {
            return $m[0];
        }
        return 'LICENSE_VERIFICATION_FAILED';
    }

    /**
     * Show system requirements check
     */
    public function requirements()
    {
        // Check if license is verified
        $licenseConfig = session('install.license');
        if (!$licenseConfig) {
            return redirect()->route('install.license')
                ->with('error', 'Please verify your license first.');
        }

        $requirements = $this->checkRequirements();
        $allPassed = collect($requirements)->every(fn($req) => $req['passed']);

        return view('install.requirements', compact('requirements', 'allPassed') + ['step' => 3, 'progressWidth' => 60]);
    }


    /**
     * Show database configuration form
     */
    public function database()
    {
        // Check if license is verified
        $licenseConfig = session('install.license');
        if (!$licenseConfig) {
            return redirect()->route('install.license')
                ->with('error', 'Please verify your license first.');
        }

        return view('install.database', ['step' => 4, 'progressWidth' => 80]);
    }

    /**
     * Process database configuration
     */
    public function databaseStore(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'db_host' => 'required|string',
            'db_port' => 'required|integer|min:1|max:65535',
            'db_name' => 'required|string',
            'db_username' => 'required|string',
            'db_password' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Test database connection
        try {
            $connection = $this->testDatabaseConnection($request->all());
            if (!$connection['success']) {
                return redirect()->back()
                    ->withErrors(['database' => $connection['message']])
                    ->withInput();
            }
        } catch (\Exception $e) {
            return redirect()->back()
                ->withErrors(['database' => 'Database connection failed: ' . $e->getMessage()])
                ->withInput();
        }

        // Store database configuration
        session(['install.database' => $request->all()]);

        return redirect()->route('install.admin');
    }

    /**
     * Show admin account creation form
     */
    public function admin()
    {
        // Check if license is verified
        $licenseConfig = session('install.license');
        if (!$licenseConfig) {
            return redirect()->route('install.license')
                ->with('error', 'Please verify your license first.');
        }

        $databaseConfig = session('install.database');

        if (!$databaseConfig) {
            return redirect()->route('install.database')
                ->with('error', 'Please configure database settings first.');
        }

        return view('install.admin', ['step' => 5, 'progressWidth' => 100]);
    }

    /**
     * Process admin account creation
     */
    public function adminStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255',
            'password' => 'required|string|min:8|confirmed',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Store admin configuration
        session(['install.admin' => $request->all()]);

        return redirect()->route('install.settings');
    }

    /**
     * Show system settings form
     */
    public function settings()
    {
        // Check if license is verified
        $licenseConfig = session('install.license');
        if (!$licenseConfig) {
            return redirect()->route('install.license')
                ->with('error', 'Please verify your license first.');
        }

        $databaseConfig = session('install.database');
        $adminConfig = session('install.admin');

        if (!$databaseConfig) {
            return redirect()->route('install.database')
                ->with('error', 'Please configure database settings first.');
        }

        if (!$adminConfig) {
            return redirect()->route('install.admin')
                ->with('error', 'Please create admin account first.');
        }

        return view('install.settings', ['step' => 6, 'progressWidth' => 100]);
    }

    /**
     * Process system settings
     */
    public function settingsStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'site_name' => 'required|string|max:255',
            'site_description' => 'nullable|string|max:500',
            'admin_email' => 'required_if:enable_email,1|nullable|string|email|max:255',
            'timezone' => 'required|string',
            'locale' => 'required|string|in:en,ar',
            'enable_email' => 'nullable|boolean',
            'mail_mailer' => 'required_if:enable_email,1|nullable|string|in:smtp,mailgun,ses,postmark',
            'mail_host' => 'required_if:enable_email,1|nullable|string|max:255',
            'mail_port' => 'required_if:enable_email,1|nullable|integer|min:1|max:65535',
            'mail_encryption' => 'nullable|string|in:tls,ssl',
            'mail_username' => 'required_if:enable_email,1|nullable|string|max:255',
            'mail_password' => 'required_if:enable_email,1|nullable|string|max:255',
            'mail_from_address' => 'required_if:enable_email,1|nullable|email|max:255',
            'mail_from_name' => 'required_if:enable_email,1|nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Store system settings
        session(['install.settings' => $request->all()]);

        return redirect()->route('install.install');
    }

    /**
     * Show installation progress
     */
    public function install()
    {
        // Check if all required configuration is available
        $licenseConfig = session('install.license');
        $databaseConfig = session('install.database');
        $adminConfig = session('install.admin');
        $settingsConfig = session('install.settings');

        if (!$licenseConfig) {
            return redirect()->route('install.license')
                ->with('error', 'Please verify your license first.');
        }

        if (!$databaseConfig) {
            return redirect()->route('install.database')
                ->with('error', 'Please configure database settings first.');
        }

        if (!$adminConfig) {
            return redirect()->route('install.admin')
                ->with('error', 'Please create admin account first.');
        }

        if (!$settingsConfig) {
            return redirect()->route('install.settings')
                ->with('error', 'Please configure system settings first.');
        }

        return view('install.install', ['step' => 7, 'progressWidth' => 100]);
    }

    /**
     * Process installation
     */
    public function installProcess(Request $request)
    {
        // Installation process started


        try {
            // Get configuration from session
            $licenseConfig = session('install.license');
            $databaseConfig = session('install.database');
            $adminConfig = session('install.admin');
            $settingsConfig = session('install.settings');

            if (!$licenseConfig || !$databaseConfig || !$adminConfig || !$settingsConfig) {
                // Installation configuration missing
                return response()->json([
                    'success' => false,
                    'message' => 'Installation configuration missing. Please start over.'
                ], 400);
            }


            // Starting installation steps...

            // Step 1: Update .env file
            $this->updateEnvFile($databaseConfig, $settingsConfig);

            // Step 2: Run migrations
            Artisan::call('migrate:fresh', ['--force' => true]);

            // Step 3: Create roles and permissions first
            $this->createRolesAndPermissions();

            // Step 4: Run database seeders
            $this->runDatabaseSeeders();

            // Step 5: Create admin user
            $adminUser = $this->createAdminUser($adminConfig);

            // Step 6: Create default settings
            $this->createDefaultSettings($settingsConfig);

            // Step 7: Store license information
            $this->storeLicenseInformation($licenseConfig);

            // Step 8: Update session and cache drivers to database
            $this->updateSessionDrivers();

            // Step 9: Create storage link
            try {
                Artisan::call('storage:link');
            } catch (\Exception $e) {
                // Storage link might already exist or fail, continue anyway
            }

            // Step 10: Create installed file
            File::put(storage_path('.installed'), now()->toDateTimeString());

            // Installation completed successfully

            return response()->json([
                'success' => true,
                'message' => 'Installation completed successfully!',
                'redirect' => route('login')
            ], 200, [], JSON_UNESCAPED_SLASHES);

        } catch (\Exception $e) {
            // Installation failed

            return response()->json([
                'success' => false,
                'message' => 'Installation failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Show installation completion page
     */
    public function completion()
    {
        // Check if system is installed
        $installedFile = storage_path('.installed');
        if (!File::exists($installedFile)) {
            return redirect()->route('install.welcome');
        }

        // Check if we have session data
        $licenseConfig = session('install.license');
        $adminConfig = session('install.admin');
        $settingsConfig = session('install.settings');
        $databaseConfig = session('install.database');

        if (!$licenseConfig || !$adminConfig || !$settingsConfig || !$databaseConfig) {
            return redirect()->route('install.welcome');
        }

        // Pass session data to view before clearing
        $viewData = [
            'step' => 7,
            'progressWidth' => 100,
            'licenseConfig' => $licenseConfig,
            'adminConfig' => $adminConfig,
            'settingsConfig' => $settingsConfig,
            'databaseConfig' => $databaseConfig
        ];

        // Clear session data after passing to view
        session()->forget(['install.license', 'install.database', 'install.admin', 'install.settings']);

        return view('install.completion', $viewData);
    }


    /**
     * Check system requirements
     */
    public function checkRequirements()
    {
        return [
            'php_version' => [
                'name' => 'PHP Version >= 8.2',
                'required' => '8.2',
                'current' => PHP_VERSION,
                'passed' => version_compare(PHP_VERSION, '8.2.0', '>=')
            ],
            'bcmath' => [
                'name' => 'BCMath Extension',
                'required' => 'Required',
                'current' => extension_loaded('bcmath') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('bcmath')
            ],
            'ctype' => [
                'name' => 'Ctype Extension',
                'required' => 'Required',
                'current' => extension_loaded('ctype') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('ctype')
            ],
            'curl' => [
                'name' => 'cURL Extension',
                'required' => 'Required',
                'current' => extension_loaded('curl') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('curl')
            ],
            'dom' => [
                'name' => 'DOM Extension',
                'required' => 'Required',
                'current' => extension_loaded('dom') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('dom')
            ],
            'fileinfo' => [
                'name' => 'Fileinfo Extension',
                'required' => 'Required',
                'current' => extension_loaded('fileinfo') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('fileinfo')
            ],
            'json' => [
                'name' => 'JSON Extension',
                'required' => 'Required',
                'current' => extension_loaded('json') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('json')
            ],
            'mbstring' => [
                'name' => 'Mbstring Extension',
                'required' => 'Required',
                'current' => extension_loaded('mbstring') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('mbstring')
            ],
            'openssl' => [
                'name' => 'OpenSSL Extension',
                'required' => 'Required',
                'current' => extension_loaded('openssl') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('openssl')
            ],
            'pcre' => [
                'name' => 'PCRE Extension',
                'required' => 'Required',
                'current' => extension_loaded('pcre') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('pcre')
            ],
            'pdo' => [
                'name' => 'PDO Extension',
                'required' => 'Required',
                'current' => extension_loaded('pdo') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('pdo')
            ],
            'tokenizer' => [
                'name' => 'Tokenizer Extension',
                'required' => 'Required',
                'current' => extension_loaded('tokenizer') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('tokenizer')
            ],
            'xml' => [
                'name' => 'XML Extension',
                'required' => 'Required',
                'current' => extension_loaded('xml') ? 'Loaded' : 'Not Loaded',
                'passed' => extension_loaded('xml')
            ],
            'storage_writable' => [
                'name' => 'Storage Directory Writable',
                'required' => 'Writable',
                'current' => is_writable(storage_path()) ? 'Writable' : 'Not Writable',
                'passed' => is_writable(storage_path())
            ],
            'bootstrap_writable' => [
                'name' => 'Bootstrap Cache Directory Writable',
                'required' => 'Writable',
                'current' => is_writable(base_path('bootstrap/cache')) ? 'Writable' : 'Not Writable',
                'passed' => is_writable(base_path('bootstrap/cache'))
            ]
        ];
    }

    /**
     * Test database connection
     */
    private function testDatabaseConnection($config)
    {
        try {
            $connection = new \PDO(
                "mysql:host={$config['db_host']};port={$config['db_port']};dbname={$config['db_name']}",
                $config['db_username'],
                $config['db_password']
            );
            $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            return ['success' => true, 'message' => 'Database connection successful'];
        } catch (\PDOException $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    /**
     * Update .env file
     */
    private function updateEnvFile($databaseConfig, $settingsConfig)
    {
        $envPath = base_path('.env');
        $envContent = File::get($envPath);

        // Update database configuration
        $envContent = preg_replace('/DB_HOST=.*/', "DB_HOST={$databaseConfig['db_host']}", $envContent);
        $envContent = preg_replace('/DB_PORT=.*/', "DB_PORT={$databaseConfig['db_port']}", $envContent);
        $envContent = preg_replace('/DB_DATABASE=.*/', "DB_DATABASE={$databaseConfig['db_name']}", $envContent);
        $envContent = preg_replace('/DB_USERNAME=.*/', "DB_USERNAME={$databaseConfig['db_username']}", $envContent);
        $envContent = preg_replace('/DB_PASSWORD=.*/', "DB_PASSWORD={$databaseConfig['db_password']}", $envContent);

        // Update application configuration
        $envContent = preg_replace('/APP_NAME=.*/', "APP_NAME=\"{$settingsConfig['site_name']}\"", $envContent);
        // Update APP_URL to current domain (this ensures emails use the correct domain)
        $currentUrl = request()->getSchemeAndHttpHost();
        $envContent = preg_replace('/APP_URL=.*/', "APP_URL={$currentUrl}", $envContent);
        $envContent = preg_replace('/APP_TIMEZONE=.*/', "APP_TIMEZONE={$settingsConfig['timezone']}", $envContent);
        // Add APP_TIMEZONE if it doesn't exist
        if (!str_contains($envContent, 'APP_TIMEZONE=')) {
            $envContent .= "\nAPP_TIMEZONE={$settingsConfig['timezone']}";
        }
        $envContent = preg_replace('/APP_LOCALE=.*/', "APP_LOCALE={$settingsConfig['locale']}", $envContent);
        // Add APP_LOCALE if it doesn't exist
        if (!str_contains($envContent, 'APP_LOCALE=')) {
            $envContent .= "\nAPP_LOCALE={$settingsConfig['locale']}";
        }
        // Update APP_FALLBACK_LOCALE
        $envContent = preg_replace('/APP_FALLBACK_LOCALE=.*/', "APP_FALLBACK_LOCALE={$settingsConfig['locale']}", $envContent);
        // Add APP_FALLBACK_LOCALE if it doesn't exist
        if (!str_contains($envContent, 'APP_FALLBACK_LOCALE=')) {
            $envContent .= "\nAPP_FALLBACK_LOCALE={$settingsConfig['locale']}";
        }
        // Update APP_FAKER_LOCALE
        $fakerLocale = $settingsConfig['locale'] === 'ar' ? 'ar_SA' : 'en_US';
        $envContent = preg_replace('/APP_FAKER_LOCALE=.*/', "APP_FAKER_LOCALE={$fakerLocale}", $envContent);
        // Add APP_FAKER_LOCALE if it doesn't exist
        if (!str_contains($envContent, 'APP_FAKER_LOCALE=')) {
            $envContent .= "\nAPP_FAKER_LOCALE={$fakerLocale}";
        }

        // Update email configuration if enabled
        if (isset($settingsConfig['enable_email']) && $settingsConfig['enable_email']) {
            $envContent = preg_replace('/MAIL_MAILER=.*/', "MAIL_MAILER={$settingsConfig['mail_mailer']}", $envContent);
            $envContent = preg_replace('/MAIL_HOST=.*/', "MAIL_HOST={$settingsConfig['mail_host']}", $envContent);
            $envContent = preg_replace('/MAIL_PORT=.*/', "MAIL_PORT={$settingsConfig['mail_port']}", $envContent);
            $envContent = preg_replace('/MAIL_USERNAME=.*/', "MAIL_USERNAME={$settingsConfig['mail_username']}", $envContent);
            $envContent = preg_replace('/MAIL_PASSWORD=.*/', "MAIL_PASSWORD={$settingsConfig['mail_password']}", $envContent);
            $envContent = preg_replace('/MAIL_ENCRYPTION=.*/', "MAIL_ENCRYPTION={$settingsConfig['mail_encryption']}", $envContent);
            $envContent = preg_replace('/MAIL_FROM_ADDRESS=.*/', "MAIL_FROM_ADDRESS={$settingsConfig['mail_from_address']}", $envContent);
            $envContent = preg_replace('/MAIL_FROM_NAME=.*/', "MAIL_FROM_NAME=\"{$settingsConfig['mail_from_name']}\"", $envContent);
        }

        // Keep session and cache drivers as file during installation
        // They will be updated to database after migrations are complete
        // $envContent = preg_replace('/SESSION_DRIVER=.*/', "SESSION_DRIVER=database", $envContent);
        // $envContent = preg_replace('/CACHE_STORE=.*/', "CACHE_STORE=database", $envContent);
        // $envContent = preg_replace('/QUEUE_CONNECTION=.*/', "QUEUE_CONNECTION=database", $envContent);

        // Set debug to false for production
        $envContent = preg_replace('/APP_DEBUG=.*/', "APP_DEBUG=false", $envContent);

        File::put($envPath, $envContent);
    }

    /**
     * Update session and cache drivers to database after migrations
     */
    private function updateSessionDrivers()
    {
        $envPath = base_path('.env');
        $envContent = File::get($envPath);

        // Update session and cache drivers to database after migrations are complete
        $envContent = preg_replace('/SESSION_DRIVER=.*/', "SESSION_DRIVER=database", $envContent);
        $envContent = preg_replace('/CACHE_STORE=.*/', "CACHE_STORE=database", $envContent);
        $envContent = preg_replace('/QUEUE_CONNECTION=.*/', "QUEUE_CONNECTION=database", $envContent);

        File::put($envPath, $envContent);
    }

    /**
     * Create roles and permissions
     */
    private function createRolesAndPermissions()
    {
        try {
            // Create permissions
            $permissions = [
                'manage_users',
                'manage_products',
                'manage_licenses',
                'manage_tickets',
                'manage_settings',
                'manage_knowledge_base',
                'view_reports',
                'manage_invoices'
            ];

            foreach ($permissions as $permission) {
                Permission::firstOrCreate(['name' => $permission]);
            }

            // Create admin role
            $adminRole = Role::firstOrCreate(['name' => 'admin']);
            $adminRole->givePermissionTo($permissions);

            // Create user role
            $userRole = Role::firstOrCreate(['name' => 'user']);
            $userRole->givePermissionTo(['view_reports']);

            // Roles and permissions created successfully
        } catch (\Exception $e) {
            // Failed to create roles and permissions
            throw $e;
        }
    }

    /**
     * Create admin user
     */
    private function createAdminUser($adminConfig)
    {
        try {
            $user = User::create([
                'name' => $adminConfig['name'],
                'email' => $adminConfig['email'],
                'password' => Hash::make($adminConfig['password']),
                'email_verified_at' => now(),
                'status' => 'active',
                'email_verified' => true,
            ]);

            $user->assignRole('admin');

            // Admin user created successfully
            return $user;
        } catch (\Exception $e) {
            // Failed to create admin user
            throw $e;
        }
    }

    /**
     * Create default settings
     */
    private function createDefaultSettings($settingsConfig)
    {
        try {
            Setting::create([
                'site_name' => $settingsConfig['site_name'],
                'site_description' => $settingsConfig['site_description'],
                'admin_email' => $settingsConfig['admin_email'] ?? null,
                'timezone' => $settingsConfig['timezone'],
                'locale' => $settingsConfig['locale'],
                'preloader_enabled' => true,
                'preloader_type' => 'spinner',
                'preloader_color' => '#3b82f6',
                'preloader_background_color' => '#ffffff',
                'preloader_duration' => 2000,
                'logo_show_text' => true,
                'logo_text' => $settingsConfig['site_name'],
                'maintenance_mode' => false,
                'registration_enabled' => true,
                'email_verification_required' => isset($settingsConfig['enable_email']) && $settingsConfig['enable_email'],
            ]);

            // Default settings created successfully
        } catch (\Exception $e) {
            // Failed to create default settings
            throw $e;
        }
    }

    /**
     * Test database connection
     */
    public function testDatabase(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'db_host' => 'required|string',
            'db_port' => 'required|integer|min:1|max:65535',
            'db_name' => 'required|string',
            'db_username' => 'required|string',
            'db_password' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $connection = $this->testDatabaseConnection($request->all());

        return response()->json($connection);
    }

    /**
     * Run specific database seeders
     */
    private function runDatabaseSeeders()
    {
        try {
            // Run only the required seeders
            $seeders = [
                'Database\\Seeders\\TicketCategorySeeder',
                'Database\\Seeders\\ProgrammingLanguageSeeder',
                'Database\\Seeders\\EmailTemplateSeeder'
            ];

            foreach ($seeders as $seeder) {
                try {
                    Artisan::call('db:seed', [
                        '--class' => $seeder,
                        '--force' => true
                    ]);
                    // Seeder executed successfully
                } catch (\Exception $seederError) {
                    // Failed to run seeder
                    // Continue with other seeders even if one fails
                }
            }

            // Required database seeders execution completed
        } catch (\Exception $e) {
            // Failed to run database seeders
            throw $e;
        }
    }

    /**
     * Store license information in database
     */
    private function storeLicenseInformation($licenseConfig)
    {
        try {
            // Store license information in settings table
            Setting::create([
                'key' => 'license_purchase_code',
                'value' => $licenseConfig['purchase_code'],
                'type' => 'license'
            ]);

            Setting::create([
                'key' => 'license_domain',
                'value' => $licenseConfig['domain'],
                'type' => 'license'
            ]);

            Setting::create([
                'key' => 'license_verified_at',
                'value' => $licenseConfig['verified_at'],
                'type' => 'license'
            ]);

            Setting::create([
                'key' => 'license_product',
                'value' => $licenseConfig['product'],
                'type' => 'license'
            ]);

            // License information stored successfully
        } catch (\Exception $e) {
            // Failed to store license information
            throw $e;
        }
    }
}
