<?php

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

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Services\Admin\SettingsService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class SocialSettingsController extends Controller
{
    protected $settingsService;

    public function __construct(SettingsService $settingsService)
    {
        $this->settingsService = $settingsService;
    }

    /**
     * Get all social media links
     */
    public function index(): JsonResponse
    {
        try {
            // Fetch directly from service
            $data = $this->settingsService->getGroup('social');
            return response()->json($data);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error loading settings'], 500);
        }
    }

    /**
     * Update social media links
     */
    public function update(Request $request): JsonResponse
    {
        try {
            // Validate inputs
            $data = $request->validate([
                'social_facebook' => 'nullable|url',
                'social_twitter'  => 'nullable|url',
                'social_instagram'=> 'nullable|url',
                'social_youtube'  => 'nullable|url',
                'social_tiktok'   => 'nullable|url',
            ]);

            // Use the service to update the 'social' group
            $this->settingsService->updateGroup('social', $data);
            
            // Clear the cache so the frontend updates immediately
            Cache::forget('social_settings');

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

        } catch (\Illuminate\Validation\ValidationException $e) {
            // Return validation errors as 422
            throw $e;
        } catch (\Exception $e) {
            // Log the actual error for debugging
            Log::error('Social Settings Update Error: ' . $e->getMessage());
            
            return response()->json([
                'message' => 'Server Error: ' . $e->getMessage()
            ], 500);
        }
    }
}