<?php defined('BASEPATH') OR exit('No direct script access allowed');

define('RSS_CACHE_DIR', APPPATH . 'cache/rss/');
define('RSS_CACHE_TTL', 900); // 15 menit

class Berita extends CI_Controller
{
    private $is_admin = false;
    private $user_id  = 0;

    private $feeds = [
        'terbaru'       => ['url' => 'https://www.cnnindonesia.com/rss',                  'label' => 'Terbaru',      'icon' => 'bi-newspaper'],
        'nasional'      => ['url' => 'https://www.cnnindonesia.com/nasional/rss',          'label' => 'Nasional',     'icon' => 'bi-flag'],
        'ekonomi'       => ['url' => 'https://www.cnnindonesia.com/ekonomi/rss',           'label' => 'Ekonomi',      'icon' => 'bi-graph-up'],
        'teknologi'     => ['url' => 'https://www.cnnindonesia.com/teknologi/rss',         'label' => 'Teknologi',    'icon' => 'bi-cpu'],
        'olahraga'      => ['url' => 'https://www.cnnindonesia.com/olahraga/rss',          'label' => 'Olahraga',     'icon' => 'bi-trophy'],
        'hiburan'       => ['url' => 'https://www.cnnindonesia.com/hiburan/rss',           'label' => 'Hiburan',      'icon' => 'bi-stars'],
        'gaya-hidup'    => ['url' => 'https://www.cnnindonesia.com/gaya-hidup/rss',        'label' => 'Gaya Hidup',   'icon' => 'bi-heart'],
        'internasional' => ['url' => 'https://www.cnnindonesia.com/internasional/rss',     'label' => 'Internasional','icon' => 'bi-globe'],
    ];

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('authorization');
        check_login();

        $this->user_id  = (int) $this->session->userdata('user_id');
        $this->is_admin = is_admin();

        if (!is_dir(RSS_CACHE_DIR)) @mkdir(RSS_CACHE_DIR, 0755, true);
    }

    // ----------------------------------------------------------------
    // Halaman daftar berita
    // ----------------------------------------------------------------
    public function index()
    {
        $kat = $this->input->get('kat') ?: 'terbaru';
        if (!isset($this->feeds[$kat])) $kat = 'terbaru';

        $data['title']    = 'Berita Terkini';
        $data['is_admin'] = $this->is_admin;
        $data['kategori'] = $kat;
        $data['feeds']    = $this->feeds;
        $data['berita']   = $this->_fetch_rss($kat);
        $data['error']    = empty($data['berita']) ? 'Gagal memuat berita. Coba beberapa saat lagi.' : '';

        $this->load->view('templates/header', $data);
        $this->load->view('berita/index', $data);
        $this->load->view('templates/footer');
    }

    // ----------------------------------------------------------------
    // Halaman baca artikel - reader page
    // URL: berita/baca?url=...&kat=...
    // ----------------------------------------------------------------
    public function baca()
    {
        $url = $this->input->get('url');
        $kat = $this->input->get('kat') ?: 'terbaru';

        if (!isset($this->feeds[$kat])) $kat = 'terbaru';

        if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) {
            redirect('berita');
        }

        // Whitelist host - hanya CNN Indonesia
        $parsed        = parse_url($url);
        $allowed_hosts = ['www.cnnindonesia.com', 'cnnindonesia.com'];
        if (!in_array($parsed['host'] ?? '', $allowed_hosts)) {
            redirect('berita');
        }

        $artikel = [
            'judul'   => '',
            'gambar'  => '',
            'isi'     => [],
            'tanggal' => '',
            'penulis' => '',
            'url'     => $url,
        ];

        $html = $this->_http_get($url);

        if ($html) {
            $doc = new DOMDocument();
            // FIX PHP 8.5: Hapus libxml_use_internal_errors(), gunakan @ pada loadHTML
            @$doc->loadHTML('<?xml encoding="UTF-8">' . $html);
            $xpath = new DOMXPath($doc);

            // Judul
            $judul = $xpath->query('//meta[@property="og:title"]/@content');
            if (!$judul->length) $judul = $xpath->query('//h1');
            if ($judul->length) {
                $node = $judul->item(0);
                $artikel['judul'] = trim($node->nodeType === XML_ATTRIBUTE_NODE ? $node->nodeValue : $node->textContent);
            }

            // Gambar
            $og_img = $xpath->query('//meta[@property="og:image"]/@content');
            if ($og_img->length) $artikel['gambar'] = trim($og_img->item(0)->nodeValue);

            // Tanggal
            $tgl = $xpath->query('//meta[@property="article:published_time"]/@content');
            if (!$tgl->length) $tgl = $xpath->query('//time/@datetime');
            if ($tgl->length) $artikel['tanggal'] = trim($tgl->item(0)->nodeValue);

            // Penulis
            $penulis = $xpath->query('//meta[@name="author"]/@content');
            if (!$penulis->length) $penulis = $xpath->query('//div[contains(@class,"author")]');
            if ($penulis->length) {
                $node = $penulis->item(0);
                $artikel['penulis'] = trim($node->nodeType === XML_ATTRIBUTE_NODE ? $node->nodeValue : $node->textContent);
            }

            // Isi artikel
            $content_selectors = [
                '//div[contains(@class,"detail-text")]',
                '//div[contains(@class,"content-body")]',
                '//div[@class="detail__body-text"]',
                '//div[contains(@class,"detail__body")]',
                '//div[contains(@class,"article-content")]',
                '//div[contains(@class,"article__content")]',
                '//div[@id="detailText"]',
                '//article',
            ];

            foreach ($content_selectors as $sel) {
                $nodes = $xpath->query($sel);
                if (!$nodes->length) continue;

                $paragraphs = $xpath->query('.//p', $nodes->item(0));
                $teks = [];
                foreach ($paragraphs as $p) {
                    $t = trim($p->textContent);
                    if (strlen($t) > 40 && !preg_match('/^(ADVERTISEMENT|SCROLL TO CONTINUE|Baca juga|Lihat juga)/i', $t)) {
                        $teks[] = $t;
                    }
                }
                if (count($teks) >= 2) {
                    $artikel['isi'] = $teks;
                    break;
                }
            }
        }

        $data['title']    = $artikel['judul'] ?: 'Baca Berita';
        $data['is_admin'] = $this->is_admin;
        $data['kategori'] = $kat;
        $data['feeds']    = $this->feeds;
        $data['artikel']  = $artikel;

        $this->load->view('templates/header', $data);
        $this->load->view('berita/baca', $data);
        $this->load->view('templates/footer');
    }

    // ----------------------------------------------------------------
    // AJAX refresh cache RSS
    // ----------------------------------------------------------------
    public function ajax_load()
    {
        header('Content-Type: application/json');
        $kat = $this->input->post('kat') ?: 'terbaru';
        if (!isset($this->feeds[$kat])) $kat = 'terbaru';

        $cache_file = RSS_CACHE_DIR . md5('cnn_' . $kat) . '.json';
        if (file_exists($cache_file)) @unlink($cache_file);

        $items = $this->_fetch_rss($kat);
        echo json_encode(['ok' => true, 'items' => $items, 'total' => count($items)]);
    }

    // ----------------------------------------------------------------
    // HTTP GET helper
    // ----------------------------------------------------------------
    private function _http_get($url)
    {
        $ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36';

        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_TIMEOUT        => 15,
                CURLOPT_CONNECTTIMEOUT => 10,
                CURLOPT_USERAGENT      => $ua,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_MAXREDIRS      => 5,
                CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
                CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
                CURLOPT_ENCODING       => '',
                CURLOPT_HTTPHEADER     => [
                    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                    'Accept-Language: id-ID,id;q=0.9,en-US;q=0.8',
                    'Connection: close',
                ],
            ]);
            $result = curl_exec($ch);
            $err    = curl_error($ch);
            $code   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            // curl_close() removed — deprecated since PHP 8.5 (no-op since PHP 8.0)

            if (!$err && $result && $code >= 200 && $code < 400) {
                return $result;
            }
        }

        // Fallback file_get_contents
        if (ini_get('allow_url_fopen')) {
            $ctx = stream_context_create([
                'http' => [
                    'method'          => 'GET',
                    'header'          => "User-Agent: $ua\r\nConnection: close\r\n",
                    'timeout'         => 15,
                    'follow_location' => 1,
                ],
                'ssl'  => ['verify_peer' => false, 'verify_peer_name' => false],
            ]);
            $result = @file_get_contents($url, false, $ctx);
            if ($result) return $result;
        }

        return '';
    }

    // ----------------------------------------------------------------
    // Fetch & parse RSS feed dengan cache
    // ----------------------------------------------------------------
    private function _fetch_rss($kategori)
    {
        $feed       = $this->feeds[$kategori] ?? $this->feeds['terbaru'];
        $cache_file = RSS_CACHE_DIR . md5('cnn_' . $kategori) . '.json';

        if (file_exists($cache_file) && (time() - filemtime($cache_file)) < RSS_CACHE_TTL) {
            $cached = json_decode(file_get_contents($cache_file), true);
            if (!empty($cached)) return $cached;
        }

        $xml_str = $this->_http_get($feed['url']);
        if (!$xml_str) return [];

        // FIX PHP 8.5: Hapus libxml_use_internal_errors(), gunakan try-catch + @ operator
        try {
            $xml = @simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);
        } catch (\Exception $e) {
            return [];
        }

        if (!$xml || !isset($xml->channel->item)) return [];

        $items = [];
        foreach ($xml->channel->item as $item) {
            $ns    = $item->getNameSpaces(true);
            $media = isset($ns['media']) ? $item->children($ns['media']) : null;
            $thumb = '';

            if ($media && isset($media->thumbnail)) {
                $attr  = $media->thumbnail->attributes();
                $thumb = (string)($attr['url'] ?? '');
            }
            if (!$thumb && $media && isset($media->content)) {
                $attr  = $media->content->attributes();
                $thumb = (string)($attr['url'] ?? '');
            }
            if (!$thumb) {
                preg_match('/<img[^>]+src=["\']([^"\']+)["\']/', (string)$item->description, $m);
                $thumb = $m[1] ?? '';
            }

            $desc = strip_tags((string)$item->description);
            $desc = preg_replace('/\s+/', ' ', $desc);
            $desc = trim(substr($desc, 0, 200));

            $items[] = [
                'title'    => html_entity_decode((string)$item->title, ENT_QUOTES, 'UTF-8'),
                'link'     => (string)$item->link,
                'desc'     => $desc,
                'thumb'    => $thumb,
                'pubdate'  => (string)$item->pubDate,
                'category' => (string)($item->category ?? ''),
            ];
        }

        if (!empty($items)) {
            @file_put_contents($cache_file, json_encode($items));
        }

        return $items;
    }
}