<?php

//  /usr/bin/docker exec aklemp_fpm_1 php /vhosts/vetandlife.ru/wp-content/themes/vij/src/yametrica.php

require '/vhosts/vetandlife.ru/wp-load.php';

define('YA_TOKEN', 'y0_AgAAAAA5ZMbXAAjnxwAAAADXZGKqufBi9E2_TnG4n9l_K0OjYOAukmk');
define('YA_COUNTER', '56480275');

vij_top();



function vij_top(){

    $items = vij_top_links ();

    if (is_array($items)){

        generate_block('top', 'blocks/top.php',['items' => $items]);
        generate_block('top_mob', 'blocks/top.php',['items' => $items, 'subclass' => 'mob-lite']);

    }

}




function vij_top_links (){

    $block_limit = 3;
    
    $resfile = '/vhosts/vetandlife.ru/wp-content/themes/vij/src/popular.json';

    //if (file_exists($resfile)) {
    //    $result = file_get_contents($resfile);
   // }
   // else {
        $result =  getstat(YA_TOKEN, YA_COUNTER);
        file_put_contents($resfile, $result);
    //}    

    $links = [];
    $items = json_decode($result, true);
    $nn = 0;

    foreach ($items['data'] as $item) {

        $link =  $item['dimensions'][2]['name'];
        $link = trim($link, '/');

        if (strpos($link, 'category') !== false){
            continue;
        }    
        
        $find_slug = strrpos($link, '/');
        
        if ($find_slug > 0){
            $slug = substr($link, $find_slug+ 1);
            $news = db_get("  
                SELECT ID, post_title, post_parent, post_type
                FROM `wp_posts`
                WHERE `post_name`  = '$slug'
                LIMIT 1
            ;");
           
            if ( isset($news['ID']) and !isset( $links[$news['ID']])) {
                $nn ++;
                $links[$news['ID']] = [
                    'title' => $news['post_title'],
                    'link' => $link
                ];

                if ($nn == $block_limit)
                    break;
            }

        }
    }

    return $links;


}


function getstat($token, $counter){


    return getData(
        'https://api-metrika.yandex.ru/stat/v1/data?preset=popular&metrics=ym:pv:pageviews&id='.$counter,
        ["Authorization: OAuth  $token"]
    );

}

function getData($url,$headers) {
    $handle=curl_init();
    curl_setopt($handle, CURLOPT_URL, $url);
    curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    $response=curl_exec($handle);
    $code=curl_getinfo($handle, CURLINFO_HTTP_CODE);
    return $response;
  }


  function generate_block($name, $file, $data){


    $blockfile = BASE_VIJ.$file;


    if (!file_exists($blockfile))
        return false;

    $cachefile = VIJ_CACHE.$name.'.html';

    extract($data);

    ob_start();
    include $blockfile; 
    $html = ob_get_contents();
    ob_end_clean();


    return file_put_contents($cachefile, $html);


}  

function generate_token(){

    #generate code
    //https://oauth.yandex.ru/authorize?response_type=code&client_id=0803497581984722a1f8aa194d38bfde&redirect_uri=https%3A%2F%2Foauth.yandex.ru%2Fverification_code 


    $username = 'info@vetandlife.ru';
    $password = 'B9c8P6y9';
    $client_id = '0803497581984722a1f8aa194d38bfde';
    $client_secret = 'd6902633d07b4ed482e7223d1aa3bdf3';
    $code = '8190284';


    $url = 'https://oauth.yandex.ru/token';
    $data = "grant_type=authorization_code&code=$code&client_id=$client_id&client_secret=$client_secret";
    $headers = ['Content-type: application/x-www-form-urlencoded'];

    $handle=curl_init();
    curl_setopt($handle, CURLOPT_URL, $url);
    curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($handle, CURLOPT_POST, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
    $response=curl_exec($handle);

    return json_decode($response,true);



}


//array(4) { ["access_token"]=> string(58) "y0_AgAAAAA5ZMbXAAjnxwAAAADXZGKqufBi9E2_TnG4n9l_K0OjYOAukmk" ["expires_in"]=> int(31532257) ["refresh_token"]=> string(120) "1:pBCp9CrVyyFSQmoa:HXgsmThJOvibXWlSq8qPotsoWQbScGfmaPGsXH-LLfujLtIkyCVtex7uWJwcjnUJeVgxA-K28_IB5Q:kXJn4Tlxx49jZAx9iDQgzg" ["token_type"]=> string(6) "bearer" }




