<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Artisan;
use Carbon\Carbon;

class BackupController extends Controller
{
    public function index()
    {
        $disk = Storage::disk('local');
        $backupName = config('backup.backup.name');
        $files = $disk->files($backupName);
        
        $backups = [];
        foreach ($files as $f) {
            if (substr($f, -4) == '.zip' && $disk->exists($f)) {
                $backups[] = [
                    'file_path' => $f,
                    'file_name' => str_replace($backupName . '/', '', $f),
                    'file_size' => $this->humanFileSize($disk->size($f)),
                    'last_modified' => Carbon::createFromTimestamp($disk->lastModified($f)),
                ];
            }
        }
        
        // Reverse order (newest first)
        $backups = array_reverse($backups);

        return view('admin.security.backups', compact('backups'));
    }

    public function store()
    {
        try {
            // Using only-db for speed in this context, but normally full backup
            Artisan::call('backup:run --only-db'); 
            return redirect()->back()->with('success', 'Database backup created successfully.');
        } catch (\Exception $e) {
            return redirect()->back()->withErrors(['error' => 'Backup failed: ' . $e->getMessage()]);
        }
    }

    public function destroy($fileName)
    {
        $disk = Storage::disk('local');
        $backupName = config('backup.backup.name');
        $filePath = $backupName . '/' . $fileName;
        
        if ($disk->exists($filePath)) {
            $disk->delete($filePath);
            return redirect()->back()->with('success', 'Backup deleted successfully.');
        }
        
        return redirect()->back()->withErrors(['error' => 'Backup not found.']);
    }

    public function download($fileName)
    {
        $disk = Storage::disk('local');
        $backupName = config('backup.backup.name');
        $filePath = $backupName . '/' . $fileName;
        
        if ($disk->exists($filePath)) {
            return $disk->download($filePath);
        }
        
        return redirect()->back()->withErrors(['error' => 'Backup file does not exist.']);
    }

    private function humanFileSize($size, $unit = "")
    {
        if ((!$unit && $size >= 1 << 30) || $unit == "GB")
            return number_format($size / (1 << 30), 2) . "GB";
        if ((!$unit && $size >= 1 << 20) || $unit == "MB")
            return number_format($size / (1 << 20), 2) . "MB";
        if ((!$unit && $size >= 1 << 10) || $unit == "KB")
            return number_format($size / (1 << 10), 2) . "KB";
        return number_format($size) . " bytes";
    }
}
