<?php
class ZNewsBridge extends BridgeAbstract {
    const NAME = 'ZNews';
    const URI = 'https://znews.vn/';
    const DESCRIPTION = 'ZNews latest news feed';
    const MAINTAINER = 'YourName';
    const CACHE_TIMEOUT = 3600;
    
    const PARAMETERS = [
        'Latest News' => [
            'category' => [
                'name' => 'Category',
                'type' => 'list',
                'values' => [
                    'Trang chủ' => '',
                    'Thời sự' => 'thoi-su',
                    'Xã hội' => 'xa-hoi',
                    'Pháp luật' => 'phap-luat',
                    'Thế giới' => 'the-gioi',
                    'Kinh doanh' => 'kinh-doanh',
                    'Bất động sản' => 'bat-dong-san',
                    'Công nghệ' => 'cong-nghe',
                    'Giáo dục' => 'giao-duc',
                    'Du lịch' => 'du-lich',
                    'Sức khỏe' => 'suc-khoe',
                    'Gia đình' => 'gia-dinh',
                    'Ẩm thực' => 'am-thuc',
                    'Thể thao' => 'the-thao',
                    'Giải trí' => 'giai-tri'
                ],
                'defaultValue' => ''
            ],
            'limit' => [
                'name' => 'Limit',
                'type' => 'number',
                'defaultValue' => 20
            ]
        ]
    ];
    
    public function collectData() {
        $category = $this->getInput('category') ?: '';
        $limit = $this->getInput('limit') ?: 20;
        
        // Build URL - znews.vn uses different URL structure
        if ($category) {
            $url = self::URI . $category . '.html';
        } else {
            $url = self::URI;
        }
        
        $html = getSimpleHTMLDOM($url)
            or returnServerError('Could not request: ' . $url);
        
        // Try multiple selectors as znews.vn might use different structures
        $selectors = [
            '.article-item',
            '.news-item', 
            '.story-item',
            '.item-news',
            'article',
            '.box-category-item'
        ];
        
        $articles = [];
        foreach ($selectors as $selector) {
            $articles = $html->find($selector);
            if (count($articles) > 0) {
                break;
            }
        }
        
        $count = 0;
        foreach ($articles as $article) {
            if ($count >= $limit) break;
            
            $item = $this->extractArticleData($article);
            if ($item) {
                $item['categories'] = [$category ?: 'trang-chu'];
                $this->items[] = $item;
                $count++;
            }
        }
        
        // If no articles found, create a debug item
        if (count($this->items) == 0) {
            $this->items[] = [
                'title' => 'Debug: No articles found for ' . $url,
                'uri' => $url,
                'content' => 'No articles were found. This might be due to changes in the website structure.',
                'timestamp' => time(),
                'categories' => ['debug']
            ];
        }
    }
    
    private function extractArticleData($article) {
        $item = [];
        
        // Try different selectors for title and link
        $titleSelectors = [
            'h1 a', 'h2 a', 'h3 a', 'h4 a',
            '.title a', '.article-title a',
            'a[title]', 'a'
        ];
        
        $titleElement = null;
        foreach ($titleSelectors as $selector) {
            $titleElement = $article->find($selector, 0);
            if ($titleElement && trim($titleElement->plaintext)) {
                break;
            }
        }
        
        if (!$titleElement) {
            return null;
        }
        
        $item['title'] = trim($titleElement->plaintext ?: $titleElement->title);
        $item['uri'] = $this->normalizeUrl($titleElement->href);
        
        // Try to find description
        $descSelectors = [
            '.article-summary', '.summary', '.sapo',
            '.description', '.excerpt', 'p'
        ];
        
        foreach ($descSelectors as $selector) {
            $descElement = $article->find($selector, 0);
            if ($descElement && trim($descElement->plaintext)) {
                $item['content'] = trim($descElement->plaintext);
                break;
            }
        }
        
        // Try to find image
        $imgSelectors = [
            '.article-thumbnail img', '.thumb img',
            '.article-image img', 'img'
        ];
        
        foreach ($imgSelectors as $selector) {
            $imgElement = $article->find($selector, 0);
            if ($imgElement) {
                $imgSrc = $imgElement->src ?: $imgElement->getAttribute('data-src');
                if ($imgSrc) {
                    $item['enclosures'] = [$this->normalizeUrl($imgSrc)];
                    break;
                }
            }
        }
        
        // Try to find time
        $timeSelectors = [
            '.article-time', '.time', '.date',
            'time', '.published'
        ];
        
        foreach ($timeSelectors as $selector) {
            $timeElement = $article->find($selector, 0);
            if ($timeElement) {
                $timeText = $timeElement->plaintext ?: $timeElement->datetime;
                if ($timeText) {
                    $item['timestamp'] = $this->parseVietnameseDateTime($timeText);
                    break;
                }
            }
        }
        
        if (!isset($item['timestamp'])) {
            $item['timestamp'] = time();
        }
        
        return $item;
    }
    
    private function normalizeUrl($url) {
        if (strpos($url, 'http') === 0) {
            return $url;
        }
        if (strpos($url, '//') === 0) {
            return 'https:' . $url;
        }
        return self::URI . ltrim($url, '/');
    }
    
    private function parseVietnameseDateTime($timeString) {
        $timeString = trim($timeString);
        
        // Handle formats like "14:30, 09/07/2025"
        if (preg_match('/(\d{1,2}):(\d{2}),?\s*(\d{1,2})\/(\d{1,2})\/(\d{4})/', $timeString, $matches)) {
            $hour = intval($matches[1]);
            $minute = intval($matches[2]);
            $day = intval($matches[3]);
            $month = intval($matches[4]);
            $year = intval($matches[5]);
            
            return mktime($hour, $minute, 0, $month, $day, $year);
        }
        
        // Handle relative time
        if (preg_match('/(\d+)\s*(phút|giờ|ngày)\s*trước/i', $timeString, $matches)) {
            $number = intval($matches[1]);
            $unit = $matches[2];
            
            $multiplier = [
                'phút' => 60,
                'giờ' => 3600,
                'ngày' => 86400
            ];
            
            if (isset($multiplier[$unit])) {
                return time() - ($number * $multiplier[$unit]);
            }
        }
        
        // Try standard parsing
        $timestamp = strtotime($timeString);
        return $timestamp ?: time();
    }
    
    public function getName() {
        $category = $this->getInput('category') ?: 'trang-chu';
        return 'ZNews - ' . ucfirst(str_replace('-', ' ', $category));
    }
}
?>