<?php

namespace App\Http\Controllers\Admin\Settings;

use Illuminate\Http\Request;
use Inertia\Inertia;

class SocialMediaSettingsController extends BaseSettingsController
{
    public function index()
    {
        $allSettings = $this->getAllSettings();

        return Inertia::render('admin/settings/social-media/index', [
            'socialMedia' => [
                'facebook' => [
                    'enabled' => $allSettings->get('social_facebook_enabled') === '1',
                    'url' => $allSettings->get('social_facebook_url') ?? '',
                ],
                'discord' => [
                    'enabled' => $allSettings->get('social_discord_enabled') === '1',
                    'url' => $allSettings->get('social_discord_url') ?? '',
                ],
                'instagram' => [
                    'enabled' => $allSettings->get('social_instagram_enabled') === '1',
                    'url' => $allSettings->get('social_instagram_url') ?? '',
                ],
                'tiktok' => [
                    'enabled' => $allSettings->get('social_tiktok_enabled') === '1',
                    'url' => $allSettings->get('social_tiktok_url') ?? '',
                ],
                'youtube' => [
                    'enabled' => $allSettings->get('social_youtube_enabled') === '1',
                    'url' => $allSettings->get('social_youtube_url') ?? '',
                ],
            ],
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'facebook_enabled' => 'required|boolean',
            'facebook_url' => 'nullable|url|max:255',
            'discord_enabled' => 'required|boolean',
            'discord_url' => 'nullable|url|max:255',
            'instagram_enabled' => 'required|boolean',
            'instagram_url' => 'nullable|url|max:255',
            'tiktok_enabled' => 'required|boolean',
            'tiktok_url' => 'nullable|url|max:255',
            'youtube_enabled' => 'required|boolean',
            'youtube_url' => 'nullable|url|max:255',
        ]);

        $platforms = ['facebook', 'discord', 'instagram', 'tiktok', 'youtube'];

        foreach ($platforms as $platform) {
            $this->setBoolSetting("social_{$platform}_enabled", $request->boolean("{$platform}_enabled"));
            $this->setSetting("social_{$platform}_url", $request->input("{$platform}_url") ?? '');
        }

        $this->refreshSettingsCache();

        return back()->with('success', 'Social media settings updated successfully.');
    }
}
