<?php

namespace Ministra\Lib;

use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\U7b1423316998af8498523ab49b7053e6\Z0123335d0e9312494791d8030b626dff;
use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e;
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\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::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\bd5c9022e9a9029209e5fd05775ea272\U7b1423316998af8498523ab49b7053e6\Z0123335d0e9312494791d8030b626dff::q8ed3cd8b3dd6b9da2bb2248a80d8859b(\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\bd5c9022e9a9029209e5fd05775ea272\U7b1423316998af8498523ab49b7053e6\Z0123335d0e9312494791d8030b626dff::y08f4e0044959ef2ebbd1e3b0db7ed4ee($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()']);
            }
        }
    }
}
