<?php namespace App\Services; use App\Models\BackupRun; use Illuminate\Support\Facades\Storage; use RuntimeException; class BackupService {public function run():BackupRun{$name='softsuite-backup-'.now()->format('Ymd-His').'.sql.gz';$run=BackupRun::create(['filename'=>$name,'status'=>'started']);try{$cfg=config('database.connections.'.config('database.default'));if(($cfg['driver']??null)!=='mysql')throw new RuntimeException('Automated DB backup currently supports MySQL.');$pass=escapeshellarg((string)($cfg['password']??''));$cmd='MYSQL_PWD='.$pass.' mysqldump --single-transaction --skip-lock-tables -h '.escapeshellarg($cfg['host']).' -P '.escapeshellarg((string)$cfg['port']).' -u '.escapeshellarg($cfg['username']).' '.escapeshellarg($cfg['database']).' | gzip';$out=shell_exec($cmd);if(!$out)throw new RuntimeException('mysqldump produced no output.');Storage::disk('local')->put('backups/'.$name,$out);$path=Storage::disk('local')->path('backups/'.$name);$run->update(['status'=>'completed','size_bytes'=>filesize($path),'checksum'=>hash_file('sha256',$path),'completed_at'=>now()]);}catch(\Throwable $e){$run->update(['status'=>'failed','error'=>$e->getMessage(),'completed_at'=>now()]);throw $e;}return $run;}}