<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Theme;
use App\Services\ThemeService;
use Illuminate\Http\Request;

class ThemeController extends Controller
{
    private ThemeService $themeService;

    public function __construct(ThemeService $themeService)
    {
        $this->themeService = $themeService;
    }

    /**
     * Display theme management interface
     */
    public function index()
    {
        $themes = $this->themeService->getAllThemes();
        $activeTheme = $this->themeService->getActiveTheme();
        
        return view('admin.themes.index', compact('themes', 'activeTheme'));
    }

    /**
     * Apply a theme
     */
    public function apply(Request $request)
    {
        $request->validate([
            'theme_id' => 'required|exists:themes,id'
        ]);

        try {
            $this->themeService->applyTheme($request->theme_id);

            return response()->json([
                'success' => true,
                'message' => 'Theme applied successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to apply theme: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Preview a theme (returns CSS variables without applying)
     */
    public function preview(int $themeId)
    {
        try {
            $theme = Theme::findOrFail($themeId);
            
            return response()->json([
                'success' => true,
                'theme' => $theme,
                'cssVariables' => $theme->toCssVariables()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Theme not found'
            ], 404);
        }
    }
}