<?php
/**
 * General functions used across the plugin.
 *
 * This file contains utility functions and helpers
 * that are shared across different modules of the Frontend Dashboard plugin.
 *
 * @package voidempo
 */

/**
 * Get user data by user ID.
 *
 * Retrieves the full WP_User object for a given user ID.
 *
 * @param int $user_id The ID of the user.
 * @return WP_User|false WP_User object on success, false on failure.
 */
function voidempo_user_by_id_( $user_id ) {
	$display_name = get_user_by( 'id', $user_id )->display_name;
	return $display_name;
}
/**
 * Fetch projects assigned to the current user.
 * Get users projects data by $user_id.
 * List of user projects.
 */
function VOIDEMPO_fetch_my_projects( $user_id ) {
	global $wpdb;

		$cache_key   = "user_projects_{$user_id}";
		$get_results = wp_cache_get( $cache_key, 'voidempo_projects' );

	if ( false === $get_results ) {
		$get_results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}voidempo_projects WHERE (FIND_IN_SET(%s, member_id) OR FIND_IN_SET(%s, manager_id))",
				(string) $user_id,
				(string) $user_id
			)
		);

		wp_cache_set( $cache_key, $get_results, 'voidempo_projects', 600 );
	}
	return $get_results;
}
/**
 * Sets the default time zone for the application.
 *
 * @return void
 */
function voidempo_default_time_zone_set_() {
	$timestamp = current_time( 'timestamp' );
	return date_i18n( 'Y-m-d H:i:s', $timestamp );
}
/**
 * Generates an array of dates between two given dates.
 *
 * @param string $start  Start date in 'Y-m-d' format.
 * @param string $end    End date in 'Y-m-d' format.
 * @param string $format Date format to return. Default is 'Y-m-d'.
 *
 * @return array Array of dates in specified format.
 */
function voidempo_getDatesFromRange_( $start, $end, $format = 'Y-m-d' ) {

	$array = array();

	$interval = new DateInterval( 'P1D' );

	$real_end = new DateTime( $end );
	$real_end->add( $interval );

	$period = new DatePeriod( new DateTime( $start ), $interval, $real_end );

	foreach ( $period as $date ) {
		$array[ strtotime( $date->format( $format ) ) ] = $date->format( $format );
	}

	return $array;
}
/**
 * Fetches task details by task ID.
 *
 * @param int $task_id The ID of the task to fetch.
 *
 * @return array|false Task data array on success, false on failure.
 */
function voidempo_fetch_tasksby_taskid( $task_id ) {
	global $wpdb;
	$cache_key   = 'voidempo_task_id_' . absint( $task_id );
	$cache_group = 'voidempo_task';

	$get_results = wp_cache_get( $cache_key, $cache_group );
	if ( false === $get_results ) {
		$get_results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}voidempo_task WHERE id = %d",
				$task_id
			)
		);
		if ( ! empty( $get_results ) ) {
			wp_cache_set( $cache_key, $get_results, $cache_group, HOUR_IN_SECONDS );
		}
	}
		return $get_results;
}

/**
 * Retrieves missing EOD (End of Day) reports for a user within a date range.
 *
 * This function checks for dates between the given start and end date
 * where the user has not submitted an EOD report.
 *
 * @param string $stdate  The start date in 'YYYY-MM-DD' format.
 * @param string $eddate  The end date in 'YYYY-MM-DD' format.
 * @param int    $user_i_d  The ID of the user to check.
 * @return array An array of dates where EOD reports are missing.
 */
function voidempo_getMissingEodByDateandUser_( $stdate, $eddate, $user_i_d ) {
	global $wpdb;

	$q = '';
	if ( ! empty( $user_i_d ) ) {
		$q = $wpdb->prepare( 'AND user_id = %d', $user_i_d );
	}

	$stdatestrtotime      = strtotime( $stdate );
	$eddatestrtotime      = strtotime( $eddate );
	$currentdatestrtotime = strtotime( gmdate( 'Y-m-d' ) );

	$norecords_data = 0;
	if ( $stdatestrtotime > $currentdatestrtotime ) {
		$norecords_data = 1;
	} else {
		if ( $eddatestrtotime > $currentdatestrtotime ) {
			$eddate = gmdate( 'Y-m-d' );
		}

		$period = voidempo_getDatesFromRange_( $stdate, $eddate );

		$table       = $wpdb->prefix . 'voidempo_eod';
		$cache_key   = 'missing_eod_' . md5( $table . $q . $stdate . $eddate );
		$cache_group = 'missing_eod_data';

		$getTodaysMissingEod = wp_cache_get( $cache_key, $cache_group );

		if ( false === $getTodaysMissingEod ) {
			$getTodaysMissingEod = $wpdb->get_results(
				$wpdb->prepare(
					"
					SELECT user_id, date_created
					FROM {$wpdb->prefix}voidempo_eod
					WHERE is_delete = %d
					AND hours >= %d
					AND date_created BETWEEN %s AND %s
					{$q}
					GROUP BY user_id, date_created
				",
					0,
					1,
					$stdate,
					$eddate
				)
			);
			wp_cache_set( $cache_key, $getTodaysMissingEod, $cache_group, 10 * MINUTE_IN_SECONDS );
		}

		if ( ! empty( $user_i_d ) ) {
			$alluserid[] = $user_i_d;
		} else {
			foreach ( get_users() as $usersmeta ) {
				if ( get_user_meta( $usersmeta->ID, '_employee_disabled', true ) != 1 ) {
					$alluserid[] = $usersmeta->ID;
				}
			}
		}

			$datewiseusers = array();
		foreach ( $getTodaysMissingEod as $existingeodmeta ) {
			$eoddateadded = $existingeodmeta->date_created;
			if ( in_array( strtotime( $eoddateadded ), array_keys( $period ) ) ) {
					$datewiseusers[ strtotime( $eoddateadded ) ][] = $existingeodmeta->user_id;
			}
		}

			$udata = array();
		foreach ( $period as $data ) {
			if ( ! empty( $datewiseusers[ strtotime( $data ) ] ) ) {
				$udata[ $data ] = array_merge( array_diff( $alluserid, $datewiseusers[ strtotime( $data ) ] ), array_diff( $datewiseusers[ strtotime( $data ) ], $alluserid ) );
			} else {
				$udata[ $data ] = $alluserid;
			}
		}

			krsort( $udata );
	}

	if ( ! empty( $user_i_d ) ) {
		$get_leaves = $wpdb->get_results(
			$wpdb->prepare(
				"
            SELECT {$wpdb->prefix}leave_applications.*, wp_users.display_name
            FROM {$wpdb->prefix}leave_applications
            INNER JOIN wp_users ON {$wpdb->prefix}leave_applications.user_id = wp_users.ID
            WHERE {$wpdb->prefix}leave_applications.user_id = %d
              AND from_date <= %s
              AND to_date >= %s
              AND {$wpdb->prefix}leave_applications.status = 'Accepted'
              AND {$wpdb->prefix}leave_applications.leave_type = 'full-day'
            ",
				$user_i_d,
				$eddate,
				$stdate
			)
		);

	} else {
		$get_leaves = $wpdb->get_results(
			$wpdb->prepare(
				"
            SELECT {$wpdb->prefix}leave_applications.*, wp_users.display_name
            FROM {$wpdb->prefix}leave_applications
            INNER JOIN wp_users ON {$wpdb->prefix}leave_applications.user_id = wp_users.ID
            WHERE from_date <= %s AND to_date >= %s
            AND {$wpdb->prefix}leave_applications.status = 'Accepted'
            AND {$wpdb->prefix}leave_applications.leave_type = 'full-day'
        ",
				$eddate,
				$stdate
			)
		);
	}

	$leave_dates = array();
	foreach ( $get_leaves as $leave ) {
		$leave_start      = strtotime( $leave->from_date );
		$leave_end        = strtotime( $leave->to_date );
		$totalleave_dates = voidempo_getDatesFromRange_( gmdate( 'Y-m-d', $leave_start ), gmdate( 'Y-m-d', $leave_end ) );

		foreach ( $totalleave_dates as $edkey => $alldates ) {
			$leave_dates[ $leave->user_id ][] = $edkey;
		}
	}

	$getholidays = $wpdb->get_results( 'select * from ' . $wpdb->prefix . 'voidempo_holidays' );

	$totalholidaysar = array();
	foreach ( $getholidays as $holidays ) {
		$eventstartdate   = $holidays->eventstartdata;
		$eventenddate = $holidays->eventenddata;
		$totaleventsdates = voidempo_getDatesFromRange_( $eventstartdate, $eventenddate );

		foreach ( $totaleventsdates as $edkey => $alldates ) {
			$totalholidaysar[] = $edkey;
		}
	}
	$unique_ids        = array();
	$udataeventfilterd = array();
	foreach ( $udata as $dkey => $d ) {
		$udataeventfilterd[] = $dkey;
		$unique_ids          = array_merge( $unique_ids, $d );
	}
	$unique_ids = array_unique( $unique_ids );
	$unique_ids = array_flip( $unique_ids );

	foreach ( $udata as $dkey => $d ) {
		foreach ( $d as $d_id ) {
			if ( is_array( $unique_ids[ $d_id ] ) ) {
				$unique_ids[ $d_id ][] = $dkey;
			} else {
				$unique_ids[ $d_id ] = array( $dkey );
			}
		}
	}

	?>
   
	<table class="table table-striped table-bordered voidempo_missingeod_table" style="width:max-content;">
		<thead>
			<tr>
				<th>Sr. No.</th>
				<th style="width:25%;">Employee Name</th>
				<?php
				foreach ( $udataeventfilterd as $key_date => $emp_id ) {
					?>
					<th class="voidempo_rotate"><?php echo esc_html( $emp_id ); ?></th>
					<?php
				}
				?>
				<th class="voidempo_rotate"># missing EOD</th>
			</tr>
		</thead>
		<tbody>
			<?php
			$sr_no = 1;

			foreach ( $unique_ids as $unique_id => $missing_dates ) {
				?>
				<tr>
				<?php
					$cnt = 0;

					$employee_disabled = get_user_meta( $unique_id, '_employee_disabled', true );
				if ( '1' == $employee_disabled ) {
					continue;
				}

				?>
					<td><?php echo esc_html( $sr_no++ ); ?></td>
					<td><?php echo esc_html( voidempo_user_by_id_( $unique_id ) ); ?></td>
					<?php
					foreach ( $udataeventfilterd as $all_date ) {
						?>
						<td>
							<?php
							if ( in_array( strtotime( $all_date ), $totalholidaysar ) ) {
								?>
								<span class="holiday-symbol">H</span>
								<?php
							} elseif ( ! empty( $leave_dates[ $unique_id ] ) && in_array( strtotime( $all_date ), $leave_dates[ $unique_id ] ) ) {
								?>
								<span class="leave-symbol">L</span>
								<?php
							} elseif ( in_array( $all_date, $missing_dates ) ) {
								?>
									<i class="fa fa-times" aria-hidden="true" style="color:red;"></i>
									<?php
									++$cnt;
							} else {
								?>
									<i class="fa fa-check" aria-hidden="true" style="color:green;"></i>
								<?php

							}
							?>
						</td>
						<?php
					}
					?>
					<td><?php echo esc_attr( $cnt ); ?></td>
				</tr>
				<?php
			}
			?>
		</tbody>
	</table>

	<?php
}
/**
 * Checks if a user is the manager of a given project.
 *
 * This function determines whether the specified user is assigned
 * as the manager for the provided project ID.
 *
 * @param int $project_id The ID of the project.
 * @param int $user_id    The ID of the user to check.
 * @return bool True if the user is the manager, false otherwise.
 */
function voidempo_fn_check_is_manager_( $project_id, $user_id ) {
	global $wpdb;
		$user_id    = intval( $user_id );
		$project_id = intval( $project_id );

		$cache_key   = 'project_manager_' . $user_id . '_' . $project_id;
		$cache_group = 'my_plugin_cache';

		$get_results = wp_cache_get( $cache_key, $cache_group );

	if ( false === $get_results ) {
		$get_results = $wpdb->get_results(
			$wpdb->prepare(
				"
					SELECT * 
					FROM {$wpdb->prefix}voidempo_projects
					WHERE FIND_IN_SET(%d, manager_id) 
					AND related_post_id <> 0 
					AND related_post_id = %d
					",
				$user_id,
				$project_id
			)
		);
			wp_cache_set( $cache_key, $get_results, $cache_group, 10 * MINUTE_IN_SECONDS );
	}

	if ( count( $get_results ) > 0 ) {
		$msg = 'is_manager';
	} else {
		$msg = 'is_not';
	}

	return $msg;
}

