<?php

namespace App\Http\Controllers\Admin;

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

class SiteSettingController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $settings = SiteSetting::orderBy('group')->orderBy('sort_order')->get();
        return view('admin.site-settings.index', compact('settings'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.site-settings.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'key' => 'required|string|unique:site_settings,key',
            'value' => 'nullable|string',
            'type' => 'required|in:text,textarea,image,boolean',
            'group' => 'required|string',
            'sort_order' => 'nullable|integer',
        ]);

        SiteSetting::create($request->all());

        return redirect()->route('admin.site-settings.index')
                        ->with('success', 'Site setting created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(SiteSetting $siteSetting)
    {
        return view('admin.site-settings.show', compact('siteSetting'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(SiteSetting $siteSetting)
    {
        return view('admin.site-settings.edit', compact('siteSetting'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, SiteSetting $siteSetting)
    {
        $request->validate([
            'key' => 'required|string|unique:site_settings,key,' . $siteSetting->id,
            'value' => 'nullable|string',
            'type' => 'required|in:text,textarea,image,boolean',
            'group' => 'required|string',
            'sort_order' => 'nullable|integer',
        ]);

        $siteSetting->update($request->all());

        return redirect()->route('admin.site-settings.index')
                        ->with('success', 'Site setting updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(SiteSetting $siteSetting)
    {
        $siteSetting->delete();

        return redirect()->route('admin.site-settings.index')
                        ->with('success', 'Site setting deleted successfully.');
    }
}
