<?php

namespace AleshaCMS\Http\Controllers\Admin;

use AleshaCMS\Http\Controllers\Controller;
use AleshaCMS\CMS\Plugin\PluginManager;
use Illuminate\Http\Request;

class PluginController extends Controller
{
    public function __construct(protected PluginManager $plugins) {}

    public function index(Request $request)
    {
        $plugins = $this->plugins->getAvailable();

        if ($request->wantsJson()) {
            return response()->json(['data' => $plugins]);
        }

        return view('admin.plugins.index', compact('plugins'));
    }

    public function toggle(Request $request)
    {
        $request->validate([
            'slug'   => ['required', 'string', 'regex:/^[A-Za-z0-9_-]+$/'],
            'active' => 'required|boolean',
        ]);

        if ($request->active) {
            $this->plugins->activate($request->slug);
        } else {
            $this->plugins->deactivate($request->slug);
        }

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'message' => 'Plugin updated.']);
        }

        return back()->with('success', 'Plugin updated.');
    }
}
