<?php

namespace App\Http\Controllers\Admin;

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

class PluginController extends Controller
{
    protected PluginManager $pluginManager;

    public function __construct(PluginManager $pluginManager)
    {
        $this->pluginManager = $pluginManager;
    }

    /**
     * Display plugins list
     */
    public function index()
    {
        $plugins = Plugin::ordered()->get();

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

    /**
     * Upload and install plugin
     */
    public function upload(Request $request)
    {
        $request->validate([
            'plugin_file' => 'required|file|mimes:zip|max:51200', // Max 50MB
        ]);

        $result = $this->pluginManager->install($request->file('plugin_file'));

        if ($result['success']) {
            return redirect()->route('admin.plugins.index')
                ->with('success', $result['message']);
        }

        return back()->with('error', $result['message']);
    }

    /**
     * Activate plugin
     */
    public function activate(Plugin $plugin)
    {
        $result = $this->pluginManager->activate($plugin);

        return response()->json($result);
    }

    /**
     * Deactivate plugin
     */
    public function deactivate(Plugin $plugin)
    {
        $result = $this->pluginManager->deactivate($plugin);

        return response()->json($result);
    }

    /**
     * Delete plugin
     */
    public function destroy(Plugin $plugin)
    {
        $result = $this->pluginManager->delete($plugin);

        if ($result['success']) {
            return redirect()->route('admin.plugins.index')
                ->with('success', $result['message']);
        }

        return back()->with('error', $result['message']);
    }

    /**
     * Toggle plugin status (AJAX)
     */
    public function toggle(Plugin $plugin)
    {
        if ($plugin->is_active) {
            $result = $this->pluginManager->deactivate($plugin);
        } else {
            $result = $this->pluginManager->activate($plugin);
        }

        return response()->json($result);
    }
}
