<?php

namespace App\Http\Controllers\Admin;

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

class ThemeController extends Controller
{
    public function index()
    {
        $themeDir = resource_path('views/themes');
        $themes = [];

        if (File::exists($themeDir)) {
            $directories = File::directories($themeDir);
            
            foreach ($directories as $dir) {
                $dirName = basename($dir);
                $jsonPath = $dir . '/theme.json';
                
                if (File::exists($jsonPath)) {
                    $json = json_decode(File::get($jsonPath), true);
                    $themes[$dirName] = [
                        'id' => $dirName,
                        'name' => $json['name'] ?? $dirName,
                        'description' => $json['description'] ?? '',
                        'version' => $json['version'] ?? '1.0.0',
                        'author' => $json['author'] ?? 'Unknown',
                        'screenshot' => $json['screenshot'] ?? null,
                    ];
                } else {
                    // Fallback jika tidak ada theme.json
                    $themes[$dirName] = [
                        'id' => $dirName,
                        'name' => ucwords(str_replace('-', ' ', $dirName)),
                        'description' => 'Tidak ada deskripsi.',
                        'version' => '1.0.0',
                        'author' => 'Unknown',
                        'screenshot' => null,
                    ];
                }
            }
        }

        $activeTheme = Setting::where('key', 'active_theme')->value('value') ?? 'default';

        return view('admin.themes.index', compact('themes', 'activeTheme'));
    }

    public function update(Request $request)
    {
        $request->validate([
            'theme' => 'required|string'
        ]);

        $themeId = $request->theme;
        $themePath = resource_path('views/themes/' . $themeId);

        if (!File::exists($themePath)) {
            return back()->with('error', 'Tema tidak ditemukan.');
        }

        Setting::updateOrCreate(
            ['key' => 'active_theme'],
            ['value' => $themeId]
        );

        return redirect()->route('admin.themes.index')->with('success', 'Tema berhasil diubah menjadi ' . $themeId);
    }
}
