<?php

namespace App\Http\Controllers\Settings\SystemSettings;

use App\Http\Controllers\Controller;
use App\Http\Requests\SystemSettings\DocumentationRequest;
use App\Models\SystemSetting;
use App\Services\GitBookJwtService;

class DocumentationController extends Controller
{
    /**
     * Initialize the controller with the GitBookJwtService.
     *
     * @param \App\Services\GitBookJwtService $jwtService The service to manage Gitbook JWT interactions
     */
    public function __construct(protected GitBookJwtService $jwtService) {}

    /**
     * Display the documentation settings view.
     *
     * @return \Illuminate\View\View The view for the documentation settings
     */
    public function index()
    {
        $systemSettings = SystemSetting::whereIn('slug', ['api_guide_url', 'help_guide_url', 'help_guide_authentication_token', 'api_guide_authentication_token'])->pluck('value', 'slug');
        $data = $systemSettings->toArray();

        return view('settings.system-settings.documentation', ['data' => $data]);
    }

    /**
     * Store or update documentation settings.
     *
     * This function takes in the validated request data and iterates over it.
     * For each key-value pair, it checks if the value is not empty.
     * If it is not, it converts the key to snake_case for the slug and to a human-readable name.
     * It then finds or creates a SystemSetting with the given slug and updates its value with the given value.
     * Finally, it redirects back to the view with a success message.
     *
     * @param \App\Http\Requests\SystemSettings\DocumentationRequest $request The incoming request instance
     *
     * @return \Illuminate\Http\RedirectResponse The redirect response with a success message
     */
    public function store(DocumentationRequest $request)
    {
        // Exclude the token and commit fields
        $requestData = $request->except(['_token']);

        foreach ($requestData as $key => $value) {
            // Skip if value is empty
            if (empty($value)) {
                continue;
            }

            // Convert key to snake_case for slug.
            $slug = snake_case($key);

            // Convert key to human-readable name.
            $name = ucwords(str_replace('_', ' ', $key));

            // Skip updating value for empty authentication token to preserve existing value.
            if (($key === 'help_guide_authentication_token' || $key === 'api_guide_authentication_token') && empty($value)) {
                continue;
            }

            // Find or create a SystemSetting with the given slug.
            SystemSetting::updateOrCreate(
                ['slug' => $slug],
                ['name' => $name, 'value' => $value]
            );
        }

        return back()->with('message', 'Settings updated');
    }
}
