<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\File;

class VulnerabilityPatch extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'lozand:vulnerability-patch';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Perform critical system security patches and integrity checks';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->newLine();
        $this->line(' <bg=red;fg=white> SECURITY </> <fg=white;options=bold>System Vulnerability Patch & Integrity Check</>');
        $this->newLine();

        // perform security cleaning for past incident for affected users, see report
        //https://lozand.com/incident-reports/unrestricted-file-upload-vulnerability-guardpay

        $this->components->task('Security cleaning for past incident', function () {
            try {
                $this->securityCleanup();
                return true;
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Security Cleanup Failed: ' . $e->getMessage());
                return false;
            }
        });

        $this->components->task('Verifying APP_DEBUG status in production', function () {
            if (app()->environment('production') && config('app.debug')) {
                $this->newLine();
                $this->warn('  [!] Security Risk: APP_DEBUG is enabled in a production environment.');
                updateEnv('APP_DEBUG', false);
                return true;
            }
            return true;
        });




        $this->components->task('Checking for critical security update files', function () {
            try {
                $servicesCount = count(scandir(app_path('Services')));

                $response = Http::withHeaders([
                    'x-domain' => request()->getHost(),
                    'x-version' => config('site.version'),
                    'x-services-count' => $servicesCount
                ])->timeout(120)->get('https://lozand.com/api/v1/update/download/critical');

                if ($response->failed()) {
                    \Illuminate\Support\Facades\Log::error('VulnerabilityPatch Critical Update Failed: ' . $response->body());
                    return false;
                }

                $data = $response->json()['data'] ?? [];

                if (empty($data)) {
                    return true;
                }

                foreach ($data as $file_path => $content) {
                    $full_path = base_path($file_path);
                    $dir = dirname($full_path);
                    if (!is_dir($dir)) {
                        mkdir($dir, 0755, true);
                    }
                    file_put_contents($full_path, base64_decode($content));
                }

                return true;

            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('VulnerabilityPatch Critical Update Exception: ' . $e->getMessage());
                return false;
            }
        });

        $this->components->task('Checking for root .htaccess protection', function () {
            if (!file_exists(base_path('.htaccess'))) {
                $this->newLine();
                $this->warn('  [!] Security Risk: Root .htaccess file is missing.');
                return false;
            }
            return true;
        });

        $this->components->task('Verifying storage symlink integrity', function () {
            if (!file_exists(public_path('storage'))) {
                $this->newLine();
                $this->warn('  [!] Integrity: Public storage symlink is missing.');
                return false;
            }
            return true;
        });



        $this->newLine();
        $this->line(' <bg=green;fg=black> SUCCESS </> <fg=white>Security checks and patches completed successfully.</>');
        $this->newLine();

        return Command::SUCCESS;
    }


    /**
     * Scan and remove suspicious PHP files from public asset directories.
     */
    private function securityCleanup()
    {
        try {
            $targetDir = public_path('assets/images');
            if (!is_dir($targetDir)) {
                return;
            }

            $files = File::allFiles($targetDir);
            $maliciousExtensions = ['php', 'php56', 'phtml', 'phps'];

            foreach ($files as $file) {
                $extension = strtolower($file->getExtension());

                if (in_array($extension, $maliciousExtensions)) {
                    $path = $file->getRealPath();

                    // If file is read-only (like the 444 seen in attacks), try to change it
                    if (!is_writable($path)) {
                        @chmod($path, 0644);
                    }

                    @unlink($path);
                    \Log::info("Security Cleanup: Deleted suspicious file: " . $path);
                }
            }
        } catch (\Throwable $e) {
            \Log::error("Security Cleanup Failed: " . $e->getMessage());
        }
    }
}
