<?php

/**
 * @file
 * Displays Google AdSense ads on Drupal pages
 *
 * This is the core module of the AdSense package, with the Drupal hooks
 * and other administrative functions.
 */

define('ADSENSE_MANAGED_AD_BLOCK_DEFAULT', '');
define('ADSENSE_MANAGED_NUMBER_BLOCKS_DEFAULT', 3);

/**
 * Implements hook_menu().
 */
function adsense_managed_menu() {
  $items = array();

  $items['admin/config/services/adsense/managed'] = array(
    'title' => 'Managed Ads',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('adsense_managed_settings'),
    'access arguments'  => array('administer adsense'),
    'weight' => 1,
    'type' => MENU_LOCAL_TASK,
    'file' => 'adsense_managed.admin.inc',
  );

  return $items;
}

/**
 * Implements hook_block_info().
 */
function adsense_managed_block_info() {
  $blocks = array();
  $max = variable_get('adsense_managed_number_blocks', ADSENSE_MANAGED_NUMBER_BLOCKS_DEFAULT);
  for ($count=0 ; $count < $max ; $count++) {
    if ($ad = _adsense_managed_get_block_config($count)) {
      $title = $ad[0];
    }
    else {
      $title = t('AdSense: unconfigured') . ' ' . $count;
    }
    $blocks[$count] = array(
      'info' => $title,
      'cache' => DRUPAL_NO_CACHE,
    );
  }

  return $blocks;
}

/**
 * Implements hook_block_configure().
 */
function adsense_managed_block_configure($delta = '') {
  $ad = _adsense_managed_get_block_config($delta);
  foreach (adsense_ad_formats() as $format => $data) {
    $ad_list[$format] = $format . ' : ' . $data['desc'];
  }

  $form['info'] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
    '#default_value' => ($ad) ? $ad[0] : '',
    '#maxlength' => 64,
    '#description' => t('A brief description of your block. Used on the <a href="@overview">block overview page</a>.', array('@overview' => url('admin/structure/block'))),
    '#required' => TRUE,
    '#weight' => -19,
  );

  $form['ad_format'] = array(
    '#type' => 'select',
    '#title' => t('Ad format'),
    '#default_value' => ($ad) ? $ad[1] : '250x250',
    '#options' => $ad_list,
    '#description' => t('Select the ad dimensions you want for this block.'),
    '#required' => TRUE,
  );

  $form['ad_slot'] = array(
    '#type' => 'textfield',
    '#title' => t('Ad Slot ID'),
    '#default_value' => ($ad) ? $ad[2] : '',
    '#description' => t('This is the Ad Slot ID from your Google Adsense account, such as 0123456789.'),
    '#required' => TRUE,
  );

  $form['ad_align'] = array(
    '#type' => 'select',
    '#title' => t('Ad alignment'),
    '#default_value' => ($ad) ? $ad[3] : 'center',
    '#options' => array(
      '' => t('None'),
      'left' => t('Left'),
      'center' => t('Centered'),
      'right' => t('Right')
    ),
    '#description' => t('Select the horizontal alignment of the ad within the block.'),
  );

  return $form;
}

/**
 * Implements hook_block_save().
 */
function adsense_managed_block_save($delta = '', $edit = array()) {
  $data = implode(':', array(urlencode($edit['info']), $edit['ad_format'], $edit['ad_slot'], $edit['ad_align']));
  variable_set('adsense_managed_ad_block_' . $delta, $data);
}

/**
 * Implements hook_block_view().
 */
function adsense_managed_block_view($delta = '') {
  if (_adsense_page_match()) {
    $ad = _adsense_managed_get_block_config($delta);
    $block['content'] = ($ad) ? adsense_display(array('format' => $ad[1], 'slot' => $ad[2])) : t('AdSense unconfigured block. <a href=!url>Click to configure.</a>', array('!url' => url('admin/structure/block/manage/adsense_managed/' . $delta)));
    if (!empty($ad[3])) {
      $block['content'] = "<div style='text-align:${ad[3]}; display: block;'>${block['content']}</div>";
    }

    return $block;
  }
}

/**
 * Configuration of the provided block
 *
 * @param $delta
 *   block number
 * @return
 *   array with the block configuration or FALSE if no such block was found
 */
function _adsense_managed_get_block_config($delta = 0) {
  if ($data = variable_get('adsense_managed_ad_block_' . $delta, ADSENSE_MANAGED_AD_BLOCK_DEFAULT)) {
    $ad = explode(':', $data);
    $ad[0] = urldecode($ad[0]);
    return $ad;
  }

  return FALSE;
}

/**
 * Generates the AdSense ad
 *
 * @param $format
 *   format of the ad
 * @param $slot
 *   Slot Id for the AdSense ad
 * @return
 *   JavaScript that embeds the Google AdSense ad
 */
function _adsense_managed_get_ad($format, $client, $slot) {
  $ad = adsense_ad_formats($format);

  if (($ad === NULL) || empty($slot)) {
    $output = "";
  }
  elseif (variable_get('adsense_test_mode', ADSENSE_TEST_MODE_DEFAULT)) {
    $output = _adsense_format_box("client = ${client}<br />slot = ${slot}<br />width = ${ad['width']}<br />height = ${ad['height']}", $ad['width'], $ad['height']);
  }
  else {
    $secret = '';
    if (variable_get('adsense_secret_adtest', ADSENSE_SECRET_ADTEST_DEFAULT)) {
      $secret .= "google_adtest = 'on';\n";
    }
    if ($lang = variable_get('adsense_secret_language', ADSENSE_SECRET_LANGUAGE_DEFAULT)) {
      $secret .= "google_language = '$lang';";
    }

    $output = <<<MANAGED_TXT
<script type="text/javascript"><!--
google_ad_client = "ca-$client";
/* $format */
google_ad_slot = "$slot";
google_ad_width = ${ad['width']};
google_ad_height = ${ad['height']};
$secret
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
MANAGED_TXT;
  }

  return $output;
}
