<?php

namespace Ministra\Lib;

use Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2;
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\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::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\w13ec15f0067ea75861e61e27c990e4ba\d4c6e5add31a0fb7d2fbf48536f9ad3a(\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\w13ec15f0067ea75861e61e27c990e4ba\t17d3317196ac950e8b2dfe26f26e5a0c($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);
            }
        }
    }
}
