<?php

namespace App\Http\Controllers;

use App\Models\Backup;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Symfony\Component\Process\Process;

class BackupController extends Controller
{
    public function index() { $backups = Backup::with('createdBy')->latest()->paginate(30); return view('settings.backups', compact('backups')); }

    public function store()
    {
        $directory = storage_path('app/private/backups'); File::ensureDirectoryExists($directory);
        $base = 'mutlaq_erp_'.now()->format('Ymd_His');
        try {
            if (config('database.default') === 'sqlite') {
                $source = config('database.connections.sqlite.database'); $filename = $base.'.sqlite'; $target = $directory.DIRECTORY_SEPARATOR.$filename;
                if (!is_file($source) || !copy($source, $target)) throw new \RuntimeException('Unable to copy the SQLite database.');
            } else {
                $connection = config('database.connections.'.config('database.default')); $filename = $base.'.sql'; $target = $directory.DIRECTORY_SEPARATOR.$filename;
                $binary = is_file('C:\\xampp\\mysql\\bin\\mysqldump.exe') ? 'C:\\xampp\\mysql\\bin\\mysqldump.exe' : 'mysqldump';
                $process = new Process([$binary, '--host='.$connection['host'], '--port='.(string) $connection['port'], '--user='.$connection['username'], '--single-transaction', '--routines', '--events', '--result-file='.$target, $connection['database']], null, ['MYSQL_PWD' => (string) $connection['password']]);
                $process->setTimeout(300); $process->mustRun();
            }
            $backup = Backup::create(['filename' => $filename, 'size' => filesize($target), 'status' => 'completed', 'checksum' => hash_file('sha256', $target), 'created_by' => Auth::id()]);
            \App\Services\AuditLogService::log('BACKUP_CREATED', 'backups', $backup->id, null, ['filename' => $filename]);
            return back()->with('success', 'Database backup created successfully.');
        } catch (\Throwable $e) { report($e); return back()->with('error', 'Backup could not be created. Check database backup permissions and try again.'); }
    }

    public function download(Backup $backup)
    {
        $path = storage_path('app/private/backups'.DIRECTORY_SEPARATOR.basename($backup->filename)); abort_unless(is_file($path), 404);
        return response()->download($path, $backup->filename);
    }
}
