<?php

/**
 * @file
 * Administration functions for the diy_meta_alternate module.
 *
 * These functions only need to be accessed from admin/structure/diy_meta_alternate, so we put them in a separate include file.
 */

/**
 * Create an overview form for sorting domains and other quick actions.
 */
function diy_meta_alternate_overview_form($form, &$form_state) {

  $form = array();

  $form['top'] = array(
    '#markup' => t('<p>The following domains have been created for your site.  The currently active domain <strong>is shown in boldface</strong>.  You may change the country codes in the beneath text field.</p><p><small>When changing settings here, you should clear the cache afterwards.</small></p>'),
  );
  // Cannot use domain_domains() here because we need to sort the output.
  $domains = array();
  // Set up the base query.
  $limit = variable_get('domain_list_size', DOMAIN_LIST_SIZE);

  $query = db_select('domain', 'd')
    ->fields('d', array('domain_id', 'sitename', 'subdomain', 'scheme', 'valid', 'weight', 'is_default'))
    ->orderBy('weight')
    ->extend('PagerDefault')
    ->limit($limit);
  // Get the domains.
  $result = $query->execute();
  while ($domain = $result->fetchAssoc()) {
    $domains[$domain['domain_id']] = domain_api($domain);
  }
  if (empty($domains)) {
    $form['error'] = array(
      '#markup' => t('No domains have been configured. <a href="!url">Add a new domain</a>.', array('!url' => url('admin/structure/domain/create'))),
    );
    return $form;
  }
  // Get the count of all domains, which may be paginated.
  $active_domain = domain_get_domain();
  $form['domain']['#tree'] = TRUE;
  $form['domainHeader'] = array(
    '#type' => 'value',
    '#value' => array(
        array('data' => t('Id')),
        array('data' => t('Name')),
        array('data' => t('Domain')),
        array('data' => t('Country Code')),
        array('data' => t('Enabled'))
    )
  );

  // Now build the form elements.
  foreach ($domains as $domain_id => $domain) {
    $form['domain'][$domain_id]['domain_id'] = array(
      '#type' => 'markup',
      '#markup' => check_plain($domain_id),
    );
    $form['domain'][$domain_id]['sitename'] = array(
      '#type' => 'markup',
      '#markup' => ($active_domain['domain_id'] == $domain_id) ? '<strong>' . check_plain($domain['sitename']) . '</strong>' : check_plain($domain['sitename']),
    );
    $form['domain'][$domain_id]['subdomain'] = array(
      '#type' => 'markup',
      '#markup' => ($active_domain['domain_id'] == $domain_id) ? '<strong>' . l($domain['subdomain'], domain_get_uri($domain)) . '</strong>' : l($domain['subdomain'], domain_get_uri($domain)),
    );
    $form['domain'][$domain_id]['country_code'] = array(
      '#type' => 'textfield',
      '#size' => 10,
      '#maxlength' => 8,
      '#required' => FALSE,
      '#default_value' => diy_meta_alternate_get_country_code_for_domain_id($domain_id),
    );
    $form['domain'][$domain_id]['enabled'] = array(
      '#type' => 'checkbox',
      '#required' => FALSE,
      '#default_value' => diy_meta_alternate_is_enabled_domain_id($domain_id),
    );
  }

  $form['view']['#tree'] = TRUE;
  $form['viewHeader'] = array(
    '#type' => 'value',
    '#value' => array(
      array('data' => 'id'),
      array('data' => 'name'),
      array('data' => 'url'),
      array('data' => 'enabled')
    )
  );
  $views = views_get_all_views();
  foreach ($views as $view) {

      $viewUrl = $view->get_url();

      if ($view->disabled || empty($view->display) || empty($viewUrl)) {
          continue;
      }

      $form['view'][$view->name]['view_id'] = array(
          '#type' => 'markup',
          '#markup' => $view->vid
      );
      $form['view'][$view->name]['name'] = array(
          '#type' => 'markup',
          '#markup' => $view->human_name
      );
      $form['view'][$view->name]['url'] = array(
          '#type' => 'markup',
          '#markup' => $viewUrl
      );
      $form['view'][$view->name]['enabled'] = array(
          '#type' => 'checkbox',
          '#default_value' => diy_meta_alternate_is_enabled_view_name($view->name)
      );
  }


  $form['pager'] = array(
    '#markup' => theme('pager'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  return $form;
}

/**
 * Validate handler for the domain overview form.
 */
function diy_meta_alternate_overview_form_validate($form, &$form_state) {
  $values = $form_state['values']['domain'];
  foreach ($values as $value) {
    if (!empty($value['country_code']) && !preg_match('#^[a-z]+$#', $value['country_code'])) {
      form_set_error('country_code', 'The country code '.htmlspecialchars($value['country_code']).' must match the pattern &quot;[a-z]+&quot;!');
    }
  }
}

/**
 * Submit handler for the domain overview form.
 */
function diy_meta_alternate_overview_form_submit($form, &$form_state) {
  if(isset($form_state['values']['domain'])) {
        $values = $form_state['values']['domain'];

        foreach ($values as $domain_id => $value) {
            $country_code = $value['country_code'];
            $enabled = $value['enabled'];

            if (empty($enabled)) {
                db_delete('diy_domain_countrycode')
                    ->condition('domain_id', $domain_id)
                    ->execute();
            } else {
                db_merge('diy_domain_countrycode')
                    ->fields(array('domain_id' => $domain_id, 'countrycode' => $country_code, 'enabled' => $enabled))
                    ->condition('domain_id', $domain_id)
                    ->execute();
            }
        }
    }

    if (isset($form_state['values']['view'])) {
    $values = $form_state['values']['view'];
    foreach($values as $view_id => $value) {
        $enabled = $value['enabled'];

        if (empty($enabled)) {
            db_delete('diy_domain_view')
                ->condition('view_id', $view_id)
                ->execute();
        } else {
            db_merge('diy_domain_view')
                ->fields(array('view_id' => $view_id, 'enabled' => $enabled))
                ->condition('view_id', $view_id)
                ->execute();
        }
    }
    }

  drupal_set_message(t('Country codes updated.') . ' ' . t('View settings saved.'));
}

/**
 * Theme the domain overview form.
 */
function theme_diy_meta_alternate_overview_form($variables) {
  $form = $variables['form'];
  if (!empty($form['error'])) {
    $output = drupal_render($form['error']);
    return $output;
  }
  // Add table javascript.
  drupal_add_js('misc/tableheader.js');

  $header = $form['domainHeader']['#value'];
  $output = '';
  $output .= drupal_render($form['top']);
  $rows = array();
  foreach (element_children($form['domain']) as $key) {
    $row = array();

    foreach (element_children($form['domain'][$key]) as $item) {
      $row[] = array(
        'data' => drupal_render($form['domain'][$key][$item]),
        'class' => array($item),
      );
    }

    $rows[] = $row;
  }
  $attributes = array(
    'id' => 'domains',
    'sticky' => TRUE,
  );
  $output .= theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => $attributes
  ));

  $rows = array();
  foreach (element_children($form['view']) as $key) {
    $row = array();

    foreach (element_children($form['view'][$key]) as $item) {
      $row[] = array(
        'data' => drupal_render($form['view'][$key][$item]),
        'class' => array($item),
      );
    }

    $rows[] = $row;
  }
  $attributes = array(
    'id' => 'views',
    'sticky' => TRUE,
  );
  $output .= '<p>'.t('The following marked views use link-alternate meta tags:').'</p>';
  $output .= theme('table', array(
    'header' => $form['viewHeader']['#value'],
    'rows' => $rows,
    'attributes' => $attributes
  ));
  $output .= drupal_render_children($form);
  return $output;
}
