<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Http;

class UrlImageExtractor
{
    /**
     * Extract the cover image URL from a webpage URL (e.g., og:image, twitter:image).
     * If the input is already a direct image URL, returns it as-is.
     * If the input is a webpage and no image can be extracted, returns null.
     *
     * @param string|null $url
     * @return string|null
     */
    public static function extract($url)
    {
        if (empty($url)) {
            return null;
        }

        $url = trim($url);

        // If it's not a valid URL, return as-is
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return $url;
        }

        // Try to check Content-Type of the URL using a quick HEAD request
        try {
            $response = Http::timeout(3)
                ->withHeaders([
                    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
                ])
                ->head($url);

            $contentType = $response->header('Content-Type');
            
            // If it is directly an image, return it
            if ($contentType && str_starts_with(strtolower($contentType), 'image/')) {
                return $url;
            }
        } catch (\Exception $e) {
            // Ignore error and proceed to GET request
        }

        // It might be a webpage, try fetching it to parse HTML
        try {
            $response = Http::timeout(5)
                ->withHeaders([
                    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
                ])
                ->get($url);

            $contentType = $response->header('Content-Type');
            
            // Double check if the GET response is directly an image
            if ($contentType && str_starts_with(strtolower($contentType), 'image/')) {
                return $url;
            }

            if ($response->successful()) {
                $html = $response->body();
                $extractedUrl = null;

                // 1. Match og:image
                if (preg_match('/<meta[^>]*property=["\']og:image["\'][^>]*content=["\']([^"\']+)["\']/i', $html, $matches)) {
                    $extractedUrl = $matches[1];
                } elseif (preg_match('/<meta[^>]*content=["\']([^"\']+)["\'][^>]*property=["\']og:image["\']/i', $html, $matches)) {
                    $extractedUrl = $matches[1];
                }
                // 2. Match twitter:image
                elseif (preg_match('/<meta[^>]*name=["\']twitter:image["\'][^>]*content=["\']([^"\']+)["\']/i', $html, $matches)) {
                    $extractedUrl = $matches[1];
                } elseif (preg_match('/<meta[^>]*content=["\']([^"\']+)["\'][^>]*name=["\']twitter:image["\']/i', $html, $matches)) {
                    $extractedUrl = $matches[1];
                }
                // 3. Match link rel="image_src"
                elseif (preg_match('/<link[^>]*rel=["\']image_src["\'][^>]*href=["\']([^"\']+)["\']/i', $html, $matches)) {
                    $extractedUrl = $matches[1];
                }
                // 4. Fallback: Parse Scribd specific if URL is Scribd
                elseif (str_contains($url, 'scribd.com') && preg_match('/"image_url":"([^"]+)"/i', $html, $matches)) {
                    $extractedUrl = stripslashes($matches[1]);
                }

                if ($extractedUrl) {
                    $extractedUrl = html_entity_decode($extractedUrl, ENT_QUOTES | ENT_HTML5, 'UTF-8');

                    // Resolve relative/protocol-relative URLs
                    if (str_starts_with($extractedUrl, '//')) {
                        $parsedUrl = parse_url($url);
                        $extractedUrl = ($parsedUrl['scheme'] ?? 'http') . ':' . $extractedUrl;
                    } elseif (str_starts_with($extractedUrl, '/')) {
                        $parsedUrl = parse_url($url);
                        $baseUrl = ($parsedUrl['scheme'] ?? 'http') . '://' . ($parsedUrl['host'] ?? '');
                        $extractedUrl = $baseUrl . $extractedUrl;
                    }
                    
                    return $extractedUrl;
                }
            }
        } catch (\Exception $e) {
            // Silently fallback on failure
        }

        // If it was a webpage but we couldn't extract any image, return null to force default image fallback
        return null;
    }

    /**
     * Generate a thematic Unsplash image based on the title and category.
     *
     * @param string $title
     * @param string $category
     * @return string
     */
    public static function getThemeImage($title, $category)
    {
        $text = strtolower($title . ' ' . $category);

        $themes = [
            'organik' => [
                'https://images.unsplash.com/photo-1545167622-3a6ac756afa4?w=800&auto=format&fit=crop&q=60', // Compost soil
                'https://images.unsplash.com/photo-1592150621744-aca64f48394a?w=800&auto=format&fit=crop&q=60', // Vegetables green leaves
                'https://images.unsplash.com/photo-1621460245598-a6d1a938be45?w=800&auto=format&fit=crop&q=60'  // Organic plant compost
            ],
            'anorganik' => [
                'https://images.unsplash.com/photo-1618477461853-cf6ed80faba5?w=800&auto=format&fit=crop&q=60', // Plastic bottle pollution
                'https://images.unsplash.com/photo-1605600611280-146e68892259?w=800&auto=format&fit=crop&q=60', // Plastic waste sorting
                'https://images.unsplash.com/photo-1503596476-1c12a8ba09a9?w=800&auto=format&fit=crop&q=60'  // Recycling bin
            ],
            'b3' => [
                'https://images.unsplash.com/photo-1532996122724-e3c354a0b15b?w=800&auto=format&fit=crop&q=60', // Battery electronics waste
                'https://images.unsplash.com/photo-1604187351574-c75ca79f5807?w=800&auto=format&fit=crop&q=60', // Chemicals lab hazardous
                'https://images.unsplash.com/photo-1548345680-f5475ea5df84?w=800&auto=format&fit=crop&q=60'  // Warning/hazardous symbol
            ],
            'poster' => [
                'https://images.unsplash.com/photo-1530587191325-3db32d826c18?w=800&auto=format&fit=crop&q=60', // Nature hands holding plants
                'https://images.unsplash.com/photo-1542601906990-b4d3fb778b09?w=800&auto=format&fit=crop&q=60', // Recycle bin green leaves
                'https://images.unsplash.com/photo-1473448912268-2022ce9509d8?w=800&auto=format&fit=crop&q=60'  // Earth day ecology
            ],
            'default' => [
                'https://images.unsplash.com/photo-1530587191325-3db32d826c18?w=800&auto=format&fit=crop&q=60', // Earth green
                'https://images.unsplash.com/photo-1502082553048-f009c37129b9?w=800&auto=format&fit=crop&q=60', // Nature leaf
                'https://images.unsplash.com/photo-1518531933037-91b2f5f229cc?w=800&auto=format&fit=crop&q=60'  // Nature green drops
            ]
        ];

        if (str_contains($text, 'organik') || str_contains($text, 'kompos') || str_contains($text, 'dapur') || str_contains($text, 'makanan') || str_contains($text, 'pupuk') || str_contains($text, 'sayur')) {
            $pool = $themes['organik'];
        } elseif (str_contains($text, 'anorganik') || str_contains($text, 'plastik') || str_contains($text, 'botol') || str_contains($text, 'daur ulang') || str_contains($text, 'kertas') || str_contains($text, 'kaca') || str_contains($text, 'kaleng')) {
            $pool = $themes['anorganik'];
        } elseif (str_contains($text, 'b3') || str_contains($text, 'racun') || str_contains($text, 'baterai') || str_contains($text, 'lampu') || str_contains($text, 'kimia') || str_contains($text, 'bahaya')) {
            $pool = $themes['b3'];
        } elseif (str_contains($text, 'poster')) {
            $pool = $themes['poster'];
        } else {
            $pool = $themes['default'];
        }

        // Deterministic selection based on title's hash
        $index = abs(crc32($title)) % count($pool);
        return $pool[$index];
    }
}
