<?php
/**
 * Exit if accessed directly.
 *
 * @package bp-user-todo-list
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Ensure BuddyPress and Groups component are active
if ( ! function_exists( 'groups_is_user_admin' ) || ! function_exists( 'bp_core_add_message' ) ) {
	return;
}

global $bp;

$group_id = isset( $bp->groups->current_group->id ) ? $bp->groups->current_group->id : 0;

// Check if user is logged in
if ( ! is_user_logged_in() ) {
	bp_core_add_message( __( 'You must be logged in to add todos.', 'wb-todo' ), 'error' );
	bp_core_redirect( bptodo_get_group_url() );
	exit;
}

// Check if user is a group admin or moderator (or site admin)
$current_user_id = get_current_user_id();
$is_site_admin   = bptodo_is_site_admin();
$is_group_admin  = groups_is_user_admin( $current_user_id, $group_id );
$is_group_mod    = groups_is_user_mod( $current_user_id, $group_id );

if ( ! $is_group_admin && ! $is_group_mod && ! $is_site_admin ) {
	bp_core_add_message( __( 'You must be a group administrator or moderator to add todos.', 'wb-todo' ), 'error' );
	bp_core_redirect( bptodo_get_group_url() );
	exit;
}

$group_members = groups_get_group_members(
	array(
		'group_id'            => $group_id,
		'exclude_admins_mods' => false,
	)
);

$group_members_ids = array();
$members_ids       = array();
if ( ! empty( $group_members['members'] ) ) {
	foreach ( $group_members['members'] as $member ) {
		$group_members_ids[]     = $member->ID;
		$members_ids[ $member->ID ] = $member->display_name;
	}
}

$todo_cats          = get_terms( array(
	'taxonomy'   => 'todo_category',
	'orderby'    => 'name',
	'hide_empty' => false,
) );
global $bptodo;

$profile_menu_label = $bptodo->profile_menu_label;
$profile_menu_slug  = $bptodo->profile_menu_slug;
$bptodo_req         = 'yes' === $bptodo->req_duedate ? 'required' : '';
$displayed_uid      = get_current_user_id();
$form_post_link     = bptodo_get_group_url() . strtolower( $profile_menu_label ) . '/list';
// Include ALL members including the task creator
// Removed code that was excluding the current user from task assignment

// Save todo items.
if ( isset( $_POST['group_todo_create'], $_POST['group_save_new_todo_data_nonce'] )
	&& wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['group_save_new_todo_data_nonce'] ) ), 'wp-bp-todo' ) ) {

	$todo_group_members = isset( $_POST['todo_group_members'] ) ? (array) wp_unslash( $_POST['todo_group_members'] ) : array(); //phpcs:ignore

	if ( ! empty( $todo_group_members ) && ! in_array( 'all', $todo_group_members, true ) ) {
		$group_members_ids = $todo_group_members;
		// Include ALL selected members including the task creator
	}

	$todo_group_id = isset( $_POST['todo_group_id'] ) ? sanitize_text_field( wp_unslash( $_POST['todo_group_id'] ) ) : $group_id;
	$title         = isset( $_POST['todo_title'] ) ? sanitize_text_field( wp_unslash( $_POST['todo_title'] ) ) : '';
	$summary       = isset( $_POST['bptodo-summary-input'] ) ? wp_kses_post( wp_unslash( $_POST['bptodo-summary-input'] ) ) : '';
	$due_date      = isset( $_POST['todo_due_date'] ) ? sanitize_text_field( wp_unslash( $_POST['todo_due_date'] ) ) : '';
	$priority      = isset( $_POST['todo_priority'] ) ? sanitize_text_field( wp_unslash( $_POST['todo_priority'] ) ) : '';
	$cat           = isset( $_POST['todo_cat'] ) ? sanitize_text_field( wp_unslash( $_POST['todo_cat'] ) ) : '';	

	$args            = array(
		'post_type'    => 'bp-todo',
		'post_status'  => 'publish',
		'post_title'   => $title,
		'post_content' => $summary,
		'post_author'  => $displayed_uid,
	);
	$primary_todo_id = wp_insert_post( $args );

	if ( $primary_todo_id ) {
		update_post_meta( $primary_todo_id, 'todo_status', 'incomplete' );
		update_post_meta( $primary_todo_id, 'todo_due_date', $due_date );
		update_post_meta( $primary_todo_id, 'todo_priority', $priority );
		update_post_meta( $primary_todo_id, 'todo_last_day_mail_sent', 'no' );
		update_post_meta( $primary_todo_id, 'todo_last_day_notification_sent', 'no' );
		update_post_meta( $primary_todo_id, 'todo_group_id', $todo_group_id );
		wp_set_object_terms( $primary_todo_id, $cat, 'todo_category' );
		update_post_meta( $primary_todo_id, 'todo_primary_id', $primary_todo_id );
		update_post_meta( $primary_todo_id, 'todo_creator_id', get_current_user_id() );

		$associated_todos = array();
		$current_user_id = get_current_user_id();

		foreach ( $group_members_ids as $member_id ) {

			// Skip the current user as they already have the primary todo assigned
			if ( $member_id == $current_user_id ) {
				continue;
			}

			// Create tasks for ALL other members including admins and mods
			$args    = array(
				'post_type'    => 'bp-todo',
				'post_status'  => 'publish',
				'post_title'   => $title,
				'post_content' => $summary,
				'post_author'  => $member_id,
			);
			$post_id = wp_insert_post( $args );

			if ( $post_id ) {
				$associated_todos[] = $post_id;
				update_post_meta( $post_id, 'todo_status', 'incomplete' );
				update_post_meta( $post_id, 'todo_due_date', $due_date );
				update_post_meta( $post_id, 'todo_priority', $priority );
				update_post_meta( $post_id, 'todo_last_day_mail_sent', 'no' );
				update_post_meta( $post_id, 'todo_last_day_notification_sent', 'no' );
				update_post_meta( $post_id, 'todo_group_id', $todo_group_id );
				wp_set_object_terms( $post_id, $cat, 'todo_category' );
				update_post_meta( $post_id, 'todo_creator_id', get_current_user_id() );
				update_post_meta( $post_id, 'todo_primary_id', $primary_todo_id );
			}
		}

		update_post_meta( $primary_todo_id, 'botodo_associated_todo', $associated_todos );

		// Trigger notifications and emails AFTER all todos are created
		do_action( 'bptodo_group_todo_submit', $group_members_ids, $primary_todo_id );

		echo '<script>window.location.replace("' . esc_url( $form_post_link ) . '");</script>';
	}
}

?>
<form class="bptodo-form-add" action="" method="post" id="myForm">
	<table class="bptodo-add-todo-tbl">
		<?php do_action( 'bp_group_todo_add_field_before_default_listing', $displayed_uid, $form_post_link ); ?>
		<tr>
			<td>
				<label><?php esc_html_e( 'Category', 'wb-todo' ); ?></label>
			</td>
			<td>
				<div class="bp_todo_categories">
					<select name="todo_cat" id="bp_todo_categories" required>
						<option value=""><?php esc_html_e( '--Select--', 'wb-todo' ); ?></option>
						<?php foreach ( $todo_cats as $todo_cat ) : ?>
							<option value="<?php echo esc_html( $todo_cat->name ); ?>"><?php echo esc_html( $todo_cat->name ); ?></option>
						<?php endforeach; ?>
					</select>
					<?php if ( 'yes' === $bptodo->allow_user_add_category ) : ?>
						<a href="javascript:void(0);" class="add-todo-category"><i class="fa fa-plus" aria-hidden="true"></i></a>
					<?php endif; ?>
				</div>
				<?php if ( 'yes' === $bptodo->allow_user_add_category ) : ?>
					<div class="add-todo-cat-row">
						<?php	/* translators: %s */ ?>
						<input type="text" id="todo-category-name" placeholder="<?php echo esc_html( sprintf( __( '%s category', 'wb-todo' ), $profile_menu_label ) ); ?>">
						<input type="hidden" id="bptodo-add-category-nonce" value="<?php echo esc_attr( wp_create_nonce( 'bptodo-add-todo-category' ) ); ?>">
						<button type="button" id="add-todo-cat" class="btn button wp-element-button"><?php esc_html_e( 'Add', 'wb-todo' ); ?></button>
					</div>
				<?php endif; ?>
			</td>
		</tr>
		<tr>
			<td><label><?php esc_html_e( 'Title', 'wb-todo' ); ?></label></td>
			<td><input type="text" placeholder="<?php esc_html_e( 'Title', 'wb-todo' ); ?>" name="todo_title" required class="bptodo-text-input"></td>
		</tr>
		<tr>
			<td><label><?php esc_html_e( 'Summary', 'wb-todo' ); ?></label></td>
			<td>
				<?php wp_editor( '', 'bptodo-summary-input', array( 'media_buttons' => true, 'editor_height' => 200 ) ); ?>
			</td>
		</tr>
		<tr>
			<td><label><?php esc_html_e( 'Due Date', 'wb-todo' ); ?></label></td>
			<td><input type="text" placeholder="<?php esc_html_e( 'Due Date', 'wb-todo' ); ?>" name="todo_due_date" class="todo_due_date bptodo-text-input" <?php echo esc_attr( $bptodo_req ); ?>></td>
		</tr>
		<tr>
			<td><label><?php esc_html_e( 'Priority', 'wb-todo' ); ?></label></td>
			<td>
				<select name="todo_priority" id="bp_todo_priority">
					<option value=""><?php esc_html_e( '--Select--', 'wb-todo' ); ?></option>
					<option value="critical"><?php esc_html_e( 'Critical', 'wb-todo' ); ?></option>
					<option value="high"><?php esc_html_e( 'High', 'wb-todo' ); ?></option>
					<option value="normal" selected><?php esc_html_e( 'Normal', 'wb-todo' ); ?></option>
				</select>
			</td>
		</tr>
		<tr>
			<td><label><?php esc_html_e( 'Group members', 'wb-todo' ); ?></label></td>
			<td>
				<select name="todo_group_members[]" id="todo_group_members" multiple placeholder="<?php esc_html_e( 'Please select group members to assign the Todo', 'wb-todo' ); ?>">
					<option value="all"><?php esc_html_e( 'All Members', 'wb-todo' ); ?></option>
					<?php foreach ( $members_ids as $member_id => $member_name ) : ?>
						<option value="<?php echo esc_attr( $member_id ); ?>"><?php echo esc_html( $member_name ); ?></option>
					<?php endforeach; ?>
				</select>
			</td>
		</tr>
		<tr>
			<td style="padding: 0;"></td>
			<td style="padding: 0;">
				<input type="hidden" name="todo_group_id" value="<?php echo esc_attr( $group_id ); ?>">
			</td>
		</tr>
		<?php $change_submit_btn = apply_filters( 'bp_group_todo_change_submit_button', false ); ?>
		<?php if ( ! $change_submit_btn ) : ?>
			<tr>
				<td></td>
				<td>
					<?php wp_nonce_field( 'wp-bp-todo', 'group_save_new_todo_data_nonce' ); ?>
						<?php /* translators: %s */ ?>
					<input id="bp-add-new-todo" type="submit" name="group_todo_create" value="<?php echo esc_html( sprintf( __( 'Submit %s', 'wb-todo' ), $profile_menu_label ) ); ?>">
				</td>
			</tr>
		<?php else : ?>
			<?php do_action( 'bp_group_todo_change_submit_button_action', $profile_menu_label ); ?>
		<?php endif; ?>
		<?php do_action( 'bp_group_todo_add_field_after_default_listing', $displayed_uid, $form_post_link ); ?>
	</table>
</form>
