<?php
/**
 * Handles leave-related operations in the plugin.
 *
 * This class manages creation, approval, rejection, and deletion
 * of leave applications submitted by employees.
 *
 * @package voidempo
 */
class VOIDEMPO_Leave {
	/**
	 * Class constructor.
	 *
	 * Initializes class properties, hooks, and dependencies required
	 * for the functionality of this component.
	 */
	public function __construct() {

		add_action( 'wp_ajax_voidempo_VWFNRejectLeave', array( $this, 'voidempo_reject_leave_application' ) );
	
		add_action( 'wp_ajax_voidempo_VWFNAcceptLeave', array( $this, 'voidempo_accept_leave_application' ) );
		
	}

	/**
	 * Rejects a pending leave application.
	 *
	 * This function updates the status of a leave application to 'rejected'
	 * based on the provided leave ID. Typically used by administrators or managers.
	 *
	 * @return void Outputs a response or redirects after processing.
	 */
	public function voidempo_reject_leave_application() {
		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;

		$leave_id = isset( $_POST['leave_id'] ) ? intval( $_POST['leave_id'] ) : 0;

		$wpdb->update( "{$wpdb->prefix}leave_applications", array( 'status' => 'Rejected' ), array( 'id' => $leave_id ) );
		wp_cache_delete( 'leave_status_' . $leave_id, 'voidempo_leave' );
		echo wp_json_encode( array( 'success' => true ) );

		wp_die();
	}
	/**
	 * Accepts a pending leave application.
	 *
	 * This function updates the leave application's status to 'accepted'
	 * based on the provided leave ID. Typically triggered by admin or manager actions.
	 *
	 * @return void Outputs a response or performs a redirect as needed.
	 */
	public function voidempo_accept_leave_application() {

		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;

		$leave_id = isset( $_POST['leave_id'] ) ? intval( $_POST['leave_id'] ) : 0;

		$wpdb->update( "{$wpdb->prefix}leave_applications", array( 'status' => 'Accepted' ), array( 'id' => $leave_id ) );

		wp_cache_delete( 'leave_status_' . $leave_id, 'voidempo_leave' );

		echo wp_json_encode( array( 'success' => true ) );

		wp_die();
	}

	
}
