<?php defined('COT_CODE') or die('Wrong URL');
/* ====================
[BEGIN_COT_EXT]
Hooks=tools
[END_COT_EXT]
==================== */

require_once cot_incfile('hybridauth', 'plug');

$provider = cot_import('provider', 'G', 'TXT');
$uid = cot_import('uid' , 'G', 'INT');
$fromprofile = cot_import('fromprofile' , 'G', 'INT');

if($uid > 0 && !empty($provider)) {
  $urr = $db->query("SELECT * FROM $db_users WHERE user_id=".$uid.' LIMIT 1')->fetch();

	$provider_code = strtolower($provider);
	$field_name = "user_{$provider_code}_id";

	if ($urr['user_id'] > 0 && !empty($urr[$field_name]))
	{
		// Erase the link
		$db->update($db_users, array($field_name => ''), "user_id=?", $urr['user_id']);
		// Logout from account
		$hybridauth = new Hybrid_Auth($hybridauth_config);
		$adapter = $hybridauth->authenticate($provider);
		$adapter->logout();

    cot_message('У пользователя '.$urr['user_name'].' успешно отвязан '.$provider);
	}
  cot_redirect((($fromprofile && $urr['user_id'] > 0) ? cot_url('users', 'm=edit&id='.$urr['user_id'], '', true) : cot_url('admin', 'm=other&p=hybridauth', '', true)));
}

$tt = new XTemplate(cot_tplfile('hybridauth.tools', 'plug'));

// Sync extra fields if necessary
foreach ($hybridauth_config['providers'] as $key => $val)
{
	$name = strtolower($key);
	if ($val['enabled'])
	{
		$fields = array("user_{$name}_id", "user_{$name}_url");
		foreach ($fields as $field_name)
		{
			if (!$db->fieldExists($db_users, $field_name))
			{
				// Create a missing user field
				$db->query("ALTER TABLE `$db_users` ADD COLUMN `$field_name` VARCHAR(96)");
				cot_message($L['Added'] . " `$db_users`.`$field_name`");
			}
		}

    $tt->assign(array(
    	'HYBRIDAUTH_TYPE' => $name
    ));
    $usrs = $db->query("SELECT * FROM $db_users WHERE user_".$name."_id!=''")->fetchAll();
    $jj=0;
    foreach($usrs as $urr) {
      $jj++;
      $tt->assign(array(
      	'USER_ROW_NAME' => $urr['user_name'],
        'USER_ROW_URL' => cot_url('users', 'm=details&id='.$urr['user_id'].'&u='.$urr['user_name']),
        'USER_ROW_SOCIAL' => $urr['user_'.$name.'_url'],
        'USER_ROW_UNLINK' => cot_url('admin', 'm=other&p=hybridauth&a=unlink&provider='.$name.'&uid='.$urr['user_id']),
      ));
      $tt->parse("MAIN.SOCIAL_ROW.USERS_ROW");
    }
    if($jj==0) $tt->parse("MAIN.SOCIAL_ROW.USERS_EMPTY");
    $tt->parse("MAIN.SOCIAL_ROW");
	}
}

cot_display_messages($tt);

// Display the main page

$tt->assign(array(
	'HYBRIDAUTH_URL'    => cot_url('admin', 'm=other&p=hybridauth'),
	'HYBRIDAUTH_ACTION' => cot_url('admin', 'm=other&p=hybridauth&a=send')
));

$tt->parse();
$plugin_body = $tt->text('MAIN');
