<?php
declare(strict_types=1);

namespace App\Modules\Settings\Services;

use App\Core\App;

/**
 * BrandingService — Centralized access to branding configuration.
 * Reads from system_config (group: branding) and caches per-request.
 */
class BrandingService
{
    private static ?array $cache = null;

    private static function load(): array
    {
        if (self::$cache !== null) {
            return self::$cache;
        }

        try {
            $db = App::getInstance()->db();
            $rows = $db->select(
                "SELECT config_key, config_value, config_type FROM system_config WHERE group_name = 'branding'"
            );
        } catch (\Throwable $e) {
            $rows = [];
        }

        $data = [];
        foreach ($rows as $row) {
            $key = str_replace('branding.', '', $row['config_key']);
            $value = $row['config_value'];
            if ($row['config_type'] === 'json' && $value) {
                $decoded = json_decode($value, true);
                $data[$key] = is_array($decoded) ? $decoded : [];
            } else {
                $data[$key] = $value;
            }
        }

        self::$cache = $data;
        return $data;
    }

    /**
     * Clear the cache (after updating branding settings).
     */
    public static function clearCache(): void
    {
        self::$cache = null;
    }

    /**
     * Get logo as data URI string (base64), or null if not set.
     */
    public static function logo(): ?string
    {
        $data = self::load();

        // Prefer base64 data URI stored in DB (survives Docker rebuilds)
        $dataUri = $data['logo_data'] ?? null;
        if ($dataUri && $dataUri !== '') {
            return $dataUri;
        }

        // Fallback: legacy file path (for backward compatibility)
        $path = $data['logo_path'] ?? null;
        if ($path && $path !== '') {
            $basePath = rtrim(parse_url(config('app.url', ''), PHP_URL_PATH) ?: '', '/');
            return $basePath . '/' . ltrim($path, '/');
        }

        return null;
    }

    public static function clubNameAr(): string
    {
        $data = self::load();
        return $data['club_name_ar'] ?? config('app.name_ar', 'الكابتن');
    }

    public static function clubNameEn(): string
    {
        $data = self::load();
        return $data['club_name_en'] ?? config('app.name_en', 'El Captain');
    }

    public static function subtitle(): string
    {
        $data = self::load();
        return $data['club_subtitle'] ?? 'SPORTS CITY';
    }

    /**
     * Get carnet design configuration as an associative array.
     */
    public static function carnetDesign(): array
    {
        $data = self::load();
        $design = $data['carnet_design'] ?? [];

        // Merge with defaults so views always have every key
        return array_merge([
            'front_bg_color'        => '#0D7377',
            'front_text_color'      => '#ffffff',
            'front_show_subtitle'   => true,
            'front_show_english_name' => true,
            'front_show_member_type'=> true,
            'front_show_qr'         => true,
            'front_qr_position'     => 'bottom-left',
            'front_logo_position'   => 'top-center',
            'back_show_branch_strip'=> true,
            'back_strip_color'      => '#0D7377',
            'back_show_instructions'=> true,
            'back_instructions_text'=> 'برجاء حمل هذه البطاقة أثناء التواجد بالنادي وتقديمها عند الطلب',
            'back_fields'           => ['full_name_ar', 'membership_number', 'branch_name', 'issued_at'],
        ], $design);
    }

    /**
     * Get receipt design configuration as an associative array.
     */
    public static function receiptDesign(): array
    {
        $data = self::load();
        $design = $data['receipt_design'] ?? [];

        return array_merge([
            'show_logo'             => true,
            'show_watermark'        => true,
            'watermark_text'        => config('app.name_ar', 'الكابتن'),
            'watermark_opacity'     => 0.06,
            'header_color'          => '#0D7377',
            'show_footer_print_info'=> true,
        ], $design);
    }
}
