<?php

namespace App\Helpers;

use App\Models\Setting;

class SeoHelper
{
    /**
     * Get the site name
     */
    public static function siteName(): string
    {
        return Setting::get('site_name', 'GengSewa');
    }

    /**
     * Get the site tagline
     */
    public static function siteTagline(): string
    {
        return Setting::get('site_tagline', 'Your Trusted Rental Marketplace');
    }

    /**
     * Get the SEO title
     */
    public static function seoTitle(): string
    {
        return Setting::get('seo_title', 'GengSewa - Rent Cars, Boats, Houseboats & Guesthouses in Malaysia');
    }

    /**
     * Get the SEO description
     */
    public static function seoDescription(): string
    {
        return Setting::get('seo_description', 'Discover and book the best rental properties in Malaysia.');
    }

    /**
     * Get the SEO keywords
     */
    public static function seoKeywords(): string
    {
        return Setting::get('seo_keywords', 'car rental malaysia, boat rental, houseboat rental');
    }

    /**
     * Get the site logo URL
     */
    public static function logo(): ?string
    {
        $logo = Setting::get('site_logo');
        return $logo ? asset($logo) : null;
    }

    /**
     * Get the site favicon URL
     */
    public static function favicon(): ?string
    {
        $favicon = Setting::get('site_favicon');
        return $favicon ? asset($favicon) : null;
    }

    /**
     * Get the Open Graph image URL
     */
    public static function ogImage(): ?string
    {
        $ogImage = Setting::get('og_image');
        return $ogImage ? asset($ogImage) : asset('images/default-og.jpg');
    }

    /**
     * Get Google Analytics ID
     */
    public static function googleAnalyticsId(): ?string
    {
        return Setting::get('google_analytics_id');
    }

    /**
     * Get Google Site Verification code
     */
    public static function googleSiteVerification(): ?string
    {
        return Setting::get('google_site_verification');
    }

    /**
     * Get Facebook App ID
     */
    public static function facebookAppId(): ?string
    {
        return Setting::get('facebook_app_id');
    }

    /**
     * Get Twitter handle
     */
    public static function twitterHandle(): ?string
    {
        return Setting::get('twitter_handle');
    }

    /**
     * Get logo display mode
     */
    public static function logoDisplayMode(): string
    {
        return Setting::get('logo_display_mode', 'both');
    }

    /**
     * Get theme mode
     */
    public static function themeMode(): string
    {
        return Setting::get('theme_mode', 'system');
    }

    /**
     * Get custom primary color
     */
    public static function customPrimaryColor(): string
    {
        return Setting::get('custom_primary_color', '#6366f1');
    }

    /**
     * Generate color shades from primary color
     */
    public static function generateColorShades(string $hexColor): array
    {
        // Convert hex to RGB
        $hex = str_replace('#', '', $hexColor);
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));

        // Generate lighter and darker shades
        return [
            '50' => self::adjustBrightness($r, $g, $b, 0.95),
            '100' => self::adjustBrightness($r, $g, $b, 0.90),
            '200' => self::adjustBrightness($r, $g, $b, 0.75),
            '300' => self::adjustBrightness($r, $g, $b, 0.60),
            '400' => self::adjustBrightness($r, $g, $b, 0.40),
            '500' => $hexColor, // Original color
            '600' => self::adjustBrightness($r, $g, $b, -0.10),
            '700' => self::adjustBrightness($r, $g, $b, -0.25),
            '800' => self::adjustBrightness($r, $g, $b, -0.40),
            '900' => self::adjustBrightness($r, $g, $b, -0.55),
        ];
    }

    /**
     * Adjust brightness of RGB color
     */
    private static function adjustBrightness(int $r, int $g, int $b, float $percent): string
    {
        if ($percent > 0) {
            // Lighten
            $r = round($r + (255 - $r) * $percent);
            $g = round($g + (255 - $g) * $percent);
            $b = round($b + (255 - $b) * $percent);
        } else {
            // Darken
            $r = round($r * (1 + $percent));
            $g = round($g * (1 + $percent));
            $b = round($b * (1 + $percent));
        }

        $r = max(0, min(255, $r));
        $g = max(0, min(255, $g));
        $b = max(0, min(255, $b));

        return sprintf('#%02x%02x%02x', $r, $g, $b);
    }

    /**
     * Generate custom theme CSS
     */
    public static function generateCustomThemeCSS(): string
    {
        $primaryColor = self::customPrimaryColor();
        $shades = self::generateColorShades($primaryColor);

        return <<<CSS
:root {
    --color-primary-50: {$shades['50']};
    --color-primary-100: {$shades['100']};
    --color-primary-200: {$shades['200']};
    --color-primary-300: {$shades['300']};
    --color-primary-400: {$shades['400']};
    --color-primary-500: {$shades['500']};
    --color-primary-600: {$shades['600']};
    --color-primary-700: {$shades['700']};
    --color-primary-800: {$shades['800']};
    --color-primary-900: {$shades['900']};
}

/* Custom theme (replaces light theme) */
.custom {
    background-color: #ffffff;
    color: #1f2937;
}

.custom .bg-gray-50 { background-color: {$shades['50']} !important; }
.custom .bg-gray-100 { background-color: {$shades['100']} !important; }
.custom .bg-white { background-color: #ffffff !important; }
.custom .bg-blue-600, .custom .bg-indigo-600, .custom .bg-purple-600 { background-color: {$shades['600']} !important; }
.custom .bg-blue-700, .custom .bg-indigo-700, .custom .bg-purple-700 { background-color: {$shades['700']} !important; }
.custom .bg-blue-100 { background-color: {$shades['100']} !important; }
.custom .text-blue-600, .custom .text-indigo-600, .custom .text-purple-600 { color: {$shades['600']} !important; }
.custom .text-blue-700, .custom .text-indigo-700 { color: {$shades['700']} !important; }
.custom .text-blue-800, .custom .text-indigo-800 { color: {$shades['800']} !important; }
.custom .border-blue-600, .custom .border-indigo-600 { border-color: {$shades['600']} !important; }
.custom .from-blue-600 { --tw-gradient-from: {$shades['600']} !important; }
.custom .via-purple-600 { --tw-gradient-via: {$shades['600']} !important; }
.custom .to-indigo-700 { --tw-gradient-to: {$shades['700']} !important; }
.custom .hover\\:from-blue-700:hover { --tw-gradient-from: {$shades['700']} !important; }
.custom .hover\\:to-purple-700:hover { --tw-gradient-to: {$shades['700']} !important; }
.custom .focus\\:border-blue-500:focus { border-color: {$shades['500']} !important; }
.custom .focus\\:ring-blue-500:focus { --tw-ring-color: {$shades['500']} !important; }
CSS;
    }

    /**
     * Generate meta tags for a page
     *
     * @param string|null $title Override the default SEO title
     * @param string|null $description Override the default SEO description
     * @param string|null $image Override the default OG image
     * @param array $additionalMeta Additional meta tags
     * @return string HTML meta tags
     */
    public static function generateMetaTags(
        ?string $title = null,
        ?string $description = null,
        ?string $image = null,
        array $additionalMeta = []
    ): string {
        $title = $title ?? self::seoTitle();
        $description = $description ?? self::seoDescription();
        $image = $image ?? self::ogImage();
        $siteName = self::siteName();
        $twitterHandle = self::twitterHandle();

        $meta = [];

        // Basic SEO
        $meta[] = '<title>' . e($title) . '</title>';
        $meta[] = '<meta name="description" content="' . e($description) . '">';
        $meta[] = '<meta name="keywords" content="' . e(self::seoKeywords()) . '">';

        // Open Graph
        $meta[] = '<meta property="og:title" content="' . e($title) . '">';
        $meta[] = '<meta property="og:description" content="' . e($description) . '">';
        $meta[] = '<meta property="og:image" content="' . e($image) . '">';
        $meta[] = '<meta property="og:type" content="website">';
        $meta[] = '<meta property="og:site_name" content="' . e($siteName) . '">';
        $meta[] = '<meta property="og:url" content="' . e(url()->current()) . '">';

        // Facebook
        if ($fbAppId = self::facebookAppId()) {
            $meta[] = '<meta property="fb:app_id" content="' . e($fbAppId) . '">';
        }

        // Twitter Card
        $meta[] = '<meta name="twitter:card" content="summary_large_image">';
        $meta[] = '<meta name="twitter:title" content="' . e($title) . '">';
        $meta[] = '<meta name="twitter:description" content="' . e($description) . '">';
        $meta[] = '<meta name="twitter:image" content="' . e($image) . '">';
        if ($twitterHandle) {
            $meta[] = '<meta name="twitter:site" content="@' . e($twitterHandle) . '">';
            $meta[] = '<meta name="twitter:creator" content="@' . e($twitterHandle) . '">';
        }

        // Google Site Verification
        if ($verification = self::googleSiteVerification()) {
            $meta[] = '<meta name="google-site-verification" content="' . e($verification) . '">';
        }

        // Additional meta tags
        foreach ($additionalMeta as $key => $value) {
            $meta[] = '<meta name="' . e($key) . '" content="' . e($value) . '">';
        }

        return implode("\n    ", $meta);
    }

    /**
     * Generate Google Analytics tracking code
     *
     * @return string|null Google Analytics script
     */
    public static function googleAnalyticsScript(): ?string
    {
        $analyticsId = self::googleAnalyticsId();

        if (!$analyticsId) {
            return null;
        }

        return <<<HTML
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={$analyticsId}"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '{$analyticsId}');
</script>
HTML;
    }

    /**
     * Generate JSON-LD structured data for the organization
     *
     * @return string JSON-LD script
     */
    public static function organizationSchema(): string
    {
        $siteName = self::siteName();
        $logo = self::logo() ? url(self::logo()) : null;
        $url = url('/');

        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Organization',
            'name' => $siteName,
            'url' => $url,
        ];

        if ($logo) {
            $schema['logo'] = $logo;
        }

        if ($twitterHandle = self::twitterHandle()) {
            $schema['sameAs'] = [
                'https://twitter.com/' . $twitterHandle,
            ];
        }

        return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES) . '</script>';
    }
}
