<?php

function bee_account_mail($op, $user_uid, $umid = NULL) {
	if (empty($user_uid)) {
		global $user;
		$user_uid = $user->uid;
	}
//	var_dump($op, $user_uid, $umid);
	switch ($op) {
		case 'view':
			$output = bee_account_mail_painel($user_uid);
			break;
		case 'edit':
			$output = (empty($umid)) ? '<h2>Add new email</h2>' : '<h2>Edit email</h2>';
			$output .= drupal_render(drupal_get_form('bee_account_mail_save_form', $user_uid, $umid));
			break;
		case 'login':
			$output = bee_account_mail_login($user_uid, $umid);
			break;
		case 'remove':
			$output = drupal_render(drupal_get_form('bee_account_mail_remove_form', $umid));
			break;
		default:
			$output = bee_account_mail_painel($user_uid);
			break;
	}
	return $output;
}

function bee_account_mail_painel($user_uid) {
	$output = "<h1>Email accounts</h1>";
	$emails = bee_account_get_emails_user($user_uid);
	if ($emails) {
		$output .= '<h2> Your emails </h2>';
		$output .= '<table class="table">';
		foreach ($emails as $value) {
			$output .= '<tr>';
			$output .= '<th>' . $value->mail . '</th>';
			$output .= '<td>' . l('access', 'manuka/mail/login/' . $user_uid . '/' . $value->umid, array('attributes' => array('target' => '_blank', 'class' => 'btn btn-success'))) . '</td>';
			$output .= '<td>' . l('edit', 'manuka/mail/edit/' . $user_uid . '/' . $value->umid, array('attributes' => array('class' => 'btn btn-info'))) . '</td>';
			$output .= '<td>' . l('remove', 'manuka/mail/remove/' . $user_uid . '/' . $value->umid, array('attributes' => array('class' => 'btn btn-danger'))) . '</td>';
			$output .= '</tr>';
		}
		$output .= '</table>';
	} else {
		$output .= bee_account_error_messages('You do not have email accounts, click "add email" to add new email account');
	}
	$output .= '<ul class="nav nav-pills">';
	$output .= '<li class="active">' . l('add email', 'manuka/mail/edit/') . '</li>';
	$output .= '</ul>';
	return $output;
}

function bee_account_mail_save_form($form, &$form_state, $user_uid, $umid = NULL) {
	drupal_set_title(t('Add new email'));
	if (empty($user_uid)) {
		return FALSE;
	}
	if (!empty($umid)) {
		drupal_set_title(t('Edit email'));
		$query = db_select('bee_account_user_mail', 'b')
				->condition('b.umid', $umid, '=')
				->condition('b.user_uid', $user_uid, '=')
				->fields('b', array('mail', 'umid'))
				->execute()
				->fetch();
		$form['umid'] = array(
			'#type' => 'hidden',
			'#value' => $query->umid,
		);
	}
	$form['mail'] = array(
		'#type' => 'textfield',
		'#title' => t('Email'),
		'#description' => t('Your email - example@manukahealth.ph or example@beehealth.ph'),
		'#required' => TRUE,
		'#default_value' => (!empty($query)) ? $query->mail : '',
	);
	$form['pass'] = array(
		'#type' => 'password_confirm',
		'#size' => 25,
		'#description' => t('Your password needs to be same as webmail'),
	);
	$form['button'] = array(
		'#type' => 'submit',
		'#value' => t('Save'),
	);
	$form['cancel'] = array(
		'#type' => 'submit',
		'#value' => t('Cancel'),
		'#submit' => array('')
	);
	$form['user_uid'] = array(
		'#type' => 'hidden',
		'#value' => $user_uid,
	);

	return $form;
}

function bee_account_mail_save_form_validate($form, $form_state) {
	$mail = strtolower($form_state['values']['mail']);
	$umid = (!empty($form_state['values']['umid'])) ? $form_state['values']['umid'] : NULL;
	$user_uid = $form_state['values']['user_uid'];
	$allowed = array(BEE_ACCOUNT_BEEHEALTHY_DOMAIN, BEE_ACCOUNT_MANUKA_DOMAIN);

	if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
		$domain = array_pop(explode('@', $mail));
		if (!in_array($domain, $allowed)) {
			form_set_error('mail', 'Invalid domain (system accepts only ' . BEE_ACCOUNT_BEEHEALTHY_DOMAIN . ' and ' . BEE_ACCOUNT_MANUKA_DOMAIN . '). Please redigit your email address');
		}
	}
	if (bee_account_mail_exists($mail)) {
		if (!$umid) {
			form_set_error('mail', 'This email already exists');
		}
		if (!bee_account_mail_owner($mail, $user_uid)) {
			form_set_error('mail', 'This email already exists');
		}
	}
}

function bee_account_mail_save_form_submit($form, $form_state) {
	$umid = (!empty($form_state['values']['umid'])) ? $form_state['values']['umid'] : NULL;
	$user_uid = $form_state['values']['user_uid'];
	$mail = strtolower($form_state['values']['mail']);
	if (!empty($umid)) {
		$mail_edit = db_update('bee_account_user_mail')
				->fields(array(
					'mail' => $mail,
					'pass' => $form_state['values']['pass'],
					'user_uid' => $user_uid,
				))
				->condition('user_uid', $user_uid, '=')
				->condition('umid', $umid, 'like');
		$mail_edit->execute();
	} else {
		$mail_save = db_insert('bee_account_user_mail')
				->fields(array(
			'mail' => $mail,
			'pass' => $form_state['values']['pass'],
			'user_uid' => $user_uid,
		));
		$mail_save->execute();
	}
	drupal_set_message('Successfully');
	drupal_goto('manuka/mail/view/' . $user_uid);
}

/*
 * Remove user email
 */

function bee_account_mail_remove_form($form, &$form_state, $umid) {
	$form['umid'] = array(
		'#type' => 'hidden',
		'#value' => $umid,
	);
	$form['question'] = array(
		'#markup' => '<h3>' . t('Are you sure you want to delete this email?') . '</h3>'
	);
	return confirm_form($form, t('Are you sure you want to delete this email?'), 'manuka/mail', '<p>' . t('You will just remove show email account, your email will not removed.') . '</p>', t('Delete'), t('Cancel'));
}

function bee_account_mail_remove_form_validate($form, &$form_state) {
	global $user;
	$umid = $form_state['values']['umid'];
	if (!empty($umid)) {
		if (!bee_account_umid_owner($umid, $user->uid)) {
			drupal_set_message('This mail doesn\'t belong you', 'error');
			drupal_goto('manuka/mail/view');
		}
	} else {
		drupal_set_message('Error, please try again', 'error');
		drupal_goto('manuka/mail/view');
	}
}

function bee_account_mail_remove_form_submit($form, &$form_state) {
	$umid = $form_state['values']['umid'];
	db_delete('bee_account_user_mail')
			->condition('umid', $umid, '=')
			->execute();
	drupal_set_message('Successfully');
	drupal_goto('manuka/mail/view');
}

function bee_account_mail_login($user_uid, $umid) {
	if ($user_uid && $umid) {
		$db_query = db_select('bee_account_user_mail', 'b')
				->condition('b.umid', $umid, '=')
				->condition('b.user_uid', $user_uid, '=')
				->fields('b')
				->execute()
				->fetchAll();
		if ($db_query) {
			foreach ($db_query as $value) {
				$user_mail = $value->mail;
				$user_pass = $value->pass;
			}
			bee_account_login_roundcube($user_mail, $user_pass);
		} else {
			drupal_set_message('email account not found');
			drupal_goto('manuka/mail/view');
		}
	}
}

/*
 * Return if email already exists
 */

function bee_account_mail_exists($mail) {
	$exists = FALSE;
	$db_query = db_select('bee_account_user_mail', 'b')
			->condition('b.mail', $mail, 'like')
			->fields('b', array('mail'))
			->execute()
			->fetch();
	if ($db_query) {
		$exists = TRUE;
	}
	return $exists;
}

/*
 * Return if user is owner this mail
 */

function bee_account_mail_owner($mail, $user_uid) {
	$is_owner = FALSE;
	$db_query = db_select('bee_account_user_mail', 'b')
			->condition('b.mail', $mail, 'like')
			->condition('b.user_uid', $user_uid, '=')
			->fields('b', array('mail'))
			->execute()
			->fetch();
	if ($db_query) {
		$is_owner = TRUE;
	}
	return $is_owner;
}

function bee_account_umid_owner($umid, $user_uid) {
	$is_owner = FALSE;
	$db_query = db_select('bee_account_user_mail', 'b')
			->condition('b.umid', $umid, '=')
			->condition('b.user_uid', $user_uid, '=')
			->fields('b', array('mail'))
			->execute()
			->fetch();
	if ($db_query) {
		$is_owner = TRUE;
	}
	return $is_owner;
}

function bee_account_login_roundcube($user, $password) {
	//external class
	require_once drupal_get_path('module', 'bee_account') . '/external/roundCube/RoundcubeLogin.class.php';
# Create RC login object.
# Note: The first parameter is the URL-path of the RC inst.,
#       NOT the file-system path
# e.g. http://host.com/path/to/roundcube/ --> "/path/to/roundcube"
	$rcl = new RoundcubeLogin("/roundcube/", TRUE);
	try {

		# If not, try to login and simply redirect on success
		$rcl->login($user, $password);

		if ($rcl->isLoggedIn())
			$rcl->redirect();

		# If the login fails, display an error message
		die("ERROR: Login failed due to a wrong user/pass combination.");
	} catch (RoundcubeLoginException $ex) {
		echo "ERROR: Technical problem, " . $ex->getMessage();
		$rcl->dumpDebugStack();
	}
}

function bee_account_get_emails_user($user_uid) {
	$query = db_select('bee_account_user_mail', 'b')
			->condition('b.user_uid', $user_uid, '=')
			->fields('b')
			->execute()
			->fetchAll();
	return $query;
}
