<?php

/**
 * @file
 * Provide a counter of visits per page in the site this module counter_visits_page.
*/

/**
 * Implements hook_init().
*/
function counter_visits_page_init() {
    global $user;
    $path = current_path();
    $result = get_counter_page($path);
    $rol = reset($user->roles);
    $argsm = explode('/', $path);
    $path_first_pos = reset($argsm);

    if (db_table_exists('counter_visits_page')) {

        if ($rol == 'anonymous user' && !path_is_admin($path) && $path_first_pos !== 'sites') {
            if ($result) {
                db_update('counter_visits_page')
                ->fields(array('counter' => ++$result['counter']))
                ->condition('cid', $result['cid'], '=')
                ->execute();
            } else {
                db_insert('counter_visits_page')
                ->fields(array(
                'counter' => 1,
                'path' => $path,
                'date' => date('d/m/y'),
                ))
                ->execute();
            }
        }
    }    
}

function get_counter_page($path) {

    $result = '';

    if (db_table_exists('counter_visits_page')) {
        $result = db_select('counter_visits_page', 'c')
        ->fields('c')
        ->condition('path', $path,'=')
        ->execute()
        ->fetchAssoc();
    }

    return $result;
}

/**
 * Implements hook_block_info().
*/
function counter_visits_page_block_info() {
    $blocks['counter_visits_page'] = array(
      'info' => t('Counter Visits Page'),
    );
    return $blocks;
}
  
/**
 * Implements hook_block_view().
*/
function counter_visits_page_block_view($delta = '') {
    $result = get_counter_page(current_path());
    $block = array();
    switch ($delta) {
        case 'counter_visits_page':
        $block['subject'] = t('Visitas :');
        $block['content'] = $result['counter'];
        break;
    }
    return $block;
}
