<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Configuration;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\Middleware;

class ConfigurationController extends Controller
{
    public static function middleware(): array
    {
        return [
            'auth',
            // new Middleware('permission:config-list|config-create|config-edit|config-delete', ['only' => ['index','show']]),
            // new Middleware('permission:config-create', ['only' => ['create','store']]),
            // new Middleware('permission:config-edit', ['only' => ['edit','update']]),
            // new Middleware('permission:config-delete', ['only' => ['destroy']]),
        ];
    }

    

    /**
     * Affiche la liste des configurations
     */
    public function index(Request $request)
    {
        $configurations = Configuration::query()
            ->when($request->search, function($query, $search) {
                $query->where('key', 'like', "%{$search}%")
                      ->orWhere('description', 'like', "%{$search}%");
            })
            ->when($request->group, function($query, $group) {
                $query->where('group', $group);
            })
            ->when($request->type, function($query, $type) {
                $query->where('type', $type);
            })
            ->orderBy('group')
            ->orderBy('key')
            ->paginate(15);

        $groups = Configuration::distinct()->pluck('group')->sort();
        $types = ['string', 'boolean', 'integer', 'json'];
        
        return view('admin.configurations.index', compact('configurations', 'groups', 'types'));
    }

    /**
     * Affiche le formulaire de création
     */
    public function create()
    {
        $groups = Configuration::distinct()->pluck('group')->sort();
        $types = ['string', 'boolean', 'integer', 'json'];
        
        return view('admin.configurations.create', compact('groups', 'types'));
    }

    /**
     * Stocke une nouvelle configuration
     */
    public function store(Request $request)
    {
        $request->validate([
            'key' => 'required|string|max:255|unique:configurations,key',
            'value' => 'required',
            'type' => 'required|in:string,boolean,integer,json',
            'description' => 'nullable|string',
            'group' => 'required|string|max:255',
            'is_public' => 'boolean'
        ]);

        if ($request->type === 'json') {
            json_decode($request->value);
            if (json_last_error() !== JSON_ERROR_NONE) {
                session()->flash('error', 'La valeur JSON n\'est pas valide.');
                return redirect()->back()->withInput();
                // ->withErrors(['value' => 'La valeur JSON n\'est pas valide.'])->withInput();
            }
        } elseif ($request->type === 'integer') {
            if (!is_numeric($request->value)) {
                session()->flash('error', 'La valeur doit être un nombre entier.');
                return redirect()->back()->withInput();
            }
        } elseif ($request->type === 'boolean') {
            $request->merge(['value' => $request->has('value') ? '1' : '0']);
        }

        Configuration::create([
            'key' => $request->key,
            'value' => $request->value,
            'type' => $request->type,
            'description' => $request->description,
            'group' => $request->group,
            'is_public' => $request->has('is_public')
        ]);

        session()->flash('success', 'Configuration créée avec succès.');
        return redirect()->route('configurations.index');
    }

    /**
     * Affiche une configuration spécifique
     */
    public function show(Configuration $configuration)
    {
        return view('admin.configurations.show', compact('configuration'));
    }

    /**
     * Affiche le formulaire d'édition
     */
    public function edit(Configuration $configuration)
    {
        $groups = Configuration::distinct()->pluck('group')->sort();
        $types = ['string', 'boolean', 'integer', 'json'];
        
        return view('admin.configurations.edit', compact('configuration', 'groups', 'types'));
    }

    /**
     * Met à jour une configuration
     */
    public function update(Request $request, Configuration $configuration)
    {
        $request->validate([
            'key' => 'required|string|max:255|unique:configurations,key,' . $configuration->id,
            'value' => 'required',
            'type' => 'required|in:string,boolean,integer,json',
            'description' => 'nullable|string',
            'group' => 'required|string|max:255',
            'is_public' => 'boolean'
        ]);

        if ($request->type === 'json') {
            json_decode($request->value);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return redirect()->back()->withErrors(['value' => 'La valeur JSON n\'est pas valide.'])->withInput();
            }
        } elseif ($request->type === 'integer') {
            if (!is_numeric($request->value)) {
                return redirect()->back()->withErrors(['value' => 'La valeur doit être un nombre entier.'])->withInput();
            }
        } elseif ($request->type === 'boolean') {
            $request->merge(['value' => $request->has('value') ? '1' : '0']);
        }

        $configuration->update([
            'key' => $request->key,
            'value' => $request->value,
            'type' => $request->type,
            'description' => $request->description,
            'group' => $request->group,
            'is_public' => $request->has('is_public')
        ]);

        return redirect()->route('configurations.index')
                        ->with('success', 'Configuration mise à jour avec succès.');
    }

    /**
     * Supprime une configuration
     */
    public function destroy(Configuration $configuration)
    {
        $configuration->delete();

        return redirect()->route('configurations.index')
                        ->with('success', 'Configuration supprimée avec succès.');
    }

    /**
     * API pour récupérer les configurations publiques
     */
    public function public()
    {
        return response()->json(Configuration::getPublic());
    }

    /**
     * API pour récupérer les configurations d'un groupe
     */
    public function group($group)
    {
        return response()->json(Configuration::getGroup($group));
    }
}
