<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Plugin;
use App\Services\PluginManager;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PluginController extends Controller
{
    public function __construct(private readonly PluginManager $plugins)
    {
        $this->middleware('can:plugin.manage');
    }

    public function index(): View
    {
        $this->plugins->sync();
        return view('admin.plugins.index', ['plugins' => $this->plugins->plugins()]);
    }

    public function install(Request $request): RedirectResponse
    {
        $request->validate(['plugin' => ['required', 'file', 'mimes:zip', 'max:'.config('plugins.max_upload_kilobytes')]]);
        try {
            $plugin = $this->plugins->install($request->file('plugin'));
            return back()->with('success', "{$plugin->name} installed and enabled.");
        } catch (\Throwable $exception) {
            report($exception);
            return back()->with('error', $exception->getMessage());
        }
    }

    public function toggle(Plugin $plugin): RedirectResponse
    {
        try {
            $this->plugins->setEnabled($plugin, ! $plugin->is_enabled);
            return back()->with('success', "{$plugin->name} has been ".($plugin->is_enabled ? 'enabled' : 'disabled').'.');
        } catch (\Throwable $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }
}
