<?php

/**
 * Return an array of cron schedules
 *
 * @param $schedules
 * @return array $reccurrences
 */
function mainwp_hmbkp_cron_schedules( $schedules ) {

	$schedules['hmbkp_hourly'] = array( 'interval' => HOUR_IN_SECONDS, 'display' => __( 'Once Hourly', 'mainwp-backupwordpress-extension' ) );
	$schedules['hmbkp_twicedaily'] = array( 'interval' => 12 * HOUR_IN_SECONDS, 'display' => __( 'Twice Daily', 'mainwp-backupwordpress-extension' ) );
	$schedules['hmbkp_daily'] = array( 'interval' => DAY_IN_SECONDS, 'display' => __( 'Once Daily', 'mainwp-backupwordpress-extension' ) );
	$schedules['hmbkp_weekly'] = array( 'interval' => WEEK_IN_SECONDS, 'display' => __( 'Once Weekly', 'mainwp-backupwordpress-extension' ) );
	$schedules['hmbkp_fortnightly'] = array( 'interval' => 2 * WEEK_IN_SECONDS, 'display' => __( 'Once Biweekly', 'mainwp-backupwordpress-extension' ) );
	$schedules['hmbkp_monthly'] = array( 'interval' => 30 * DAY_IN_SECONDS, 'display' => __( 'Once Monthly', 'mainwp-backupwordpress-extension' ) );

	return $schedules;
}

add_filter( 'cron_schedules', 'mainwp_hmbkp_cron_schedules' );

/**
 * Recursively delete a directory including
 * all the files and sub-directories.
 *
 * @param string $dir
 * @return bool
 * @return bool|WP_Error
 */
function mainwp_hmbkp_rmdirtree( $dir ) {

	//  if ( false !== strpos( MAINWP\BackUpWordPress\Backup::get_home_path(), $dir ) )
	//      return new WP_Error( 'mainwp_hmbkp_invalid_action_error', sprintf( __( 'You can only delete directories inside your WordPress installation', 'mainwp-backupwordpress-extension' ) ) );
	//
	//  if ( is_file( $dir ) )
	//      @unlink( $dir );
	//
	//  if ( ! is_dir( $dir ) || ! is_readable( $dir ) )
	//      return false;
	//
	//  $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir ), RecursiveIteratorIterator::CHILD_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD );
	//
	//  foreach ( $files as $file ) {
	//
	//      if ( $file->isDir() )
	//          @rmdir( $file->getPathname() );
	//
	//      else
	//          @unlink( $file->getPathname() );
	//
	//  }
	//
	//  @rmdir( $dir );
	//
	//  return true;
}

/**
 * Check if a backup is possible with regards to file
 * permissions etc.
 *
 * @return bool
 */
// not used
function mainwp_hmbkp_possible() {

	//  if ( ! wp_is_writable( mainwp_hmbkp_path() ) || ! is_dir( mainwp_hmbkp_path() ) ) {
	//      return false;
	//  }
	//
	//  $test_backup = new MAINWP\BackUpWordPress\Backup();
	//
	//  if ( ! is_readable( $test_backup->get_root() ) ) {
	//      return false;
	//  }

	return true;
}

/**
 * Get the max email attachment filesize
 *
 * Can be overridden by defining MAINWP_HMBKP_ATTACHMENT_MAX_FILESIZE
 *
 * return int the filesize
 */
function mainwp_hmbkp_get_max_attachment_size() {

	$max_size = '10mb';

	if ( defined( 'MAINWP_HMBKP_ATTACHMENT_MAX_FILESIZE' ) && wp_convert_hr_to_bytes( MAINWP_HMBKP_ATTACHMENT_MAX_FILESIZE ) ) {
		$max_size = MAINWP_HMBKP_ATTACHMENT_MAX_FILESIZE; }

	return wp_convert_hr_to_bytes( $max_size );
}

// not used
function mainwp_hmbkp_is_path_accessible( $dir ) {

	// Path is inaccessible
	//  if ( strpos( $dir, MAINWP\BackUpWordPress\Backup::get_home_path() ) === false ) {
	//      return false;
	//  }
	//  return true;
}

/**
 * List of schedules
 *
 * @return array
 */
function mainwp_hmbkp_get_cron_schedules() {

	$schedules = wp_get_schedules();

	// remove any schedule whose key is not prefixed with 'mainwp_hmbkp_'
	foreach ( $schedules as $key => $arr ) {
		if ( ! preg_match( '/^hmbkp_/', $key ) ) {
			unset( $schedules[ $key ] ); }
	}

	return $schedules;
}

/**
 * @param string $type the type of the schedule
 * @param array $times {
 *     An array of time arguments. Optional.
 *
 *     @type int $minutes          The minute to start the schedule on. Defaults to current time + 10 minutes. Accepts
 *                                 any valid `date( 'i' )` output.
 *     @type int $hours            The hour to start the schedule on. Defaults to current time + 10 minutes. Accepts
 *                                 any valid `date( 'G' )` output.
 *     @type string $day_of_week   The day of the week to start the schedule on. Defaults to current time + 10 minutes. Accepts
 *                                 any valid `date( 'l' )` output.
 *     @type int $day_of_month     The day of the month to start the schedule on. Defaults to current time + 10 minutes. Accepts
 *                                 any valid `date( 'j' )` output.
 *     @type int $now              The current time. Defaults to `time()`. Accepts any valid timestamp.
 *
 * }
 * @return int $timestamp Returns the resulting timestamp on success and Int 0 on failure
 */
function mainwp_hmbkp_determine_start_time( $type, $times = array() ) {

	// Default to in 10 minutes
	if ( ! empty( $times['now'] ) ) {
		$default_timestamp = $times['now'] + 600;
	} else {
		$default_timestamp = time() + 600;
	}

	$default_times = array(
		'minutes' => date( 'i', $default_timestamp ),
		'hours' => date( 'G', $default_timestamp ),
		'day_of_week' => date( 'l', $default_timestamp ),
		'day_of_month' => date( 'j', $default_timestamp ),
		'now' => time(),
	);

	$args = wp_parse_args( $times, $default_times );

	$intervals = MAINWP\BackUpWordPress\Scheduled_Backup::get_cron_schedules();

	// Allow the hours and minutes to be overwritten by a constant
	if ( defined( 'MAINWP_HMBKP_SCHEDULE_TIME' ) && MAINWP_HMBKP_SCHEDULE_TIME ) {
		$hm = MAINWP_HMBKP_SCHEDULE_TIME;
	} // The hour and minute that the schedule should start on
	else {
		$hm = $args['hours'] . ':' . $args['minutes'] . ':00';
	}

	switch ( $type ) {

		case 'hmbkp_hourly' :
		case 'hmbkp_daily' :
		case 'hmbkp_twicedaily':

			// The next occurance of the specified time
			$schedule_start = $hm;
			break;

		case 'hmbkp_weekly' :
		case 'hmbkp_fortnightly' :

			// The next day of the week at the specified time
			$schedule_start = $args['day_of_week'] . ' ' . $hm;
			break;

		case 'hmbkp_monthly' :

			// The occurance of the time on the specified day of the month
			$schedule_start = date( 'F', $args['now'] ) . ' ' . $args['day_of_month'] . ' ' . $hm;

			// If we've already gone past that day this month then we'll need to start next month
			if ( strtotime( $schedule_start, $args['now'] ) <= $args['now'] ) {
				$schedule_start = date( 'F', strtotime( '+ 1 month', $args['now'] ) ) . ' ' . $args['day_of_month'] . ' ' . $hm;
			}

			// If that's still in the past then we'll need to jump to next year
			if ( strtotime( $schedule_start, $args['now'] ) <= $args['now'] ) {
				$schedule_start = date( 'F', strtotime( '+ 1 month', $args['now'] ) ) . ' ' . $args['day_of_month'] . ' ' . date( 'Y', strtotime( '+ 1 year', $args['now'] ) ) . ' ' . $hm;
			}

			break;

		default :

			return 0;
	}

	$timestamp = strtotime( $schedule_start, $args['now'] );

	// Convert to UTC
	$timestamp -= get_option( 'gmt_offset' ) * 3600;

	// If the scheduled time already passed then keep adding the interval until we get to a future date
	while ( $timestamp <= $args['now'] ) {
		$timestamp += $intervals[ $type ]['interval'];
	}

	return $timestamp;
}

/**
 * Helper function for creating safe action URLs.
 *
 * @param string $action Callback function name.
 * @param array $query_args Additional GET params.
 *
 * @return string
 */
function mainwp_hmbkp_admin_action_url( $action, array $query_args = array() ) {

	$query_args = array_merge( $query_args, array( 'action' => 'mainwp_hmbkp_' . $action ) );

	return esc_url( wp_nonce_url( add_query_arg( $query_args, admin_url( 'admin-post.php' ) ), 'mainwp_hmbkp_' . $action, 'hmbkp-' . $action . '_nonce' ) );
}
