<?php
declare(strict_types=1);

class Design
{
    private string $file;

    private array $defaults = [
        'font_heading'    => 'Playfair Display',
        'font_body'       => 'Inter',
        'preset'          => 'classic',
        'color_primary'   => '#b8962e',
        'color_secondary' => '#d4af72',
        'color_bg'        => '#ffffff',
        'color_headline'  => '#1a1a1a',
        'color_body'      => '#444444',
    ];

    public function __construct(string $dataDir)
    {
        $this->file = $dataDir . '/design.json';
    }

    public function get(): array
    {
        if (!file_exists($this->file)) {
            return $this->defaults;
        }
        $data = json_decode(file_get_contents($this->file), true) ?? [];
        return array_merge($this->defaults, $data);
    }

    private const VALID_FONTS = [
        'Playfair Display', 'Cormorant Garamond', 'Lora', 'Merriweather',
        'EB Garamond', 'Libre Baskerville', 'Crimson Pro',
        'Inter', 'Montserrat', 'Raleway', 'Josefin Sans', 'Nunito',
        'Open Sans', 'Lato', 'Poppins', 'Work Sans', 'DM Sans',
        'Outfit', 'Plus Jakarta Sans', 'Mulish',
        'Great Vibes', 'Tangerine', 'Pinyon Script',
        'La Belle Aurore', 'Over the Rainbow',
    ];

    private const VALID_PRESETS = ['classic', 'romantic', 'modern_dark', 'autumn', 'custom'];

    public function update(array $input): array
    {
        $current = $this->get();

        $allowed = ['font_heading', 'font_body', 'preset', 'color_primary', 'color_secondary', 'color_bg', 'color_headline', 'color_body'];
        foreach ($allowed as $key) {
            if (array_key_exists($key, $input)) {
                $val = (string)$input[$key];
                if (str_starts_with($key, 'color_')) {
                    $val = $this->sanitizeColor($val);
                } elseif (str_starts_with($key, 'font_')) {
                    if (!in_array($val, self::VALID_FONTS, true)) continue;
                } elseif ($key === 'preset') {
                    if (!in_array($val, self::VALID_PRESETS, true)) continue;
                }
                $current[$key] = $val;
            }
        }

        $tmp = $this->file . '.tmp';
        file_put_contents($tmp, json_encode($current, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
        rename($tmp, $this->file);

        return $current;
    }

    // ── Private ───────────────────────────────────────────────────────────────

    private function sanitizeColor(string $val): string
    {
        $val = trim($val);
        // Allow #rrggbb and #rgb
        if (preg_match('/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/', $val)) {
            return strtolower($val);
        }
        return '';
    }
}
