<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Module;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ModuleController extends Controller
{
    /**
     * Display all modules
     */
    public function index()
    {
        $modules = Module::ordered()->get();
        
        return view('admin.modules.index', compact('modules'));
    }

    /**
     * Update module details
     */
    public function update(Request $request, Module $module)
    {
        $validated = $request->validate([
            'label' => 'required|string|max:100',
            'icon' => 'nullable|string|max:50',
            'description' => 'nullable|string',
            'route_name' => 'nullable|string|max:100',
            'url_path' => 'nullable|string|max:200',
            'sort_order' => 'required|integer|min:0',
        ]);

        $module->update($validated);

        // Clear cache
        $this->clearCache();

        return back()->with('success', 'Modül başarıyla güncellendi.');
    }

    /**
     * Toggle module active status
     */
    public function toggleActive(Module $module)
    {
        $module->update([
            'is_active' => !$module->is_active,
        ]);

        // Clear cache
        $this->clearCache();

        return response()->json([
            'success' => true,
            'is_active' => $module->is_active,
            'message' => $module->is_active ? 'Modül aktif edildi.' : 'Modül pasif edildi.',
        ]);
    }

    /**
     * Toggle module maintenance mode
     */
    public function toggleMaintenance(Module $module)
    {
        $module->update([
            'is_maintenance' => !$module->is_maintenance,
        ]);

        // Clear cache
        $this->clearCache();

        return response()->json([
            'success' => true,
            'is_maintenance' => $module->is_maintenance,
            'message' => $module->is_maintenance ? 'Bakım modu aktif.' : 'Bakım modu pasif.',
        ]);
    }

    /**
     * Update sort order
     */
    public function updateSortOrder(Request $request, Module $module)
    {
        $validated = $request->validate([
            'sort_order' => 'required|integer|min:0',
        ]);

        $module->update(['sort_order' => $validated['sort_order']]);

        // Clear cache
        $this->clearCache();

        return response()->json([
            'success' => true,
            'message' => 'Sıra güncellendi.',
        ]);
    }

    /**
     * Clear application cache
     */
    protected function clearCache()
    {
        Cache::flush();
    }
}
