<?php

namespace App\Http\Controllers\Api;

use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * @tags 11. App Settings (Public)
 */
class SettingsApiController extends ApiController
{
    /**
     * Get App Settings
     * 
     * Get all public app settings for mobile/web apps.
     */
    public function index(Request $request): JsonResponse
    {
        $currentLocale = $this->getCurrentLocale($request);
        $countryId = $currentLocale['country_id'];

        $settings = [
            'app' => [
                'name' => app_name(),
                'version' => app_version(),
                'logo' => app_logo(),
                'favicon' => app_favicon(),
                'description' => setting('general.app_description', '', $countryId),
            ],
            'social' => [
                'facebook_app_id' => setting('social.facebook_app_id'),
                'google_client_id' => setting('social.google_client_id'),
                'facebook_url' => setting('social.facebook_url'),
                'twitter_url' => setting('social.twitter_url'),
                'instagram_url' => setting('social.instagram_url'),
            ],
            'seo' => [
                'title_template' => seo_title('', $countryId),
                'description' => seo_description($countryId),
                'keywords' => seo_keywords($countryId),
                'google_analytics_id' => google_analytics_id(),
                'facebook_pixel_id' => facebook_pixel_id(),
                'google_tag_manager_id' => google_tag_manager_id(),
            ],
            'features' => [
                'maintenance_mode' => setting('general.maintenance_mode', false),
                'maintenance_message' => setting('general.maintenance_message', ''),
                'facebook_login' => !empty(setting('social.facebook_app_id')),
                'google_login' => !empty(setting('social.google_client_id')),
            ],
        ];

        return $this->successResponse($settings, 'App settings retrieved successfully');
    }

    /**
     * Check App Version
     * 
     * Check if client app version is compatible.
     */
    public function checkVersion(Request $request): JsonResponse
    {
        $request->validate([
            'app_version' => 'required|string',
            'platform' => 'required|in:android,ios,web',
        ]);

        $clientVersion = $request->app_version;
        $currentVersion = app_version();
        $needsUpdate = version_compare($clientVersion, $currentVersion, '<');

        return $this->successResponse([
            'needs_update' => $needsUpdate,
            'client_version' => $clientVersion,
            'current_version' => $currentVersion,
            'platform' => $request->platform,
        ], 'Version checked successfully');
    }
}