<?php

/* Titan © TakfeDev (MKJUEL). All Rights. */

namespace App\Http\Controllers\Api\Admin;

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

class PostSettingsController extends Controller
{
    public function index(): JsonResponse
    {
        $settings = Setting::where('group', 'post')
            ->pluck('value', 'key')
            ->toArray();

        return response()->json([
            'submission_enabled'    => $settings['submission_enabled'] ?? 'true',
            'auto_approval'         => $settings['auto_approval'] ?? 'false',
            'enable_inline_related' => $settings['enable_inline_related'] ?? 'true',
            'comments_enabled'      => $settings['comments_enabled'] ?? 'true',
            'quick_fetch_enabled'   => $settings['quick_fetch_enabled'] ?? 'true',
            'show_right_sidebar'    => $settings['show_right_sidebar'] ?? 'true',
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        $request->validate([
            'submission_enabled'    => 'required|in:true,false',
            'auto_approval'         => 'required|in:true,false',
            'enable_inline_related' => 'required|in:true,false',
            'comments_enabled'      => 'required|in:true,false',
            'quick_fetch_enabled'   => 'required|in:true,false',
            'show_right_sidebar'    => 'required|in:true,false',
        ]);

        $settings = [
            'submission_enabled'    => $request->submission_enabled,
            'auto_approval'         => $request->auto_approval,
            'enable_inline_related' => $request->enable_inline_related,
            'comments_enabled'      => $request->comments_enabled,
            'quick_fetch_enabled'   => $request->quick_fetch_enabled,
            'show_right_sidebar'    => $request->show_right_sidebar,
        ];

        foreach ($settings as $key => $value) {
            Setting::updateOrCreate(
                ['group' => 'post', 'key' => $key],
                ['value' => $value]
            );
        }

        Cache::forget('post_settings');

        return response()->json(['message' => 'Post settings updated successfully.']);
    }
}