<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\CmsService;
use Illuminate\Http\Request;

class CmsController extends Controller
{
    protected $service;

    public function __construct(CmsService $service)
    {
        $this->service = $service;
    }

    public function index()
    {
        $settings = $this->service->getAllGrouped();
        return view('admin.cms.index', compact('settings'));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'app_name' => 'required|string|max:50',
            'app_subtitle' => 'nullable|string|max:255',
            'hero_tagline' => 'nullable|string|max:255',
            'login_button_text' => 'required|string|max:30',
            'register_button_text' => 'required|string|max:30',
            'front_logo' => 'nullable|image|mimes:jpeg,png,jpg,svg,webp|max:2048',
            'hero_background' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
            'hero_overlay_opacity' => 'nullable|numeric|min:0|max:1',
            'hero_alignment' => 'nullable|in:left,center,right',
            'hero_text_color' => 'nullable|string|max:20',
        ]);

        // Handle Text Settings
        foreach ($request->only(['app_name', 'app_subtitle', 'hero_tagline', 'login_button_text', 'register_button_text', 'hero_overlay_opacity', 'hero_alignment', 'hero_text_color']) as $key => $value) {
            $this->service->set($key, $value);
        }

        // Handle Logo Upload
        if ($request->hasFile('front_logo')) {
            $path = $request->file('front_logo')->store('cms', 'public');
            $this->service->set('front_logo', $path, 'image');
        }

        // Handle Hero Background Upload
        if ($request->hasFile('hero_background')) {
            $path = $request->file('hero_background')->store('cms', 'public');
            $this->service->set('hero_background', $path, 'image');
        }

        $this->service->clearCache();

        return back()->with('success', 'Konfigurasi CMS berhasil diperbarui dan dipublikasikan.');
    }
}
