<?php

/**
 * @file
 *
 */

function incubator_social_incubator_settings_menu() {
  return array(
    'description' => 'Settings for social site integration.',
    'title' => 'Social Integration',
  );
}

function incubator_social_incubator_settings() {
  
  $form = $form_state = array();
  
  // =============================
  // SHARING
  
  $form['sharing'] = array(
    '#type' => 'fieldset',
    '#title' => t('Sharing'),
  );
  
  // Social widgets: Socialite.js
  $form['sharing']['incubator_social_widgets'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use social sharing buttons'),
    '#description' => t('Enables buttons for Facebook like, Twitter share, Google +1.'),
    '#default_value' => variable_get('incubator_social_widgets', TRUE),
  );
  $form['sharing']['incubator_social_widgets_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Widget settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#states' => array(
      'invisible' => array(
        ':input[name="incubator_social_widgets"]' => array('checked' => FALSE),
      ),
    ),
  );
  $form['sharing']['incubator_social_widgets_settings']['incubator_social_widgets_node_full'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show social buttons on full node display'),
    '#default_value' => variable_get('incubator_social_widgets_node_full', TRUE),
  );
  $form['sharing']['incubator_social_widgets_settings']['incubator_social_widgets_node_teaser'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show social buttons on teasers'),
    '#default_value' => variable_get('incubator_social_widgets_node_teaser', TRUE),
  );
  $form['sharing']['incubator_social_widgets_settings']['incubator_social_widgets_services'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Buttons to implement'),
    '#options' => array(
      'tw' => t('Twitter'),
      'go' => t('Google+'),
      'li' => t('LinkedIn'),
      'fb' => t('Facebook'),
    ),
    '#default_value' => variable_get('incubator_social_widgets_services', array('tw', 'go', 'fb')),
  );
  
  
  // Markerly
  $markerly_exists = module_exists('markerly');
  $form['sharing']['incubator_social_markerly'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use Markerly micro-sharing (experimental)'),
    '#description' => t('Markerly is a service which allows people to share text selections and images with social networks.'),
    '#default_value' => $markerly_exists,
  );
  $form['sharing']['incubator_social_markerly_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Markerly settings'),
    '#collapsible' => $markerly_exists,
    '#collapsed' => $markerly_exists,
    '#states' => array(
      'invisible' => array(
        ':input[name="incubator_social_markerly"]' => array('checked' => FALSE),
      ),
    ),
  );
  if (module_exists('markerly')) {
    module_load_include('inc', 'markerly', 'markerly.admin');
    $form['sharing']['incubator_social_markerly_settings'] += markerly_settings();
    $form['sharing']['incubator_social_markerly_settings']['markerly_settings']['#title'] = t('Advanced');
    $form['sharing']['incubator_social_markerly_settings']['markerly_settings']['#collapsed'] = TRUE;
    unset ($form['sharing']['incubator_social_markerly_settings']['#description']);
    unset ($form['sharing']['incubator_social_markerly_settings']['#submit']);
    unset ($form['sharing']['incubator_social_markerly_settings']['submit']);
  }
  else {
    $form['sharing']['incubator_social_markerly_settings']['explanation'] = array(
      '#markup' => t('Save the configuration to see all Markerly settings.'),
    );
  }
  
  // =============================
  // SOCIAL ACCOUNTS
  
//  $form['incubator_social_accounts'] = array(
//    '#type' => 'fieldset',
//    '#title' => t('Accounts'),
//    '#description' => t('If your organization maintains public accounts on '
//        . 'social media services, enter the information here.'),
//    '#collapsible' => FALSE,
//    '#collapsed' => FALSE,
//  );
  
  // =============================
  // SOCIAL LOGIN
  
  $form['social_login'] = array(
    '#type' => 'fieldset',
    '#title' => t('Social login'),
  );
  $hybridauth_exists = module_exists('hybridauth');
  $form['social_login']['incubator_social_hybridauth'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable login through social services'),
    '#description' => t('Allow people to login to your site using social network accounts.') . 
      ($hybridauth_exists ? '' : '<br/><b>' . t('Note that this requires advanced setup before it will work.') . '</b>'),
    '#default_value' => $hybridauth_exists,
  );
  $form['social_login']['incubator_social_hybridauth_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Social login settings'),
    '#collapsible' => $hybridauth_exists,
    '#collapsed' => $hybridauth_exists,
    '#states' => array(
      'invisible' => array(
        ':input[name="incubator_social_hybridauth"]' => array('checked' => FALSE),
      ),
    ),
  );
  
  $form['social_login']['incubator_social_hybridauth_settings']['explanation'] = array(
    '#markup' => module_exists('hybridauth') ? 
      t('Social login is handled by the Hybridauth library; the full settings are available at !link', array('!link' => l('/admin/config/people/hybridauth', '/admin/config/people/hybridauth'))) :
      t('Save the configuration to see social login settings.'),
  );

  if (module_exists('hybridauth')) {
    module_load_include('inc', 'hybridauth', 'hybridauth.admin');
  
    $core_settings = array(
      USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'),
      USER_REGISTER_VISITORS => t('Visitors'),
      USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'),
    );
    $form['social_login']['incubator_social_hybridauth_settings']['hybridauth_register'] = array(
      '#type' => 'radios',
      '#title' => t('Who can register accounts?'),
      '#options' => array(
        0 => t('Follow core') . ': ' . $core_settings[variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)],
        1 => t('Visitors'),
        2 => t('Visitors, but administrator approval is required'),
      ),
      '#description' => t('Select who can register accounts through HybridAuth.') . ' '
        . t('The core settings are available at <a href="!link">Account settings</a>.',
          array('!link' => url('admin/config/people/accounts'))),
      '#default_value' => variable_get('hybridauth_register', 0),
    );
    $core_settings = array(
      0 => t("Don't require e-mail verification"),
      1 => t('Require e-mail verification'),
    );
    $form['social_login']['incubator_social_hybridauth_settings']['hybridauth_email_verification'] = array(
      '#type' => 'radios',
      '#title' => t('E-mail verification'),
      '#options' => array(
        0 => t('Follow core') . ': ' . $core_settings[variable_get('user_email_verification', TRUE)],
        1 => t('Require e-mail verification'),
        2 => t("Don't require e-mail verification"),
      ),
      '#description' => t('Select how to handle not verified e-mail addresses (authentication provider gives non-verified e-mail address).') . ' '
        . t('The core settings are available at <a href="!link">Account settings</a>.',
          array('!link' => url('admin/config/people/accounts'))),
      '#default_value' => variable_get('hybridauth_email_verification', 0),
    );
    foreach(incubator_social_preferred_providers() as $provider_id) {
      $keys_form = hybridauth_admin_provider_settings($form, $form_state, $provider_id);
      $enabled = variable_get("hybridauth_provider_{$provider_id}_enabled", FALSE);
      $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id] = $keys_form['keys'];
      $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id]['#title'] = $provider_id . ($enabled ? ' <span class="provider-enabled">' . t('Enabled') . '</span>' : '');
      $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id]['#collapsible'] = TRUE;
      $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id]['#collapsed'] = TRUE;
    }
  }
  
  $form = system_settings_form($form);
  $form['#submit'][] = 'incubator_social_incubator_settings_submit';
  drupal_add_css('.provider-enabled{background-color:green;color:white;padding:1px 5px;}', array('type' => 'inline'));
  
  return $form;
  
}

function incubator_social_incubator_settings_submit(&$form, &$form_state) {

  // SHARING
  
  variable_set('incubator_social_widgets_services', array_filter($form_state['values']['incubator_social_widgets_services']));
  
  if (!empty($form_state['values']['incubator_social_markerly'])) {
    if (!module_exists('markerly')) {
      module_enable(array('markerly'));
      $settings = variable_get('markerly_settings', array());
      $settings += array(
        'services' => 'facebook,twitter,email,pinterest,googleplus',
        'image_sharing' => TRUE,
        'image_sharing_exclude' => 'node-teaser',
        'image_sharing_position' => 'nw',
        'image_services' => 'facebook,twitter,email,pinterest',
        'copy_link' => '{{link}}',
        'copy_link_sharing' => TRUE,
        'text_sharing' => TRUE,
        'container_restrict' => '.block-system-main',
        'sidebar_sharing' => TRUE,
      );
      variable_set('markerly_settings', $settings);
    }
    else {
      variable_set('markerly_settings', $form_state['values']['markerly_settings']);
    }
  }
  else {
    if (module_exists('markerly')) {
      module_disable(array('markerly'));
    }
  }  
  
  // SOCIAL LOGIN
  
  if (!empty($form_state['values']['incubator_social_hybridauth'])) {
    if (!module_exists('hybridauth')) {
      // Enable the module if it is not already enabled
      module_enable(array('hybridauth'));
      
      // Add hybridauth permissions for anonymous and authenticated users
      if (!variable_get('incubator_site_disabled', TRUE)) {
        user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('use hybridauth'));
      }
       user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array('use hybridauth'));

      // Limit hybridauth facebook scope requested
      variable_set('hybridauth_provider_Facebook_scope', array('email' => 'email'));

      // Set hybridauth on all forms
      variable_set('hybridauth_forms', array(
        'user_login' => 'user_login',
        'user_login_block' => 'user_login_block',
        'user_register_form' => 'user_register_form',
        'comment_form' => 'comment_form',
      ));

      // Remove hybridauth identities field from user profile display
      $user_settings = variable_get('field_bundle_settings_user__user', array());
      $user_settings['extra_fields']['display']['hybridauth_identities']['default']['visible'] = 0;
      $user_settings['extra_fields']['display']['hybridauth_identities']['default']['weight'] = 0;
      variable_set('field_bundle_settings_user__user', $user_settings);

    }
    else {
      // if Hybridauth is already enabled, set the settings
      foreach(incubator_social_preferred_providers() as $provider_id) {
        if ($form_state['values']["hybridauth_provider_{$provider_id}_keys_secret"] && (
            $form_state['values']["hybridauth_provider_{$provider_id}_keys_id"] ||
            $form_state['values']["hybridauth_provider_{$provider_id}_keys_key"]
          )) {
          variable_set("hybridauth_provider_{$provider_id}_enabled", TRUE);
        }
        else {
          variable_set("hybridauth_provider_{$provider_id}_enabled", FALSE);
        }
      }
    }
  }
  else {
    if (module_exists('hybridauth')) {
      module_disable(array('hybridauth'));
    }
  }
  
  drupal_flush_all_caches();
  
}
