<?php

namespace Core\App\Services;

class ThemeAssetService
{
    public const DEFAULTS = [
        'colors' => [
            'primary'   => '#598aee',
            'secondary' => '#f7182e',
            'success'   => '#1ae055',
            'danger'    => '#e8663b',
            'warning'   => '#ced062',
            'info'      => '#39dbba',
            'light'     => '#f6f4f4',
            'dark'      => '#16161d',
        ],
        'fonts' => [
            'body'    => 'ar_cairo',
            'heading' => 'ar_tajawal',
        ],
        'custom_css' => '',
        'admin_theme' => [
            'fonts' => [
                'body'    => 'ar_cairo',
                'heading' => 'ar_tajawal',
            ],
            'colors' => [
                'primary'             => '#0d6efd',
                'secondary'           => '#6c757d',
                'success'             => '#198754',
                'info'                => '#0dcaf0',
                'warning'             => '#ffc107',
                'danger'              => '#dc3545',
                'light'               => '#f8f9fa',
                'dark'                => '#212529',
                'sidebar_bg'          => '#212529',
                'sidebar_text'        => '#c2c7d0',
                'sidebar_active_bg'   => '#0d6efd',
                'sidebar_active_text' => '#ffffff',
                'header_bg'           => '#ffffff',
                'header_text'         => '#212529',
                'body_bg'             => '#f4f6f9',
                'body_text'           => '#212529',
                'card_bg'             => '#ffffff',
                'card_header_bg'      => '#ffffff',
                'link'                => '#0d6efd',
                'border'              => '#dee2e6',
            ],
            'mode' => 'light',
        ],
    ];

    public static function fontMap(): array
    {
        return [
            'ar_cairo' => [
                'family' => "'Cairo', sans-serif",
                'import' => "@import url('/public/assets/fonts/cairo/cairo.css');",
            ],
            'ar_tajawal' => [
                'family' => "'Tajawal', sans-serif",
                'import' => "@import url('/public/assets/fonts/tajawal/tajawal.css');",
            ],
            'ar_noto_kufi' => [
                'family' => "'Noto Kufi Arabic', sans-serif",
                'import' => "@import url('/public/assets/fonts/noto-kufi-arabic/noto-kufi-arabic.css');",
            ],
            'en_poppins' => [
                'family' => "'Poppins', sans-serif",
                'import' => "@import url('/public/assets/fonts/poppins/poppins.css');",
            ],
            'en_roboto' => [
                'family' => "'Roboto', sans-serif",
                'import' => "@import url('/public/assets/fonts/roboto/roboto.css');",
            ],
        ];
    }

    public static function frontendDefaults(): array
    {
        return self::DEFAULTS;
    }

    public static function buildFrontendCss(array $settings = []): string
    {
        $defaults   = self::DEFAULTS;
        $fontMap    = self::fontMap();
        $colors     = array_merge($defaults['colors'], (array)($settings['colors'] ?? []));
        $fonts      = array_merge($defaults['fonts'], (array)($settings['fonts'] ?? []));
        $customCss  = (string)($settings['custom_css'] ?? $defaults['custom_css']);

        $bodyKey     = $fonts['body']    ?? $defaults['fonts']['body'];
        $headingKey  = $fonts['heading'] ?? $defaults['fonts']['heading'];
        $bodyFont    = $fontMap[$bodyKey]['family']    ?? $fontMap[$defaults['fonts']['body']]['family'];
        $headingFont = $fontMap[$headingKey]['family'] ?? $fontMap[$defaults['fonts']['heading']]['family'];

        $imports = [];
        foreach ([$bodyKey, $headingKey] as $key) {
            if (!empty($fontMap[$key]['import'])) {
                $imports[$key] = $fontMap[$key]['import'];
            }
        }

        $css = "/* Generated automatically by Theme Customizer */
";
        foreach ($imports as $imp) {
            $css .= $imp . "
";
        }

        $css .= "
:root {
";
        foreach ($colors as $name => $value) {
            $safeName  = preg_replace('/[^a-z0-9_-]/i', '', (string)$name);
            $safeValue = trim((string)$value);
            if ($safeName === '' || $safeValue === '') {
                continue;
            }
            $css .= "  --{$safeName}: {$safeValue};
";
        }

        $aliasMap = [
            'primary'   => 'primary-color',
            'secondary' => 'secondary-color',
            'success'   => 'success-color',
            'danger'    => 'danger-color',
            'warning'   => 'warning-color',
            'info'      => 'info-color',
            'light'     => 'light-color',
            'dark'      => 'dark-color',
        ];
        foreach ($aliasMap as $src => $alias) {
            if (!empty($colors[$src])) {
                $css .= "  --{$alias}: {$colors[$src]};
";
            }
        }
        $css .= "  --site-font-body: {$bodyFont};
";
        $css .= "  --site-font-heading: {$headingFont};
";
        $css .= "}

";

        $css .= "html, body, body button, body input, body select, body textarea {
";
        $css .= "  font-family: var(--site-font-body) !important;
";
        $css .= "}

";

        $css .= "body, body p, body span, body a, body li, body td, body th, body label, body small, body strong, body em, body div, body input, body button, body select, body textarea {
";
        $css .= "  font-family: var(--site-font-body) !important;
";
        $css .= "}

";

        $css .= "body h1, body h2, body h3, body h4, body h5, body h6, body .section-title, body .hero-title, body .product-title {
";
        $css .= "  font-family: var(--site-font-heading) !important;
";
        $css .= "}

";

        if (trim($customCss) !== '') {
            $css .= "/* Custom CSS */
" . trim($customCss) . "
";
        }

        return $css;
    }

    public static function writeFrontendCss(array $settings = []): string
    {
        $path = ROOT_PATH . '/public/assets/theme/style-generated.css';
        $dir  = dirname($path);
        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }
        file_put_contents($path, self::buildFrontendCss($settings));
        return $path;
    }

    public static function ensureFrontendCss(array $settings = []): string
    {
        $path = ROOT_PATH . '/public/assets/theme/style-generated.css';
        if (!is_file($path) || filesize($path) === 0) {
            return self::writeFrontendCss($settings);
        }
        return $path;
    }

    public static function assetUrl(string $path = '/public/assets/theme/style-generated.css'): string
    {
        $full = ROOT_PATH . $path;
        $ver  = is_file($full) ? (string)filemtime($full) : (string)time();
        return $path . '?v=' . $ver;
    }
}
