wpalchemist
7/20/2016 - 10:11 PM

Cron job to make Employee Scheduler send shift reminders

Cron job to make Employee Scheduler send shift reminders

<?php
// Scheduled Action Hook
function employee_scheduler_check_for_reminder( ) {
	// get tomorrow's date in the correct format
	$tomorrow = date( 'F j, Y', strtotime( '+1 day', date() ) );

	// find all shifts scheduled for tomorrow
	$args = array(
		'post_type' => 'shift',
		'meta_query' => array(
			array(
				'key' => '_wpaesm_date',
				'value' => $tomorrow,
			),
		),
		'tax_query' => array(
			array(
				'taxonomy' => 'shift_type',
				'field' => 'slug',
				'terms' => array( 'extra', 'pto' ),
				'operator' => 'NOT IN',
			),
		),
		'posts_per_page' => -1,
	);
	$tomorrows_shifts = new WP_Query( $args );
	if ( $tomorrows_shifts->have_posts() ) :
		while ( $tomorrows_shifts->have_posts() ) : $tomorrows_shifts->the_post();
			// send reminder to employee
			employee_scheduler_send_reminder( get_the_id() );
		endwhile;
	endif;
	wp_reset_postdata();


}

function employee_scheduler_send_reminder( $shiftid ) {

	$text_notifications = new Employee_Scheduler_Text_Notifications_Admin();

	$users = get_users( array(
		'connected_type' => 'shifts_to_employees',
		'connected_items' => $shiftid
	) );
	if( !$users or empty( $users ) ) {
		return;
	}
	foreach( $users as $user ) {
		$employee = $user->ID;
		$employee_email = $user->user_email();
	}

	if( 'email' == $text_notifications->get_notification_preference( $employee ) || 'both' == $text_notifications->get_notification_preference( $employee ) ) {
		employee_scheduler_send_reminder_email( $shiftid, $employee_email );
	}

	if( 'text' == $text_notifications->get_notification_preference( $employee ) || 'both' == $text_notifications->get_notification_preference( $employee ) ) {
		$message =  'You are scheduled to work tomorrow. Here are the details of your shift: ' . get_the_permalink( $shiftid );;

		$text_notifications->send_text_message( 'admin', $message );
	}



}

function employee_scheduler_send_reminder_email( $shiftid, $email ) {

	$options = get_option('wpaesm_options');

	$from = $options['notification_from_name'] . "";

	$to = $email;

	$cc = '';

	$subject = 'You are scheduled to work tomorrow!';

	$message_text = 'You are scheduled to work tomorrow. Here are the details of your shift: ' . get_the_permalink( $shiftid );


	wpaesm_send_email( $from, $to, $cc, $subject, $message_text );
}

// Schedule Cron Job Event
function employee_scheduler_reminders_cron() {
	if ( ! wp_next_scheduled( 'employee_scheduler_check_for_reminder' ) ) {
		wp_schedule_event( current_time( 'timestamp' ), 'daily', 'employee_scheduler_check_for_reminder' );
	}
}
add_action( 'wp', 'employee_scheduler_reminders_cron' );