<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\User;
use App\Models\PoliceStation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Symfony\Component\Process\Process;

class SettingsController extends Controller
{
    /**
     * Display the settings index page.
     */
    public function index()
    {
        // Redirect to general settings by default
        return redirect()->route('settings.general');
    }

    /**
     * Display the general settings page.
     */
    public function general()
    {
        // Get general settings
        $settings = Setting::where('group', 'general')->get();
        
        return view('settings.general', compact('settings'));
    }
    
    /**
     * Update general settings.
     */
    public function updateGeneral(Request $request)
    {
        $validated = $request->validate([
            'site_name' => 'required|string|max:255',
            'site_description' => 'nullable|string',
            'contact_email' => 'required|email',
            'contact_phone' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);
        
        // Handle logo upload if provided
        if ($request->hasFile('logo')) {
            $logoPath = $request->file('logo')->store('logos', 'public');
            Setting::setValue('logo_path', $logoPath, 'general', 'string', 'Path to system logo');
        }
        
        // Save other settings
        foreach ($validated as $key => $value) {
            if ($key !== 'logo') {
                Setting::setValue($key, $value, 'general', 'string');
            }
        }
        
        // Log the settings update
        Log::info('General settings updated by user: ' . auth()->user()->name);
        
        return redirect()->route('settings.general')
            ->with('success', 'General settings updated successfully.');
    }
    
    /**
     * Display the backup settings page.
     */
    public function backup()
    {
        // Create the backup directory in the app directory (not app/private)
        $backupDir = storage_path('app/backups');
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0755, true);
        }
        
        // Get list of existing backups directly from the filesystem
        $backupFiles = glob($backupDir . '/*.sql');
        $backups = [];
        
        foreach ($backupFiles as $file) {
            $backups[] = [
                'name' => basename($file),
                'path' => $file,
                'size' => filesize($file),
                'date' => filemtime($file)
            ];
        }
        
        // Debug information
        Log::info('Backup directory: ' . $backupDir);
        Log::info('Number of backups found: ' . count($backups));
        
        // Get backup settings
        $settings = Setting::where('group', 'backup')->get();
        
        return view('settings.backup', compact('backups', 'settings'));
    }
    
    /**
     * Create a new database backup.
     */
    public function createBackup()
    {
        try {
            // Generate a unique filename for the backup
            $timestamp = date('Y-m-d_H-i-s');
            $filename = 'backup_' . $timestamp . '.sql';
            $backupDir = storage_path('app/backups');
            $path = $backupDir . '/' . $filename;
            
            // Ensure backup directory exists
            if (!is_dir($backupDir)) {
                mkdir($backupDir, 0755, true);
            }
            
            // Also ensure through Storage facade
            if (!Storage::disk('local')->exists('backups')) {
                Storage::disk('local')->makeDirectory('backups');
            }
            
            // Get database configuration
            $dbHost = config('database.connections.mysql.host');
            $dbPort = config('database.connections.mysql.port');
            $dbName = config('database.connections.mysql.database');
            $dbUser = config('database.connections.mysql.username');
            $dbPass = config('database.connections.mysql.password');
            
            // Try multiple methods to find mysqldump
            $mysqldumpPaths = [
                trim(shell_exec('which mysqldump 2>/dev/null')),
                '/usr/bin/mysqldump',
                '/usr/local/bin/mysqldump',
                '/usr/local/mysql/bin/mysqldump',
                '/opt/homebrew/bin/mysqldump',  // Common on macOS with Homebrew
                'C:\xampp\mysql\bin\mysqldump.exe', // Windows with XAMPP
                'C:\wamp64\bin\mysql\mysql5.7.36\bin\mysqldump.exe', // Windows with WAMP
            ];
            
            $mysqldumpPath = null;
            foreach ($mysqldumpPaths as $testPath) {
                if (!empty($testPath) && file_exists($testPath)) {
                    $mysqldumpPath = $testPath;
                    break;
                }
            }
            
            if (empty($mysqldumpPath)) {
                // Try using PHP's PDO as a fallback
                return $this->createBackupWithPDO($filename);
            }
            
            // Use the found mysqldump path
            $command = sprintf(
                '%s --host=%s --port=%s --user=%s --password=%s --no-tablespaces --skip-lock-tables --single-transaction %s',
                escapeshellarg($mysqldumpPath),
                escapeshellarg($dbHost),
                escapeshellarg($dbPort),
                escapeshellarg($dbUser),
                escapeshellarg($dbPass),
                escapeshellarg($dbName)
            );
            
            // Execute the command and capture the output
            $process = Process::fromShellCommandline($command);
            $process->setTimeout(300); // 5 minutes timeout
            $process->run();
            
            if (!$process->isSuccessful()) {
                throw new \Exception('Database backup failed: ' . $process->getErrorOutput());
            }
            
            // Get the output and write it to the file
            $output = $process->getOutput();
            if (empty($output)) {
                throw new \Exception('Database backup generated empty output');
            }
            
            // Write the output to the file
            if (file_put_contents($path, $output) === false) {
                throw new \Exception('Failed to write backup file');
            }
            
            // Verify the backup file was created and has content
            if (!file_exists($path) || filesize($path) === 0) {
                throw new \Exception('Backup file was not created or is empty');
            }
            
            // Log the backup creation
            Log::info('Database backup created: ' . $filename . ' by user: ' . auth()->user()->name);
            
            return redirect()->route('settings.backup')
                ->with('success', 'Database backup created successfully.');
        } catch (\Exception $e) {
            Log::error('Backup creation failed: ' . $e->getMessage());
            
            return redirect()->route('settings.backup')
                ->with('error', 'Failed to create backup: ' . $e->getMessage() . '. Please ensure MySQL client tools are installed or contact your system administrator.');
        }
    }
    
    /**
     * Create a backup using PHP's PDO as a fallback when mysqldump is not available.
     * This method is less efficient for large databases but works without external tools.
     */
    private function createBackupWithPDO($filename)
    {
        try {
            $backupDir = storage_path('app/backups');
            $path = $backupDir . '/' . $filename;
            
            // Get database configuration
            $dbHost = config('database.connections.mysql.host');
            $dbPort = config('database.connections.mysql.port');
            $dbName = config('database.connections.mysql.database');
            $dbUser = config('database.connections.mysql.username');
            $dbPass = config('database.connections.mysql.password');
            
            // Connect to the database
            $dsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4";
            $pdo = new \PDO($dsn, $dbUser, $dbPass, [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
            
            // Start the SQL file with some metadata
            $output = "-- Police CCMS Database Backup\n";
            $output .= "-- Generated on: " . date('Y-m-d H:i:s') . "\n";
            $output .= "-- Database: {$dbName}\n\n";
            
            // Get all tables
            $tables = [];
            $stmt = $pdo->query('SHOW TABLES');
            while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
                $tables[] = $row[0];
            }
            
            // Process each table
            foreach ($tables as $table) {
                $output .= "\n-- Table structure for table `{$table}`\n";
                $output .= "DROP TABLE IF EXISTS `{$table}`;\n";
                
                // Get create table statement
                $stmt = $pdo->query("SHOW CREATE TABLE `{$table}`");
                $row = $stmt->fetch(\PDO::FETCH_NUM);
                $output .= $row[1] . ";\n\n";
                
                // Get table data
                $stmt = $pdo->query("SELECT * FROM `{$table}`");
                $columnCount = $stmt->columnCount();
                
                if ($stmt->rowCount() > 0) {
                    $output .= "-- Dumping data for table `{$table}`\n";
                    $output .= "INSERT INTO `{$table}` VALUES\n";
                    
                    $rowCount = 0;
                    while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
                        $output .= "(";
                        for ($i = 0; $i < $columnCount; $i++) {
                            if ($row[$i] === null) {
                                $output .= "NULL";
                            } else {
                                $output .= $pdo->quote($row[$i]);
                            }
                            if ($i < $columnCount - 1) {
                                $output .= ",";
                            }
                        }
                        $rowCount++;
                        if ($rowCount < $stmt->rowCount()) {
                            $output .= "),\n";
                        } else {
                            $output .= ");\n";
                        }
                    }
                }
            }
            
            // Write the output to the file
            if (file_put_contents($path, $output) === false) {
                throw new \Exception('Failed to write backup file');
            }
            
            // Log the backup creation
            Log::info('Database backup created using PDO fallback: ' . $filename . ' by user: ' . auth()->user()->name);
            
            return redirect()->route('settings.backup')
                ->with('success', 'Database backup created successfully using PHP fallback method (mysqldump not found).');
        } catch (\Exception $e) {
            Log::error('PDO backup creation failed: ' . $e->getMessage());
            
            return redirect()->route('settings.backup')
                ->with('error', 'Failed to create backup with PDO fallback: ' . $e->getMessage());
        }
    }
    
    /**
     * Download a backup file.
     */
    public function downloadBackup($filename)
    {
        $path = storage_path('app/backups/' . $filename);
        
        if (file_exists($path)) {
            // Log the backup download
            Log::info('Backup downloaded: ' . $filename . ' by user: ' . auth()->user()->name);
            
            return response()->download($path);
        }
        
        return redirect()->route('settings.backup')
            ->with('error', 'Backup file not found.');
    }
    
    /**
     * Restore from a backup file.
     */
    public function restoreBackup($filename)
    {
        try {
            $path = storage_path('app/backups/' . $filename);
            
            if (!file_exists($path)) {
                throw new \Exception('Backup file not found');
            }
            
            // Get database configuration
            $dbHost = config('database.connections.mysql.host');
            $dbPort = config('database.connections.mysql.port');
            $dbName = config('database.connections.mysql.database');
            $dbUser = config('database.connections.mysql.username');
            $dbPass = config('database.connections.mysql.password');
            
            // Try multiple methods to find mysql client
            $mysqlPaths = [
                trim(shell_exec('which mysql 2>/dev/null')),
                '/usr/bin/mysql',
                '/usr/local/bin/mysql',
                '/usr/local/mysql/bin/mysql',
                '/opt/homebrew/bin/mysql',  // Common on macOS with Homebrew
                'C:\\xampp\\mysql\\bin\\mysql.exe', // Windows with XAMPP
                'C:\\wamp64\\bin\\mysql\\mysql5.7.36\\bin\\mysql.exe', // Windows with WAMP
            ];
            
            $mysqlPath = null;
            foreach ($mysqlPaths as $testPath) {
                if (!empty($testPath) && file_exists($testPath)) {
                    $mysqlPath = $testPath;
                    break;
                }
            }
            
            if (empty($mysqlPath)) {
                throw new \Exception('MySQL client not found. Please ensure MySQL client tools are installed.');
            }
            
            // Create restore command
            $command = sprintf(
                '%s --host=%s --port=%s --user=%s --password=%s %s < %s',
                escapeshellarg($mysqlPath),
                escapeshellarg($dbHost),
                escapeshellarg($dbPort),
                escapeshellarg($dbUser),
                escapeshellarg($dbPass),
                escapeshellarg($dbName),
                escapeshellarg($path)
            );
            
            // Execute restore command using Process
            $process = Process::fromShellCommandline($command);
            $process->setTimeout(300); // 5 minutes timeout
            $process->run();
            
            if (!$process->isSuccessful()) {
                throw new \Exception('Database restore failed: ' . $process->getErrorOutput());
            }
            
            // Log the backup restoration
            Log::info('Database restored from backup: ' . $filename . ' by user: ' . auth()->user()->name);
            
            return redirect()->route('settings.backup')
                ->with('success', 'Database restored successfully from backup.');
        } catch (\Exception $e) {
            Log::error('Backup restoration failed: ' . $e->getMessage());
            
            return redirect()->route('settings.backup')
                ->with('error', 'Failed to restore from backup: ' . $e->getMessage());
        }
    }
    
    /**
     * Delete a backup file.
     */
    public function deleteBackup($filename)
    {
        $path = storage_path('app/backups/' . $filename);
        
        if (file_exists($path)) {
            unlink($path);
            
            // Log the backup deletion
            Log::info('Backup deleted: ' . $filename . ' by user: ' . auth()->user()->name);
            
            return redirect()->route('settings.backup')
                ->with('success', 'Backup deleted successfully.');
        }
        
        return redirect()->route('settings.backup')
            ->with('error', 'Backup file not found.');
    }
    
    /**
     * Update backup settings.
     */
    public function updateBackupSettings(Request $request)
    {
        $validated = $request->validate([
            'auto_backup_enabled' => 'boolean',
            'backup_frequency' => 'required|string|in:daily,weekly,monthly',
            'backup_retention_days' => 'required|integer|min:1|max:365',
            'backup_notification_email' => 'nullable|email',
        ]);
        
        // Save backup settings
        foreach ($validated as $key => $value) {
            Setting::setValue($key, $value, 'backup', gettype($value), 'Backup configuration setting');
        }
        
        // If auto backup is enabled, set up the task scheduler
        if ($validated['auto_backup_enabled']) {
            try {
                // This would normally set up a cron job or task scheduler
                // For now, we'll just log that it would be set up
                Log::info('Auto backup scheduled with frequency: ' . $validated['backup_frequency']);
            } catch (\Exception $e) {
                Log::error('Failed to schedule auto backup: ' . $e->getMessage());
            }
        }
        
        // Log the settings update
        Log::info('Backup settings updated by user: ' . auth()->user()->name);
        
        return redirect()->route('settings.backup')
            ->with('success', 'Backup settings updated successfully.');
    }
    
    /**
     * Display the logs page.
     */
    public function logs()
    {
        try {
            // Get list of log files
            $logFiles = Storage::disk('logs')->exists('/') ? Storage::disk('logs')->files() : [];
            
            // Get selected log file content
            $selectedLog = request('log', 'laravel.log');
            $logContent = '';
            
            if (!empty($logFiles) && Storage::disk('logs')->exists($selectedLog)) {
                // Get the last 1000 lines of the log file
                $logPath = storage_path('logs/' . $selectedLog);
                if (file_exists($logPath) && is_readable($logPath)) {
                    $logContent = array_slice(file($logPath), -1000);
                    $logContent = implode('', $logContent);
                }
            }
        } catch (\Exception $e) {
            // Handle any errors gracefully
            $logFiles = [];
            $selectedLog = 'laravel.log';
            $logContent = 'Error accessing log files: ' . $e->getMessage();
        }
        
        return view('settings.logs', compact('logFiles', 'selectedLog', 'logContent'));
    }
    
    /**
     * View a specific log file.
     */
    public function viewLog(Request $request)
    {
        try {
            $filename = $request->query('filename', 'laravel.log');
            $logContent = '';
            
            if (Storage::disk('logs')->exists($filename)) {
                $logPath = storage_path('logs/' . $filename);
                if (file_exists($logPath) && is_readable($logPath)) {
                    // Get the last 1000 lines of the log file
                    $logContent = array_slice(file($logPath), -1000);
                    $logContent = implode('', $logContent);
                } else {
                    $logContent = 'Log file exists but cannot be read. Check file permissions.';  
                }
            } else {
                $logContent = 'Log file not found: ' . $filename;
            }
        } catch (\Exception $e) {
            $logContent = 'Error accessing log file: ' . $e->getMessage();
            Log::error('Error viewing log file: ' . $e->getMessage());
        }
        
        return response()->json([
            'content' => $logContent
        ]);
    }
    
    /**
     * Clear a log file.
     *
     * @param string $filename
     * @return \Illuminate\Http\RedirectResponse
     */
    public function clearLog($filename)
    {
        try {
            // Validate filename to prevent directory traversal
            if (strpos($filename, '/') !== false || strpos($filename, '\\') !== false) {
                Log::warning('Attempted directory traversal in log clearing: ' . $filename . ' by user: ' . auth()->user()->name);
                return redirect()->route('settings.logs')
                    ->with('error', 'Invalid log filename.');
            }
            
            $logPath = storage_path('logs/' . $filename);
            
            // Check if file exists and is writable
            if (file_exists($logPath) && is_writable($logPath)) {
                // Clear the log file by writing an empty string to it
                file_put_contents($logPath, '');
                
                // Log the log clearing
                Log::info('Log file cleared: ' . $filename . ' by user: ' . auth()->user()->name);
                
                return redirect()->route('settings.logs')
                    ->with('success', 'Log file cleared successfully.');
            }
            
            return redirect()->route('settings.logs')
                ->with('error', 'Log file not found or not writable.');
        } catch (\Exception $e) {
            Log::error('Log clearing failed: ' . $e->getMessage());
            
            return redirect()->route('settings.logs')
                ->with('error', 'Failed to clear log file: ' . $e->getMessage());
        }
    }
    
    /**
     * Download a log file.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Illuminate\Http\RedirectResponse
     */
    public function downloadLog(Request $request)
    {
        try {
            $filename = $request->query('filename', 'laravel.log');
            
            // Validate filename to prevent directory traversal
            if (strpos($filename, '/') !== false || strpos($filename, '\\') !== false) {
                Log::warning('Attempted directory traversal in log download: ' . $filename . ' by user: ' . auth()->user()->name);
                return redirect()->route('settings.logs')
                    ->with('error', 'Invalid log filename.');
            }
            
            $logPath = storage_path('logs/' . $filename);
            
            // Check if file exists
            if (file_exists($logPath) && is_readable($logPath)) {
                // Log the download
                Log::info('Log file downloaded: ' . $filename . ' by user: ' . auth()->user()->name);
                
                // Return the file as a download
                return response()->download($logPath, $filename, [
                    'Content-Type' => 'text/plain',
                ]);
            }
            
            return redirect()->route('settings.logs')
                ->with('error', 'Log file not found or not readable.');
        } catch (\Exception $e) {
            Log::error('Log download failed: ' . $e->getMessage());
            
            return redirect()->route('settings.logs')
                ->with('error', 'Failed to download log file: ' . $e->getMessage());
        }
    }

    /**
     * Update log settings.
     */
    public function updateLogSettings(Request $request)
    {
        $validated = $request->validate([
            'log_level' => 'required|string|in:debug,info,notice,warning,error,critical,alert,emergency',
            'log_retention_days' => 'required|integer|min:1|max:365',
            'log_channel' => 'required|string|in:single,daily,slack,stderr,syslog,papertrail,stack',
        ]);
        
        // Save log settings
        foreach ($validated as $key => $value) {
            Setting::setValue($key, $value, 'logs', gettype($value), 'Log configuration setting');
        }
        
        // Update .env file for log level if possible
        try {
            $this->updateEnvFile('LOG_LEVEL', $validated['log_level']);
            $this->updateEnvFile('LOG_CHANNEL', $validated['log_channel']);
        } catch (\Exception $e) {
            Log::warning('Could not update .env file with log settings: ' . $e->getMessage());
        }
        
        // Log the settings update
        Log::info('Log settings updated by user: ' . auth()->user()->name);
        
        return redirect()->route('settings.logs')
            ->with('success', 'Log settings updated successfully.');
    }
    
    /**
     * Helper method to update .env file.
     */
    private function updateEnvFile($key, $value)
    {
        $path = base_path('.env');
        
        if (file_exists($path)) {
            $content = file_get_contents($path);
            
            // If the key exists, replace its value
            if (strpos($content, $key . '=') !== false) {
                $content = preg_replace('/^' . $key . '=.*$/m', $key . '=' . $value, $content);
            } else {
                // Otherwise, add the key-value pair
                $content .= "\n" . $key . '=' . $value;
            }
            
            file_put_contents($path, $content);
        }
    }
    
    /**
     * Display the roles and permissions page.
     */
    public function roles()
    {
        // Get all roles and permissions
        $roles = Role::with('permissions')->get();
        $permissions = Permission::all();
        
        return view('settings.roles', compact('roles', 'permissions'));
    }
    
    /**
     * Update an existing role.
     */
    public function updateRole(Request $request, $id)
    {
        $role = Role::findOrFail($id);
        
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:roles,name,' . $id,
            'rank_level' => 'nullable|integer|min:1|max:10',
            'description' => 'nullable|string|max:1000',
            'is_police_rank' => 'nullable|boolean',
            'can_supervise' => 'nullable|boolean',
            'jurisdiction_level' => 'nullable|in:station,district,regional,national',
            'permissions' => 'nullable|array',
            'permissions.*' => 'exists:permissions,id',
        ]);
        
        // Update basic role information
        $role->name = $validated['name'];
        
        // Update police rank-specific fields if they exist in the database schema
        if (Schema::hasColumn('roles', 'rank_level')) {
            $role->rank_level = $validated['rank_level'] ?? null;
        }
        
        if (Schema::hasColumn('roles', 'description')) {
            $role->description = $validated['description'] ?? null;
        }
        
        if (Schema::hasColumn('roles', 'is_police_rank')) {
            $role->is_police_rank = isset($validated['is_police_rank']) ? 1 : 0;
        }
        
        if (Schema::hasColumn('roles', 'can_supervise')) {
            $role->can_supervise = isset($validated['can_supervise']) ? 1 : 0;
        }
        
        if (Schema::hasColumn('roles', 'jurisdiction_level')) {
            $role->jurisdiction_level = $validated['jurisdiction_level'] ?? null;
        }
        
        $role->save();
        
        // Update permissions
        if (isset($validated['permissions'])) {
            $permissions = Permission::whereIn('id', $validated['permissions'])->get();
            $role->syncPermissions($permissions);
        } else {
            $role->syncPermissions([]);
        }
        
        // Log the role update
        Log::info('Role updated: ' . $role->name . ' by user: ' . auth()->user()->name);
        
        return redirect()->route('settings.roles')
            ->with('success', 'Role updated successfully.');
    }
    
    /**
     * Delete a role.
     */
    public function deleteRole($id)
    {
        $role = Role::findOrFail($id);
        
        // Check if role is being used
        $usersWithRole = User::role($role->name)->count();
        
        if ($usersWithRole > 0) {
            return redirect()->route('settings.roles')
                ->with('error', 'Cannot delete role. It is assigned to ' . $usersWithRole . ' users.');
        }
        
        // Log the role deletion
        Log::info('Role deleted: ' . $role->name . ' by user: ' . auth()->user()->name);
        
        $role->delete();
        
        return redirect()->route('settings.roles')
            ->with('success', 'Role deleted successfully.');
    }
    
    /**
     * Display the API settings page.
     */
    public function api()
    {
        // Get API settings
        $settings = Setting::where('group', 'api')->get();
        
        return view('settings.api', compact('settings'));
    }
    
    /**
     * Update API settings.
     */
    public function updateApi(Request $request)
    {
        $validated = $request->validate([
            'api_enabled' => 'boolean',
            'api_throttle_rate' => 'required|integer|min:10|max:1000',
            'api_token_expiry_days' => 'required|integer|min:1|max:365',
        ]);
        
        // Save API settings
        foreach ($validated as $key => $value) {
            Setting::setValue($key, $value, 'api', gettype($value));
        }
        
        // Log the API settings update
        Log::info('API settings updated by user: ' . auth()->user()->name);
        
        return redirect()->route('settings.api')
            ->with('success', 'API settings updated successfully.');
    }
    
    /**
     * Update API access control settings.
     */
    public function updateApiAccess(Request $request)
    {
        // Convert checkbox values to boolean
        $accessSettings = [
            'api_admin_access' => $request->has('api_admin_access') ? '1' : '0',
            'api_officer_access' => $request->has('api_officer_access') ? '1' : '0',
            'api_investigator_access' => $request->has('api_investigator_access') ? '1' : '0',
            'api_clerk_access' => $request->has('api_clerk_access') ? '1' : '0',
        ];
        
        // Save API access settings
        foreach ($accessSettings as $key => $value) {
            Setting::setValue($key, $value, 'api_access', 'boolean');
        }
        
        // Log the API access settings update
        Log::info('API access settings updated by user: ' . auth()->user()->name);
        
        return redirect()->route('settings.api')
            ->with('success', 'API access settings updated successfully.');
    }
    
    /**
     * Generate API documentation.
     */
    public function generateApiDocs()
    {
        try {
            // Generate API documentation using Laravel Scribe if installed
            if (class_exists('\Knuckles\Scribe\Commands\GenerateDocumentation')) {
                Artisan::call('scribe:generate');
                
                return redirect()->route('settings.api')
                    ->with('success', 'API documentation generated successfully.');
            }
            
            return redirect()->route('settings.api')
                ->with('error', 'API documentation generator not installed.');
        } catch (\Exception $e) {
            Log::error('API documentation generation failed: ' . $e->getMessage());
            
            return redirect()->route('settings.api')
                ->with('error', 'Failed to generate API documentation: ' . $e->getMessage());
        }
    }
}
