<?php

namespace App\Http\Controllers\Admin;

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

class ModuleController extends Controller
{
    public function index()
    {
        $groups = Module::getGroupedModules();
        return view('admin.modules.index', compact('groups'));
    }

    public function install($code)
    {
        $info = Module::getModuleInfo($code);
        if (!$info) {
            return redirect()->route('admin.modules.index')
                ->with('error', "Module '{$code}' not found.");
        }

        Module::updateOrCreate(
            ['code' => $code],
            [
                'name' => $info['name'],
                'group' => $info['group'],
                'is_installed' => true,
                'is_active' => true,
            ]
        );

        return redirect()->route('admin.modules.index')
            ->with('success', "Module '{$info['name']}' installed.");
    }

    public function uninstall($code)
    {
        $module = Module::where('code', $code)->first();
        if (!$module) {
            return redirect()->route('admin.modules.index')
                ->with('error', 'Module not found.');
        }

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

        return redirect()->route('admin.modules.index')
            ->with('success', "Module '{$module->name}' uninstalled.");
    }

    public function toggle($code)
    {
        $module = Module::where('code', $code)->first();
        if (!$module) {
            return redirect()->route('admin.modules.index')
                ->with('error', 'Module not found.');
        }

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

        $status = $module->is_active ? 'activated' : 'deactivated';
        return redirect()->route('admin.modules.index')
            ->with('success', "Module '{$module->name}' {$status}.");
    }

    public function refresh()
    {
        Module::truncate();
        $this->seed();

        return redirect()->route('admin.modules.index')
            ->with('success', 'All modules refreshed from configuration.');
    }

    protected function seed()
    {
        $order = 0;
        foreach (config('modules', []) as $group => $groupConfig) {
            foreach ($groupConfig['modules'] ?? [] as $modCode => $modConfig) {
                Module::create([
                    'code' => $modCode,
                    'name' => $modConfig['name'],
                    'group' => $group,
                    'is_installed' => true,
                    'is_active' => true,
                    'order' => $order++,
                ]);
            }
        }
    }
}
