<?php

namespace Ministra\Lib;

use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\U7b1423316998af8498523ab49b7053e6\Z0123335d0e9312494791d8030b626dff;
use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e;
class Widget
{
    public $db;
    public $widget_name;
    public $cache_table;
    public $cache_expire = 3600;
    public $rss_url;
    public $rss_fields = array();
    public $rss_atributes = array();
    public function __construct()
    {
        $this->db = \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::getInstance();
        $this->cache_table = 'rss_cache_' . $this->widget_name;
    }
    public function getData()
    {
        return $this->getDataFromDBCache();
    }
    private function getDataFromDBCache()
    {
        $content = $this->db->get($this->cache_table)->first('content');
        $content = \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\U7b1423316998af8498523ab49b7053e6\Z0123335d0e9312494791d8030b626dff::q8ed3cd8b3dd6b9da2bb2248a80d8859b(\base64_decode($content));
        if (\is_array($content)) {
            return $content;
        }
        return 0;
    }
    public function getDataFromRSS()
    {
        $rss_new = [];
        $rss = \simplexml_load_file($this->rss_url);
        if ($rss) {
            foreach ($rss->channel->item as $item) {
                $new_item = [];
                foreach ($this->rss_fields as $field) {
                    $new_item[$field] = (string) $item->{$field};
                }
                foreach ($this->rss_atributes as $atribute) {
                    $new_item['attributes_' . $atribute] = (string) $item->enclosure->attributes()->{$atribute};
                }
                $rss_new[] = $new_item;
            }
            $this->setDataDBCache($rss_new);
            return $rss_new;
        }
    }
    private function setDataDBCache($arr)
    {
        $content = \base64_encode(\Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\U7b1423316998af8498523ab49b7053e6\Z0123335d0e9312494791d8030b626dff::y08f4e0044959ef2ebbd1e3b0db7ed4ee($arr));
        $result = $this->db->get($this->cache_table);
        if (\md5($content) != $result->first('crc')) {
            $data = ['content' => $content, 'updated' => 'NOW()', 'url' => $this->rss_url, 'crc' => \md5($content)];
            if ($result->count() == 1) {
                $this->db->update($this->cache_table, $data);
            } else {
                $this->db->insert($this->cache_table, $data);
            }
        }
    }
}
