<?php
/**
 * Class VOIDEMPO_Holidays
 *
 * Handles holiday event management functionality.
 * This may include adding, updating, deleting, and fetching holiday events
 * via AJAX or other methods within the plugin.
 *
 * @package voidempo
 */
class VOIDEMPO_Holidays {
	/**
	 * Constructor.
	 *
	 * Initializes the class by setting up necessary hooks, actions, or dependencies.
	 * This method runs automatically when an object of this class is instantiated.
	 */
	public function __construct() {

		add_action( 'wp_ajax_voidempo_holidays_event_add', array( $this, 'voidempo_holidays_event_add' ) );

		add_action( 'wp_ajax_voidempo_holidays_event_delete', array( $this, 'voidempo_holidays_event_delete' ) );

		add_action( 'wp_ajax_voidempo_get_calendar_events', array( $this, 'voidempo_get_calendar_events' ) );

		add_action( 'wp_ajax_voidempo_holidays_eventtitle_update', array( $this, 'voidempo_holidays_eventtitle_update' ) );

		add_action( 'wp_ajax_voidempo_save_company_half_day', array( $this, 'voidempo_save_company_half_day' ) );

		add_action( 'wp_ajax_voidempo_delete_halfday', array( $this, 'voidempo_delete_halfday' ) );
	}

	/**
	 * Adds a new holiday event via AJAX.
	 *
	 * Handles AJAX requests to insert a new holiday event into the database.
	 * This function should validate input data, check user capabilities, and
	 * respond with success or failure status.
	 *
	 * @return void Outputs a JSON response indicating the result of the insertion.
	 */
	public function voidempo_holidays_event_add() {
		global $wpdb;
		// Security check
		check_ajax_referer( 'voidempo_dashboard_nonce', 'security' );

		if ( ! is_user_logged_in() ) {
			wp_safe_redirect( wp_login_url() );
			exit;
		}

		if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'voidempo_manager_access' ) ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized access!' ), 403 );
		}


		// Get and sanitize fields
		$title = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
		$start = isset( $_POST['start'] ) ? sanitize_text_field( wp_unslash( $_POST['start'] ) ) : '';
		$end   = isset( $_POST['end'] ) ? sanitize_text_field( wp_unslash( $_POST['end'] ) ) : '';

		if ( empty( $title ) || empty( $start ) || empty( $end ) ) {
			wp_send_json_error( array( 'message' => 'Missing required fields' ) );
		}

		// Insert into DB
		$table_name = $wpdb->prefix . 'voidempo_holidays';
		$inserted   = $wpdb->insert(
			$table_name,
			array(
				'event_title'    => $title,
				'eventstartdata' => $start,
				'eventenddata'   => $end,
				'date_created'   => gmdate( 'Y-m-d' ),
			),
			array( '%s', '%s', '%s' )
		);
		if ( $inserted ) {
			wp_send_json_success(
				array( 'message' => 'Holiday saved successfully!' )
			);
		} else {
			wp_send_json_error( array( 'message' => 'Database insert failed' ) );
		}
	}

	
	/**
	 * Updates the title of a holiday event via AJAX.
	 *
	 * This function handles AJAX requests to modify the title of an existing
	 * holiday event in the database. It should validate the input data, check
	 * user permissions, and respond with success or error status.
	 *
	 * @return void Outputs a JSON response indicating the update status.
	 */
	public function voidempo_holidays_eventtitle_update() {

		check_ajax_referer( 'voidempo_dashboard_nonce', 'security' );

		if ( ! is_user_logged_in() ) {
			wp_safe_redirect( wp_login_url() );
			exit;
		}
		
		if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'voidempo_manager_access' ) ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized access!' ), 403 );
		}

		global $wpdb;
		$eventid    = isset( $_POST['eventid'] ) ? sanitize_text_field( wp_unslash( $_POST['eventid'] ) ) : '';
		$eventtitle = isset( $_POST['eventtitle'] ) ? sanitize_text_field( wp_unslash( $_POST['eventtitle'] ) ) : '';

		$is_update = $wpdb->update(
			$wpdb->prefix . 'voidempo_holidays',
			array( 'event_title' => $eventtitle ),
			array( 'id' => $eventid )
		);

		if ( $is_update !== false ) {
			wp_cache_delete( 'voidempo_holidays_all_events' );
			wp_cache_delete( 'voidempo_holiday_event_' . $eventid );
			echo 'updated';
		}

		wp_die();
	}

	/**
	 * Deletes a holiday event from the database via AJAX.
	 *
	 * This function is triggered by an AJAX request and is responsible for
	 * removing a holiday-type event based on the provided event ID.
	 * It should include validation such as nonce checks and user capability checks.
	 *
	 * @return void Outputs a JSON response indicating the result of the deletion.
	 */
	public function voidempo_holidays_event_delete() {

		check_ajax_referer( 'voidempo_dashboard_nonce', 'security' );

		if ( ! is_user_logged_in() ) {
			wp_safe_redirect( wp_login_url() );
			exit;
		}
			if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'voidempo_manager_access' ) ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized access!' ), 403 );
		}


		global $wpdb;
		$eventid = isset( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;

		if ( ! $eventid ) {
			wp_send_json_error( array( 'message' => 'Invalid event ID' ) );
		}

		$is_deleted = $wpdb->delete(
			$wpdb->prefix . 'voidempo_holidays',
			array( 'id' => $eventid ),
			array( '%d' )
		);

		if ( $is_deleted ) {
			wp_cache_delete( 'voidempo_holidays_all_events' );
			wp_send_json_success( array( 'message' => 'Holiday deleted successfully!' ) );
		} else {
			wp_send_json_error( array( 'message' => 'Failed to delete holiday' ) );
		}
	}

	function voidempo_get_calendar_events() {

		check_ajax_referer( 'voidempo_dashboard_nonce', 'security' );

		if ( ! is_user_logged_in() ) {
			wp_safe_redirect( wp_login_url() );
			exit;
		}

		if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'voidempo_manager_access' ) ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized access!' ), 403 );
		}


		global $wpdb;

		$jsonevent         = array();
		$json_leave_events = array();
		$disabled_user_ids = wp_cache_get( 'disabled_users', 'user_meta' );
		if ( false === $disabled_user_ids ) {
			$disabled_user_ids = $wpdb->get_col(
				"
				SELECT user_id FROM {$wpdb->usermeta}
				WHERE meta_key = '_employee_disabled' AND meta_value = '1'
			"
			);
			wp_cache_set( 'disabled_users', $disabled_user_ids, 'user_meta', 30 * MINUTE_IN_SECONDS );
		}
		
		$disabled_user_ids = array_map( 'intval', (array) $disabled_user_ids );
		$placeholders      = implode( ',', array_fill( 0, count( $disabled_user_ids ), '%d' ) );

		$get_leaves = wp_cache_get( 'leave_applications_excluding_disabled_users', 'leave_data' );
		if ( false === $get_leaves ) {
			if ( ! empty( $disabled_user_ids ) ) {
				$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 NOT IN ($placeholders)
						",
						...$disabled_user_ids
					)
				);
			} else {
				$get_leaves = $wpdb->get_results(
					"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"
				);
			}
			wp_cache_set( 'leave_applications_excluding_disabled_users', $get_leaves, 'leave_data', 30 * MINUTE_IN_SECONDS );
		}

		foreach ( $get_leaves as $leave ) {
			$color = ( 'full-day' === $leave->leave_type )
				? ( $leave->status === 'Accepted' ? 'green' : 'red' )
				: ( $leave->status === 'Accepted' ? 'black' : 'red' );

			$to_date = ( new DateTime( $leave->to_date ) )->modify( '+1 day' )->format( 'Y-m-d' );

			$json_leave_events[] = array(
				'id'    => $leave->id,
				'title' => 'Leave: ' . $leave->display_name . ' - ' . $leave->leave_type . ', reason - ' . $leave->reason,
				'start' => $leave->from_date,
				'end'   => $to_date,
				'color' => $color,
			);
		}

			$sql = "
			SELECT user_id, meta_key, meta_value 
			FROM {$wpdb->usermeta}
			WHERE meta_key IN ('user_dob', 'user_joining_date')
		";

		$params = [];

		if ( ! empty( $disabled_user_ids ) ) {
			$placeholders = implode( ',', array_fill( 0, count( $disabled_user_ids ), '%d' ) );
			$sql .= " AND user_id NOT IN ($placeholders)";
			$params = $disabled_user_ids;
		}

		if ( ! empty( $params ) ) {
			$sql = $wpdb->prepare( $sql, $params );
		} else {
			$sql = $wpdb->prepare( $sql ); 
		}

		$get_users_meta = $wpdb->get_results( $sql );

		$user_names = $wpdb->get_results( 'SELECT ID, display_name FROM ' . $wpdb->users, OBJECT_K );

		foreach ( $get_users_meta as $user_meta ) {
			if ( empty( $user_meta->meta_value ) ) {
				continue;
			}

			$color = $user_meta->meta_key === 'user_dob' ? '#2A52E0' : '#8521E1';

			for ( $year = 2000; $year <= 2030; $year++ ) {
				$recurring_date = $year . substr( $user_meta->meta_value, 4 );
				$user_name      = $user_names[ $user_meta->user_id ]->display_name ?? 'Unknown';

				$json_leave_events[] = array(
					'id'    => 'user_' . $user_meta->user_id . '_' . $user_meta->meta_key . '_' . $year,
					'title' => ucfirst( str_replace( '_', ' ', $user_meta->meta_key ) ) . ': ' . $user_name,
					'start' => $recurring_date,
					'end'   => $recurring_date,
					'color' => $color,
				);
			}
		}

		$get_holidays = wp_cache_get( 'voidempo_holidays_all', 'site_data' );
		if ( false === $get_holidays ) {
			$get_holidays = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}voidempo_holidays" );
			wp_cache_set( 'voidempo_holidays_all', $get_holidays, 'site_data', 12 * HOUR_IN_SECONDS );
		}
		foreach ( $get_holidays as $holiday ) {
			$jsonevent[] = array(
				'id'         => $holiday->id,
				'title'      => $holiday->event_title,
				'start'      => $holiday->eventstartdata,
				'end'        => $holiday->eventenddata,
				'color'      => '#660413',
				'event_type' => 'holiday',
			);
		}

		$half_day_options = $wpdb->get_results(
			"SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE 'half_days_%'"
		);

		foreach ( $half_day_options as $option ) {
			$dates = maybe_unserialize( $option->option_value );

			if ( is_array( $dates ) ) {
				$unique_dates = array_unique( $dates );
				foreach ( $unique_dates as $index => $date ) {
					if ( ! empty( $date ) ) {
						$json_leave_events[] = array(
							'id'         => 'half_day_' . sanitize_title( $option->option_name ) . '_' . $index,
							'title'      => 'Company Half Day',
							'start'      => $date,
							'end'        => $date,
							'color'      => 'orange',
							'event_type' => 'half_day',
						);
					}
				}
			}
		}

		wp_send_json_success(
			array(
				'jsonevent'       => $jsonevent,
				'jsonLeaveEvents' => $json_leave_events,
			)
		);
	}
	// voidempo_save_company_half_day
	public function voidempo_delete_halfday() {
		global $wpdb;
		// Security check
		check_ajax_referer( 'voidempo_dashboard_nonce', 'security' );

		if ( ! is_user_logged_in() ) {
			wp_safe_redirect( wp_login_url() );
			exit;
		}

		if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'voidempo_manager_access' ) ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized access!' ), 403 );
		}

		$dateToDelete = isset( $_POST['date'] ) ? sanitize_text_field( $_POST['date'] ) : '';
		if ( empty( $dateToDelete ) ) {
			wp_send_json_error( array( 'message' => 'No date provided' ) ); }
		// Fetch all half-day options
			$half_day_options = $wpdb->get_results( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE 'half_days_%'" );
			$found            = false;
		foreach ( $half_day_options as $option ) {
			$dates = maybe_unserialize( $option->option_value );

			if ( is_array( $dates ) && in_array( $dateToDelete, $dates ) ) {
				// Remove the target date
				$updated_dates = array_values(
					array_filter(
						$dates,
						function ( $date ) use ( $dateToDelete ) {
							return $date !== $dateToDelete;
						}
					)
				);
				update_option( $option->option_name, $updated_dates );
				$found = true;
				break; // stop after first match
			}
		}
		if ( $found ) {
				wp_send_json_success( array( 'message' => 'Half-day deleted successfully' ) );
		} else {
				wp_send_json_error( array( 'message' => 'Half-day not found' ) );
		}
	}


	public function voidempo_save_company_half_day() {

		check_ajax_referer( 'voidempo_dashboard_nonce', 'security' );

		if ( ! is_user_logged_in() ) {
			wp_safe_redirect( wp_login_url() );
			exit;
		}

		if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'voidempo_manager_access' ) ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized access!' ), 403 );
		}


		$selected_date = sanitize_text_field( $_POST['start'] );
		$date          = new DateTime( $selected_date );
		$month         = $date->format( 'Y-m' );

		$option_name = 'half_days_' . $month;
		$half_days   = get_option( $option_name, array() );

		if ( ! is_array( $half_days ) ) {
			$half_days = array();
		}

		if ( ! in_array( $selected_date, $half_days, true ) ) {
			$half_days[] = $selected_date;
			update_option( $option_name, $half_days );
		}

		wp_send_json_success(
			array(
				'msg'        => 'inserted',
				'title'      => 'Company Half Day',
				'start'      => $selected_date,
				'end'        => $selected_date,
				'color'      => 'orange',
				'event_type' => 'half_day',
			)
		);
	}
}
