<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GooglePlugin;
use Illuminate\Http\Request;

class GooglePluginController extends Controller
{
    public function index()
    {
        $plugins = GooglePlugin::orderBy('order')->get();
        return view('admin.google-plugins.index', compact('plugins'));
    }

    public function install($code)
    {
        $pluginConfig = config("google_plugins.{$code}");
        if (!$pluginConfig || !class_exists($pluginConfig['class'])) {
            return redirect()->route('admin.google-plugins.index')
                ->with('error', "Google plugin '{$code}' not found.");
        }

        $existing = GooglePlugin::where('code', $code)->first();
        if ($existing) {
            $existing->update(['is_installed' => true]);
            return redirect()->route('admin.google-plugins.index')
                ->with('success', "Plugin '{$pluginConfig['name']}' installed.");
        }

        $plugin = app($pluginConfig['class']);

        GooglePlugin::create([
            'code' => $code,
            'name' => $pluginConfig['name'],
            'description' => $pluginConfig['description'],
            'version' => $plugin->getVersion(),
            'author' => $plugin->getAuthor(),
            'is_active' => false,
            'is_installed' => true,
            'config' => [],
            'order' => GooglePlugin::max('order') + 1,
        ]);

        return redirect()->route('admin.google-plugins.index')
            ->with('success', "Plugin '{$pluginConfig['name']}' installed successfully.");
    }

    public function uninstall($code)
    {
        $plugin = GooglePlugin::where('code', $code)->first();
        if (!$plugin) {
            return redirect()->route('admin.google-plugins.index')
                ->with('error', 'Plugin not found.');
        }

        $plugin->update(['is_installed' => false, 'is_active' => false]);

        return redirect()->route('admin.google-plugins.index')
            ->with('success', "Plugin '{$plugin->name}' uninstalled.");
    }

    public function edit(GooglePlugin $googlePlugin)
    {
        $resolved = $googlePlugin->resolvePlugin();
        $fields = $resolved ? $resolved->getConfigFields() : [];

        return view('admin.google-plugins.edit', compact('googlePlugin', 'fields'));
    }

    public function update(Request $request, GooglePlugin $googlePlugin)
    {
        $resolved = $googlePlugin->resolvePlugin();
        if (!$resolved) {
            return redirect()->route('admin.google-plugins.index')
                ->with('error', 'Google plugin class not found.');
        }

        $validated = $resolved->validateConfig($request->input('config', []));

        $googlePlugin->update([
            'config' => $validated,
            'is_active' => $request->boolean('is_active', false),
        ]);

        return redirect()->route('admin.google-plugins.index')
            ->with('success', "Plugin '{$googlePlugin->name}' configured.");
    }

    public function toggle(GooglePlugin $googlePlugin)
    {
        $resolved = $googlePlugin->resolvePlugin();
        if ($resolved && !$resolved->isConfigured($googlePlugin)) {
            return redirect()->route('admin.google-plugins.edit', $googlePlugin)
                ->with('error', 'Configure the plugin before activating.');
        }

        $googlePlugin->update(['is_active' => !$googlePlugin->is_active]);

        $status = $googlePlugin->is_active ? 'activated' : 'deactivated';
        return redirect()->route('admin.google-plugins.index')
            ->with('success', "Plugin '{$googlePlugin->name}' {$status}.");
    }
}
