<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class BackupCommand extends Command
{
    protected $signature = 'erp:backup {--keep=14 : Number of recent backups to retain}';
    protected $description = 'Scheduled mysqldump into storage/app/backups with retention pruning';

    public function handle(): int
    {
        $bin = trim((string) shell_exec('command -v mysqldump || command -v mariadb-dump'));
        if ($bin === '') {
            $this->error('mysqldump not found on server.');
            return self::FAILURE;
        }
        $c = config('database.connections.mysql');
        $fn = 'backups/nowills_sqc_erp_' . date('Ymd_His') . '.sql';
        Storage::disk('local')->makeDirectory('backups');
        $path = Storage::disk('local')->path($fn);
        $cmd = sprintf('%s --host=%s --port=%s --user=%s --password=%s %s > %s 2>/dev/null',
            escapeshellarg($bin), escapeshellarg($c['host']), escapeshellarg($c['port']),
            escapeshellarg($c['username']), escapeshellarg($c['password']), escapeshellarg($c['database']), escapeshellarg($path));
        exec($cmd, $o, $code);
        if ($code !== 0 || !is_file($path) || filesize($path) < 1000) {
            @unlink($path);
            $this->error('Backup dump failed.');
            return self::FAILURE;
        }
        $files = collect(Storage::disk('local')->files('backups'))
            ->filter(fn($f) => str_ends_with($f, '.sql'))->sort()->values();
        $keep = max(1, (int) $this->option('keep'));
        foreach ($files->slice(0, max(0, $files->count() - $keep)) as $old) {
            Storage::disk('local')->delete($old);
        }
        $this->info('Backup written: ' . $fn . ' (' . number_format(filesize($path)) . ' bytes).');
        return self::SUCCESS;
    }
}
