<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Schema;
use Throwable;

class WebsiteSettings
{
    public const SETTINGS_KEY = 'website';

    /**
     * @return array<string, mixed>
     */
    public function settings(): array
    {
        try {
            if (! Schema::hasTable('settings')) {
                return $this->defaultSettings();
            }

            return $this->normalizeAssetPaths([
                ...$this->defaultSettings(),
                ...(Setting::query()->where('key', self::SETTINGS_KEY)->first()?->value ?? []),
            ]);
        } catch (Throwable) {
            return $this->defaultSettings();
        }
    }

    /**
     * @param  array<string, mixed>  $settings
     */
    public function save(array $settings): void
    {
        $settings = $this->normalizeAssetPaths($settings);

        Setting::query()->updateOrCreate(
            ['key' => self::SETTINGS_KEY],
            ['value' => [
                ...$this->defaultSettings(),
                ...$settings,
            ]],
        );
    }

    public function apply(): void
    {
        $settings = $this->settings();

        config([
            'app.name' => $settings['site_name'] ?: config('app.name'),
            'app.locale' => $settings['default_language'] ?: config('app.locale'),
            'app.timezone' => $settings['default_timezone'] ?: config('app.timezone'),
        ]);
    }

    /**
     * @return array<string, mixed>
     */
    public function defaultSettings(): array
    {
        return [
            'site_name' => 'urless',
            'site_tagline' => 'Shorten, Share & Monetize',
            'site_description' => 'Advanced URL shortener and monetized redirect platform with analytics, CMS, and admin dashboard.',
            'support_email' => 'support@urless.test',
            'sales_email' => 'sales@urless.test',
            'contact_phone' => '',
            'default_language' => config('app.locale', 'en'),
            'default_timezone' => config('app.timezone', 'UTC'),
            'primary_color' => '#4648d4',
            'logo_path' => null,
            'dark_logo_path' => null,
            'favicon_path' => null,
            'seo_title' => 'urless - Advanced URL Shortener & Monetized Redirect Platform',
            'seo_description' => 'Create branded short links, show monetized interstitial pages, track realtime analytics, and manage your URL platform from a premium admin dashboard.',
            'seo_keywords' => 'url shortener, monetized links, short links, redirect platform, link analytics, QR codes',
            'canonical_url' => config('app.url'),
            'robots' => 'index,follow',
            'og_title' => 'urless - Shorten, Share & Monetize',
            'og_description' => 'Turn links into measurable, monetized campaigns with urless.',
            'og_image_path' => null,
            'twitter_handle' => '',
            'default_country' => 'United States',
            'default_region' => '',
            'default_city' => '',
            'geo_latitude' => '',
            'geo_longitude' => '',
            'google_site_verification' => '',
            'bing_site_verification' => '',
            'google_analytics_id' => '',
            'facebook_pixel_id' => '',
            'facebook_url' => '',
            'x_url' => '',
            'linkedin_url' => '',
            'youtube_url' => '',
            'announcement_enabled' => false,
            'announcement_text' => 'New: Monetized interstitial pages are now available for creators.',
            'header_cta_label' => 'Register',
            'header_cta_url' => '/register',
            'footer_copyright' => '© 2026 urless. Kinetic Lens Design.',
            'custom_head_scripts' => '',
            'custom_body_scripts' => '',
        ];
    }

    public function logoUrl(?string $mode = null): ?string
    {
        $settings = $this->settings();
        $path = $mode === 'dark'
            ? ($settings['dark_logo_path'] ?: $settings['logo_path'])
            : $settings['logo_path'];

        return $this->publicUrl($path);
    }

    public function faviconUrl(): ?string
    {
        return $this->publicUrl($this->settings()['favicon_path'] ?? null);
    }

    public function ogImageUrl(): ?string
    {
        return $this->publicUrl($this->settings()['og_image_path'] ?? null);
    }

    /**
     * @param  mixed  $path
     */
    private function publicUrl($path): ?string
    {
        $path = $this->normalizeAssetPath($path);

        if (! filled($path)) {
            return null;
        }

        if (str_starts_with((string) $path, 'http://') || str_starts_with((string) $path, 'https://')) {
            return (string) $path;
        }

        return '/storage/'.ltrim((string) $path, '/');
    }

    /**
     * @param  array<string, mixed>  $settings
     * @return array<string, mixed>
     */
    private function normalizeAssetPaths(array $settings): array
    {
        foreach (['logo_path', 'dark_logo_path', 'favicon_path', 'og_image_path'] as $key) {
            if (array_key_exists($key, $settings)) {
                $settings[$key] = $this->normalizeAssetPath($settings[$key]);
            }
        }

        return $settings;
    }

    /**
     * @param  mixed  $path
     */
    private function normalizeAssetPath($path): ?string
    {
        if (is_array($path)) {
            $path = reset($path) ?: null;
        }

        if (! filled($path)) {
            return null;
        }

        $path = trim((string) $path);

        if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
            $urlPath = parse_url($path, PHP_URL_PATH);

            if (is_string($urlPath) && str_starts_with($urlPath, '/storage/')) {
                return ltrim(substr($urlPath, strlen('/storage/')), '/');
            }

            return $path;
        }

        return preg_replace('#^/?storage/#', '', $path);
    }
}
