<?php

namespace Modules\VetSite\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetSite\Entities\VsSite;
use Modules\VetSite\Support\ThemeRegistry;

class ThemeController extends Controller
{
    private function biz()
    {
        return request()->session()->get('user.business_id');
    }

    private function gate()
    {
        if (! auth()->user()->can('vet_site.manage_design')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->gate();
        $site   = VsSite::forBusiness($this->biz());
        $themes = ThemeRegistry::all();
        return view('vetSite::admin.theme', compact('site', 'themes'));
    }

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

        $theme = $request->input('theme');
        if (! ThemeRegistry::exists($theme)) {
            return redirect()->route('vs.theme')->with('status', ['success' => 0, 'msg' => 'Unknown theme.']);
        }

        $site = VsSite::forBusiness($this->biz());
        $site->update(['theme' => $theme]);

        return redirect()->route('vs.theme')->with('status', ['success' => 1, 'msg' => 'Theme applied: ' . ThemeRegistry::get($theme)['name']]);
    }

    public function customize(Request $request)
    {
        $this->gate();
        $site = VsSite::forBusiness($this->biz());

        $clean = fn($v) => $v && preg_match('/^#?[0-9a-fA-F]{3,8}$/', $v) ? (str_starts_with($v, '#') ? $v : '#' . $v) : null;

        $site->update([
            'primary_color'   => $clean($request->input('primary_color')),
            'secondary_color' => $clean($request->input('secondary_color')),
            'accent_color'    => $clean($request->input('accent_color')),
            'font_heading'    => $request->input('font_heading') ?: null,
            'font_body'       => $request->input('font_body') ?: null,
        ]);

        return redirect()->route('vs.theme')->with('status', ['success' => 1, 'msg' => __('vetSite::lang.saved')]);
    }
}
