<?php

namespace App\Http\Controllers\Settings;

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

class SystemUpdateController extends Controller
{
    public function index()
    {
        $vFile = storage_path('app/version.txt');
        $currentVersion = File::exists($vFile) ? File::get($vFile) : '1.0.0';

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

        $updates = File::files($updatesDir);
        $updateFiles = collect($updates)->sortByDesc(fn($f) => $f->getMTime());

        return view('settings.system.updates.index', compact('currentVersion', 'updateFiles'));
    }

    public function upload(Request $request)
    {
        $request->validate([
            'update_file' => 'required|file|mimes:zip,php',
        ]);

        $path = $request->file('update_file')->storeAs('updates', $request->file('update_file')->getClientOriginalName());

        return back()->with('success', 'Update file uploaded successfully to: ' . $path);
    }

    public function run(Request $request)
    {
        $filename = $request->filename;
        $path = storage_path('app/updates/' . $filename);

        if (!File::exists($path)) {
            return back()->with('error', 'Update file not found.');
        }

        try {
            // If it's a PHP file, include it
            if (File::extension($path) == 'php') {
                include $path;
            }
            // If it's a ZIP, we might need a more complex extractor, but for now let's stick to script execution

            // Run migrations just in case
            Artisan::call('migrate', ['--force' => true]);

            return back()->with('success', 'Update "' . $filename . '" executed successfully.');
        } catch (\Exception $e) {
            return back()->with('error', 'Update failed: ' . $e->getMessage());
        }
    }
}
