<?php

namespace Ministra\Lib;

use Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2;
class Google
{
    public $gapi_name;
    public $gapi_url;
    public $cache_expire = 3600;
    public $gapi_module;
    public $gapi_field;
    private $db;
    private $gapi_arr;
    private $cache_table;
    public function __construct()
    {
        $this->db = \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d3507c2999d38573a0a0c91771d70af2::getInstance();
        $this->cache_table = 'gapi_cache_' . $this->gapi_name;
    }
    public function getData()
    {
        return $this->getDataFromDBCache();
    }
    private function getDataFromDBCache()
    {
        $content = $this->db->from($this->cache_table)->get()->first('content');
        $content = \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\d4c6e5add31a0fb7d2fbf48536f9ad3a(\base64_decode($content));
        if (\is_array($content)) {
            return $content;
        }
        return 0;
    }
    public function getDataFromGAPI()
    {
        $gapi_arr = [];
        $gapi_resp = \simplexml_load_file($this->gapi_url);
        if ($gapi_resp) {
            foreach ($gapi_resp->{$this->gapi_module}->{$this->gapi_field} as $item) {
                $new_item = [];
                foreach ($item as $field => $data) {
                    $new_item[$field] = (string) $data->attributes()->data;
                }
                $gapi_arr[] = $new_item;
            }
            $this->setDataDBCache($gapi_arr);
            return $gapi_arr;
        }
    }
    private function setDataDBCache($arr)
    {
        $content = \base64_encode(\Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\t17d3317196ac950e8b2dfe26f26e5a0c($arr));
        $result = $this->db->from($this->cache_table)->get();
        $crc = $result->get('crc');
        if (\md5($content) != $crc) {
            $data = ['content' => $content, 'updated' => 'NOW()', 'url' => $this->gapi_url, 'crc' => \md5($content)];
            if ($result->count() == 1) {
                $this->db->update($this->cache_table, $data);
            } else {
                $this->db->insert($this->cache_table, $data);
            }
        } else {
            if ($result->count() == 1) {
                $this->db->update($this->cache_table, ['updated' => 'NOW()']);
            }
        }
    }
}
