<?php

namespace Modules\LandingPage\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;

class ThemeSettingController extends Controller
{
    public function edit()
    {
        $activeTheme = setting('landingpage_active_theme', 'general');
        $availableThemes = $this->getAvailableThemes();

        // Here you could load theme-specific settings if you implement them
        // For now, we only manage the active theme.

        return view('landingpage::admin.theme_settings.edit', compact('activeTheme', 'availableThemes'));
    }

    public function update(Request $request)
    {
        $request->validate([
            'landingpage_active_theme' => 'required|string',
            // Add validation for other theme-specific settings here
        ]);

        Setting::updateOrCreate(
            ['key' => 'landingpage_active_theme'],
            ['value' => $request->input('landingpage_active_theme')]
        );

        // Save other theme-specific settings here

        Artisan::call('cache:clear');
        Artisan::call('config:clear'); // Clear config cache as settings might be cached

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

    protected function getAvailableThemes(): array
    {
        $themes = [];
        $themePath = module_path('LandingPage', 'Resources/views/themes');

        if (File::isDirectory($themePath)) {
            $directories = File::directories($themePath);
            foreach ($directories as $directory) {
                $themeName = basename($directory);
                // You could read a theme.json file here for more theme details (name, author, screenshot)
                $themes[$themeName] = ucfirst(str_replace('_', ' ', $themeName));
            }
        }
        return $themes;
    }
}