<?php
// custom-bridges/VnEconomyBridge.php
class VnEconomyBridge extends BridgeAbstract {
    const NAME = 'VnEconomy';
    const URI = 'https://vneconomy.vn/';
    const DESCRIPTION = 'VnEconomy 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',
                    'Kinh tế' => 'kinh-te',
                    'Doanh nghiệp' => 'doanh-nghiep',
                    'Thương mại' => 'thuong-mai',
                    'Chứng khoán' => 'chung-khoan',
                    'Ngân hàng' => 'ngan-hang',
                    'Bất động sản' => 'bat-dong-san',
                    'Khởi nghiệp' => 'khoi-nghiep',
                    'Công nghệ' => 'cong-nghe',
                    'Tiêu dùng' => 'tieu-dung',
                    'Năng lượng' => 'nang-luong',
                    'Nông nghiệp' => 'nong-nghiep',
                    'Thế giới' => 'the-gioi',
                    'Tài chính' => 'tai-chinh'
                ],
                'defaultValue' => ''
            ],
            'limit' => [
                'name' => 'Limit',
                'type' => 'number',
                'defaultValue' => 20
            ]
        ]
    ];
    
    public function collectData() {
        $category = $this->getInput('category') ?: '';
        $limit = $this->getInput('limit') ?: 20;
        
        $url = self::URI . ($category ? $category . '.htm' : '');
        $html = getSimpleHTMLDOM($url)
            or returnServerError('Could not request: ' . $url);
        
        $articles = $html->find('.story, .story-item, .news-item');
        $count = 0;
        
        foreach ($articles as $article) {
            if ($count >= $limit) break;
            
            $item = [];
            
            // Get title and link
            $titleElement = $article->find('h3 a', 0);
            if (!$titleElement) {
                $titleElement = $article->find('.story-title a', 0);
            }
            if (!$titleElement) {
                $titleElement = $article->find('a.story-link', 0);
            }
            if (!$titleElement) continue;
            
            $item['title'] = trim($titleElement->plaintext ?: $titleElement->title);
            $item['uri'] = $this->normalizeUrl($titleElement->href);
            
            // Get description
            $descElement = $article->find('.story-summary', 0);
            if (!$descElement) {
                $descElement = $article->find('.summary', 0);
            }
            if (!$descElement) {
                $descElement = $article->find('p', 0);
            }
            if ($descElement) {
                $item['content'] = trim($descElement->plaintext);
            }
            
            // Get image
            $imgElement = $article->find('.story-photo img', 0);
            if (!$imgElement) {
                $imgElement = $article->find('img', 0);
            }
            if ($imgElement) {
                $imgSrc = $imgElement->src ?: $imgElement->getAttribute('data-src');
                if ($imgSrc) {
                    $item['enclosures'] = [$this->normalizeUrl($imgSrc)];
                }
            }
            
            // Get publish time
            $timeElement = $article->find('.story-time', 0);
            if (!$timeElement) {
                $timeElement = $article->find('.time', 0);
            }
            if (!$timeElement) {
                $timeElement = $article->find('time', 0);
            }
            if ($timeElement) {
                $timeText = $timeElement->plaintext ?: $timeElement->datetime;
                $item['timestamp'] = $this->parseVietnameseDateTime($timeText);
            } else {
                $item['timestamp'] = time();
            }
            
            // Get author if available
            $authorElement = $article->find('.story-author', 0);
            if ($authorElement) {
                $item['author'] = trim($authorElement->plaintext);
            }
            
            // Get category
            $item['categories'] = [$category ?: 'trang-chu'];
            
            $this->items[] = $item;
            $count++;
        }
    }
    
    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 "15:30 | 09/07/2025"
        if (preg_match('/(\d{1,2}):(\d{2})\s*\|\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];
            
            $seconds = 0;
            switch ($unit) {
                case 'phút':
                    $seconds = $number * 60;
                    break;
                case 'giờ':
                    $seconds = $number * 3600;
                    break;
                case 'ngày':
                    $seconds = $number * 86400;
                    break;
            }
            
            return time() - $seconds;
        }
        
        // Try standard parsing
        $timestamp = strtotime($timeString);
        return $timestamp ?: time();
    }
    
    public function getName() {
        $category = $this->getInput('category') ?: 'trang-chu';
        return 'VnEconomy - ' . ucfirst(str_replace('-', ' ', $category));
    }
}
?>