<?php

namespace App\Livewire\Settings;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithFileUploads;

class BackupSettings extends Component
{
    use WithFileUploads;

    public $restoreFile;
    public array $backups = [];

    public function mount()
    {
        $this->loadBackups();
    }

    public function loadBackups()
    {
        $backupPath = storage_path('app/backups');
        
        if (!File::exists($backupPath)) {
            File::makeDirectory($backupPath, 0755, true);
        }

        $files = File::files($backupPath);
        $this->backups = collect($files)
            ->map(function ($file) {
                return [
                    'name' => $file->getFilename(),
                    'size' => round($file->getSize() / 1024, 2) . ' KB',
                    'date' => date('Y-m-d H:i:s', $file->getMTime()),
                    'path' => $file->getPathname(),
                ];
            })
            ->sortByDesc('date')
            ->values()
            ->toArray();
    }

    public function createBackup()
    {
        try {
            $dbPath = database_path('database.sqlite');
            
            if (!File::exists($dbPath)) {
                session()->flash('error', __('Database file not found.'));
                return;
            }

            $backupPath = storage_path('app/backups');
            if (!File::exists($backupPath)) {
                File::makeDirectory($backupPath, 0755, true);
            }

            $filename = 'backup_' . date('Y-m-d_His') . '.sqlite';
            File::copy($dbPath, $backupPath . '/' . $filename);

            $this->loadBackups();
            session()->flash('success', __('Backup created successfully: ') . $filename);

        } catch (\Exception $e) {
            session()->flash('error', __('Backup failed: ') . $e->getMessage());
        }
    }

    public function downloadBackup(string $filename)
    {
        $path = storage_path('app/backups/' . $filename);
        
        if (File::exists($path)) {
            return response()->download($path);
        }
        
        session()->flash('error', __('Backup file not found.'));
    }

    public function restoreBackup(string $filename)
    {
        try {
            $backupPath = storage_path('app/backups/' . $filename);
            $dbPath = database_path('database.sqlite');

            if (!File::exists($backupPath)) {
                session()->flash('error', __('Backup file not found.'));
                return;
            }

            // Create a backup of current database before restore
            $currentBackup = storage_path('app/backups/pre_restore_' . date('Y-m-d_His') . '.sqlite');
            File::copy($dbPath, $currentBackup);

            // Restore the backup
            File::copy($backupPath, $dbPath);

            $this->loadBackups();
            session()->flash('success', __('Database restored successfully.'));

        } catch (\Exception $e) {
            session()->flash('error', __('Restore failed: ') . $e->getMessage());
        }
    }

    public function deleteBackup(string $filename)
    {
        try {
            $path = storage_path('app/backups/' . $filename);
            
            if (File::exists($path)) {
                File::delete($path);
                $this->loadBackups();
                session()->flash('success', __('Backup deleted.'));
            }

        } catch (\Exception $e) {
            session()->flash('error', __('Delete failed: ') . $e->getMessage());
        }
    }

    public function clearCache()
    {
        try {
            Artisan::call('cache:clear');
            Artisan::call('config:clear');
            Artisan::call('view:clear');
            Artisan::call('route:clear');
            
            session()->flash('success', __('All caches cleared successfully.'));

        } catch (\Exception $e) {
            session()->flash('error', __('Failed to clear cache: ') . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.settings.backup');
    }
}
