<?php

function bee_account_payroll($op, $user = NULL) {
	switch ($op) {
		case 'add':
			$output = drupal_render(drupal_get_form('bee_account_payroll_form'));
			break;
		case 'woutpay':
			$output = bee_account_get_employeers_actives_wout_payroll(BEE_ACCOUNT_PAYROLL_DAYS_TIME);
			break;
		default:
			$output = drupal_render(drupal_get_form('bee_account_payroll_form'));
			break;
	}
	return $output;
}

function bee_account_payroll_form($form, &$form_state) {
	$form['payroll_files'] = array(
		'#type' => 'mfw_managed_file',
		'#title' => t('Files'),
		'#size' => 22,
		'#upload_validators' => array('file_validate_extensions' => array('pdf')),
	);
	$form['actions'] = array(
		'#type' => 'fieldset',
		'#weight' => 5,
		'#collapsible' => TRUE,
		'#collapsed' => FALSE,
		'#attributes' => array(
			'class' => array('form-actions'),
	));
	$form['actions']['button'] = array(
		'#type' => 'submit',
		'#value' => t('Upload'),
		'#attributes' => array(
			'class' => array('btn btn-primary'),
	));
	$form['actions']['cancel'] = array(
		'#type' => 'submit',
		'#value' => t('Cancel'),
		'#submit' => array(''),
		'#attributes' => array(
			'class' => array('btn'),
	));
	return $form;
}

function bee_account_payroll_form_validate($form, &$form_state) {
	$filesName = $_FILES['files']['name']['payroll_files'];
	if (!$filesName) {
		return FALSE;
	}
	foreach ($filesName as $file) {
		$fileInfo = pathinfo($file);
		if (!bee_account_payroll_validate_file_ext($fileInfo['extension'])) {
			drupal_set_message('The files extension needs to be PDF', 'error');
			return FALSE;
		}
	}
}

function bee_account_payroll_form_submit($form, &$form_state) {
	$year = date('Y');
	$month = date('m');
	if ($month && $year) {
		$folderYear = BEE_ACCOUNT_PAYROLL_FOLDER_BASE . $year;
		$folderMonth = "$folderYear/$month";
		if (!file_prepare_directory($folderMonth)) {
			if (!file_prepare_directory($folderYear)) {
				if (!drupal_mkdir($folderYear) || !drupal_mkdir($folderMonth)) {
					return FALSE;
				}
			} else {
				if (!drupal_mkdir($folderMonth)) {
					return FALSE;
				}
			}
		}
		$filesCount = count($_FILES['files']['name']['payroll_files']);
		for ($i = 0; $i < $filesCount; $i++) {
			$files[] = mfw_file_save_upload('payroll_files', $i, NULL, $folderMonth, FILE_EXISTS_REPLACE);
		}
		if (is_array($files)) {
			bee_account_payroll_save_files($files);
		}
	}
}

function bee_account_payroll_save_files($files) {
	$alreadyExists = array();
	$success = array();
	$filesError = array();
	foreach ($files as $file) {
		if (bee_account_get_fids($file->fid)) {
			$alreadyExists[] = $file->filename;
			$fileBasicInfo = bee_account_get_info_file($file->filename);
			continue;
		}
		$fileBasicInfo = bee_account_get_info_file($file->filename);
		$timestamp = strtotime($fileBasicInfo[2] . '/' . $fileBasicInfo[3] . '/' . $fileBasicInfo[1]);
		if ($fileBasicInfo) {
			$mail_save = db_insert('bee_account_payroll_files')
					->fields(array(
				'uri' => $file->uri,
				'date' => (!empty($timestamp)) ? $timestamp : $file->timestamp,
				'uploaded' => $file->timestamp,
				'bid' => $fileBasicInfo[0],
				'fid' => $file->fid,
			));
			$mail_save->execute();
			$success[] = $file->filename;
		} else {
			$filesError[] = $file->filename;
		}
	}
// messages
	if (count($filesError)) {
		drupal_set_message(count($filesError) . ' file(s) cannot be uploaded.  Filenames: ' . implode($filesError, ', '), 'error');
	}
	if (count($success)) {
		drupal_set_message(count($success) . ' files uploaded sucessfully');
	}
	if (count($alreadyExists)) {
		drupal_set_message(count($alreadyExists) . ' file(s) already exists, and they were just updated.');
	}
}

function bee_account_get_info_file($filename = '') {
	if (!empty($filename)) {
		$nameOnly = preg_replace("/\\.[^.\\s]{3,4}$/", "", $filename);
		$fileInfo = explode('_', $nameOnly);
		if (4 <= count($fileInfo)) {
			$fileDate = strtotime($fileInfo[1] . '/' . $fileInfo[2] . '/' . $fileInfo[3]);
			$result = $fileInfo;
			if (!bee_account_is_bid_exists($fileInfo[0])) {
				drupal_set_message('The system does not have the follow employeer id: ' . $fileInfo[0], 'warning');
			}
			if (empty($fileDate)) {
				drupal_set_message('Somethings as wrong with the following filename date: ' . $filename, 'error');
				$result = FALSE;
			}
			if (strtotime('+5 days', time()) <= $fileDate) {
				drupal_set_message('The following file appears to be more NEWER than the system date (5 or more days):  ' . $filename, 'error');
				$result = FALSE;
			}
			if (strtotime('-1 year', time()) >= $fileDate) {
				drupal_set_message('The following file appears to be more OLDER than the system date (1 or more years): ' . $filename, 'error');
				$result = FALSE;
			}
			return $result;
		}
	} else {
		return FALSE;
	}
}

function bee_account_payroll_validate_file_ext($fileExt) {
	$allowedFiles = array('pdf');
	if (in_array(strtolower($fileExt), $allowedFiles)) {
		return TRUE;
	}
	return FALSE;
}

function bee_account_get_fids($fid) {
	$query = db_select('bee_account_payroll_files', 'p')
			->fields('p', array('fid'))
			->condition('p.fid', $fid, '=');
	return $query->execute()->fetch();
}

function bee_account_employeers_without_payroll($days) {
	$lastDate = strtotime("-$days days", time());
	if (!$lastDate) {
		return FALSE;
	}
	$query = db_select('bee_account_user_profile', 'up');
	$query->leftJoin('bee_account_payroll_files', 'pl', 'up.bid = pl.bid');
	$query->fields('pl', array('date'))
			->fields('up', array('bid', 'name', 'photo', 'position', 'uid'))
			->condition('up.position', BEE_ACCOUNT_POSITION_INACTIVE, '!=');
	$newCond = db_or();
	$newCond->condition('pl.date', $lastDate, '<')
			->isNull('pl.date');
	$query->condition($newCond);
	return $query->execute()->fetchAll();
}

function bee_account_get_employeers_actives_wout_payroll($days) {
	$output = '';
	$employers = bee_account_employeers_without_payroll($days);
	if ($employers) {
		$module_path = drupal_get_path('module', 'bee_account');
		drupal_add_css($module_path . '/external/hover-effect/css/fdw.css');
		drupal_add_js($module_path . '/external/hover-effect/js/fdw.js');
		foreach ($employers as $userProfile) {
			$photo_path = ($userProfile->photo) ? file_create_url($userProfile->photo) : file_create_url(BEE_ACCOUNT_PHOTO_DEFAULT);
			$position = (!empty($userProfile->position)) ? bee_account_position_map($userProfile->position) : 'empty';
			$output .= '<li class = "span3">';
			$output .= '<article class = "c-two" style = "background-image:url( ' . $photo_path . ')">';
			$output .= '<div class = "fdw-background">';
			$output .= '<h4><a href = "' . base_path() . 'manuka/myaccount/view/' . $userProfile->uid . '" style = "color:#fff;">' . $userProfile->name . '</a></h4>';
			$output .= '<div class = "fdw-subtitle a-center">is <a href = "">' . $position . '</a></div>';
			$output .= '<p class = "fdw-port">';
			$output .= '<a href = "' . base_path() . 'manuka/myaccount/view/' . $userProfile->uid . '">View<span class = "vg-icon">→</span></a>';
			$output .= '</p>';
			$output .= '</div>';
			$output .= '</article>';
			$output .= '</li>';
		}
	} else {
		$output .= bee_account_error_messages('No employeers without payroll');
	}
	return $output;
}
