<?php

class AlexaService
{

    private $site;
    private $parser;
    private $apiUrl = 'http://data.alexa.com/data?cli=10&dat=snbamz&url=';
    private $alexaData = [
        'global_rank'        => -1,
        'country_name'       => '',
        'country_short_name' => '',
        'country_rank'       => -1,
        'backlink_count'     => -1,
        'top_countries'      => [],
        'top_keywords'       => []
    ];

    public function __construct($site, $parser)
    {
        $this->parser = $parser;
        $this->site = $site;
    }

    public function get()
    {
        $this->getAlexaInfo();
        $this->getCountryKeywordInfo();

        return $this->alexaData;

    }

    private function getAlexaInfo()
    {
        $data = file_get_contents_curl($this->apiUrl . $this->site);

        if (!$data) {
            return false;
        }

        $xml = new SimpleXMLElement($data);

        $popularity = $xml->xpath("//POPULARITY");
        $country = $xml->xpath("//COUNTRY");
        $links = $xml->xpath("//LINKSIN");

        if ($popularity) {
            $this->alexaData['global_rank'] = (string)$popularity[0]['TEXT'];
        }

        if ($links) {
            $this->alexaData['backlink_count'] = (string)$links[0]['NUM'];
        }

        if ($country) {
            $this->alexaData['country_short_name'] = (string)$country[0]['CODE'];
            $this->alexaData['country_name'] = (string)$country[0]['NAME'];
            $this->alexaData['country_rank'] = (string)$country[0]['RANK'];;
        }
    }

    private function getCountryKeywordInfo()
    {

        $data = file_get_contents_curl('http://www.alexa.com/siteinfo/' . $this->site);

        if (!$data) {
            return false;
        }

        $html = $this->parser->str_get_html($data);

        $countryRows = $html->find('#demographics_div_country_table tbody tr');

        if ($countryRows) {
            foreach ($countryRows as $index => $row) {
                if ($index > 0) {
                    if (isset($row->find('td')[0]->plaintext)
                        && isset($row->find('td')[1]->plaintext)
                        && isset($row->find('td')[2]->plaintext)
                    ) {

                        $countryName = trim(str_replace('&nbsp;', '', $row->find('td')[0]->plaintext));
                        $countryRatio = trim($row->find('td')[1]->plaintext);
                        $countryRank = trim($row->find('td')[2]->plaintext);
                        $shortCountryName = $row->find('td')[0]->find('.dynamic-icon')[0]->src;

                        preg_match('/flags\/(.*?)\.+\w+/is', $shortCountryName, $match);

                        if($match){
                            $shortCountryName = substr($match[1], 0, 2);
                        }else{
                            $shortCountryName = 'n/a';
                        }

                        //$shortCountryName = str_replace('.png', '', substr($shortCountryName, -6));
                        if ($countryName) {
                            $this->alexaData['top_countries'][] = [
                                'name'       => $countryName,
                                'short_name' => $shortCountryName,
                                'ratio'      => $countryRatio,
                                'rank'       => $countryRank
                            ];
                        }
                    }
                }
            }
        }

        $keywordRows = $html->find('#keywords_top_keywords_table tbody tr');

        if ($keywordRows) {
            foreach ($keywordRows as $index => $row) {
                if ($index > 0) {
                    if (isset($row->find('td')[0]->find('span')[1]->innertext) && isset($row->find('td')[1]->plaintext)) {
                        $keyword = trim($row->find('td')[0]->find('span')[1]->innertext);
                        $ratio = trim($row->find('td')[1]->plaintext);
                        if ($keyword) {
                            $this->alexaData['top_keywords'][] = [
                                'name'  => $keyword,
                                'ratio' => $ratio
                            ];
                        }
                    }
                }
            }
        }
    }
}