<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use GemBoards\Entities\Notification;
use GemBoards\Entities\NotifiedUser;
use GemBoards\Utils\Helper;

if ( ! function_exists( 'gemboards_task_comment_query' ) ) {
	function gemboards_task_comment_query( $args, $request ) {
		if ( empty( $request['type'] ) ) {
			return $args;
		}

		if ( empty( $request['post'] ) ) {
			return $args;
		}

		$post_id          = (int) $request['post'];
		$target_post_type = get_post_type( $post_id );
		$post_type        = GEMBOARDS_PLUGIN_SLUG . '_task';

		if ( $target_post_type === $post_type ) {
			$args['type'] = sanitize_text_field( $request['type'] );
		}

		return $args;
	}
}

if ( ! function_exists( 'gemboards_task_comment_query_params' ) ) {
	function gemboards_task_comment_query_params( $params ) {
		$params['type'] = [
			'description'       => __( 'Filter comments by comment type', 'gemboards' ),
			'type'              => 'string',
			'sanitize_callback' => 'sanitize_text_field',
		];

		return $params;
	}
}

if ( ! function_exists( 'gemboards_task_mention_notification' ) ) {
	function gemboards_task_mention_notification( ?int $task_id, ?array $usernames ): void {
		$current_user = wp_get_current_user();
		if ( is_array( $usernames ) && ! empty( $current_user->user_login ) ) {
			$usernames = array_diff( $usernames, [ $current_user->user_login ] );
		}
		if ( empty( $usernames ) ) {
			return;
		}
		$task = get_post( $task_id );
		if ( ! $task ) {
			return;
		}

		$notification = new Notification();
		$notification->set_event_type( 'mentioned_in_task' );
		$notification->set_notification_object_type( 'task' );
		$notification->set_object_id( $task_id );
		$notification->set_from_user_id( get_current_user_id() );
		$notification->set_message(
		// translators: %s is the task title.
			sprintf( __( 'You are mentioned in %s', 'gemboards' ), $task->post_title
			) );
		$notification->set_meta( wp_json_encode( $task ) );
		$notification->save();
	}
}

if ( ! function_exists( 'gemboards_task_comment_mention_notification' ) ) {
	function gemboards_task_comment_mention_notification( ?int $task_comment_id, ?array $usernames ): void {
		$current_user = wp_get_current_user();
		if ( is_array( $usernames ) && ! empty( $current_user->user_login ) ) {
			$usernames = array_diff( $usernames, [ $current_user->user_login ] );
		}

		if ( empty( $usernames ) ) {
			return;
		}

		$task_comment = get_comment( $task_comment_id );
		if ( ! $task_comment ) {
			return;
		}
		$notification = new Notification();
		$notification->set_event_type( 'mentioned_in_task_comment' );
		$notification->set_object_id( $task_comment_id );
		$notification->set_notification_object_type( 'task' );
		$notification->set_message(
		// translators: %s is the comment author name.
			sprintf( __( 'You are mentioned in comment of %s', 'gemboards' ), $task_comment->comment_author )
		);
		$notification->set_meta( wp_json_encode( $task_comment ) );
		$notification->set_from_user_id( get_current_user_id() );
		$notification->save();

		$user_ids = get_users([
			'login__in' => ! is_array( $usernames ) ? [] : $usernames,
			'fields'    => 'ID',
		]);
		$user_ids = array_map('absint', $user_ids);

		foreach ( $user_ids as $to_user ) {
			$notified_user = new NotifiedUser();
			$notified_user->set_notification_id( $notification->get_id() );
			$notified_user->set_to_user_id( $to_user );
			$notified_user->save();
		}
	}
}

if ( ! function_exists( 'gemboards_board_member_assigned' ) ) {
	function gemboards_board_member_assigned( int $board_id, int $user_id ): void {
		try {
			$current_user = wp_get_current_user();
			$user         = get_userdata( $user_id );
			$comment      = sprintf(
			/* translators: 1: Name of an assigned user 2: Name of by-assigned user */
				__( '%1$s is assigned by %2$s', 'gemboards' ),
				$user->display_name,
				$current_user->display_name ?? 'System'
			);

			$board = Helper::get_board( $board_id );
			if ( ! $board ) {
				return;
			}

			$notification = new Notification();
			$notification->set_event_type( 'assigned_user_to_board' );
			$notification->set_notification_object_type( 'board' );
			$notification->set_object_id( $board_id );
			$notification->set_from_user_id( get_current_user_id() );
			$notification->set_meta( wp_json_encode( array_merge( $board->get_data(), [
				'id'         => $board->get_id(),
				'created_at' => $board->get_date_created_at() ? $board->get_date_created_at()->format( 'Y-m-d H:i:s' ) : null,
				'updated_at' => $board->get_date_updated_at() ? $board->get_date_updated_at()->format( 'Y-m-d H:i:s' ) : null,
			] ) ) );
			$notification->set_message( $comment );
			$notification->save();

			if ( ! $user_id ) {
				$notified_user = new NotifiedUser();
				$notified_user->set_notification_id( $notification->get_id() );
				$notified_user->set_to_user_id( $user_id );
				$notified_user->save();
			}
		} catch ( Throwable $e ) {
			Helper::error_log(sprintf(
				'Exception caught in %s on line %d: %s',
				$e->getFile(),
				$e->getLine(),
				$e->getMessage()
			));
		}
	}
}


if ( ! function_exists( 'gemboards_board_member_removed' ) ) {
	function gemboards_board_member_removed( int $board_id, int $user_id ): void {
		try {
			$current_user = wp_get_current_user();
			$user         = get_userdata( $user_id );
			$comment      = sprintf(
			/* translators: 1: Name of a removed user 2: Name of by-removed user */
				__( '%1$s is removed by %2$s', 'gemboards' ),
				$user->display_name,
				$current_user->display_name ?? 'System'
			);

			$board = Helper::get_board( $board_id );
			if ( ! $board ) {
				return;
			}

			$notification = new Notification();
			$notification->set_event_type( 'removed_user_from_board' );
			$notification->set_notification_object_type( 'board' );
			$notification->set_object_id( $board_id );
			$notification->set_from_user_id( get_current_user_id() );
			$notification->set_meta( wp_json_encode( array_merge( $board->get_data(), [
				'id'         => $board->get_id(),
				'created_at' => $board->get_date_created_at() ? $board->get_date_created_at()->format( 'Y-m-d H:i:s' ) : null,
				'updated_at' => $board->get_date_updated_at() ? $board->get_date_updated_at()->format( 'Y-m-d H:i:s' ) : null,
			] ) ) );
			$notification->set_message( $comment );
			$notification->save();

			if ( ! $user_id ) {
				$notified_user = new NotifiedUser();
				$notified_user->set_notification_id( $notification->get_id() );
				$notified_user->set_to_user_id( $user_id );
				$notified_user->save();
			}
		} catch ( Throwable $e ) {
			Helper::error_log(sprintf(
				'Exception caught in %s on line %d: %s',
				$e->getFile(),
				$e->getLine(),
				$e->getMessage()
			));
		}
	}
}

if ( ! function_exists( 'gemboards_top_bar_link' ) ) {
	function gemboards_top_bar_link( $wp_admin_bar ): void {
		if ( ! is_admin() && ! is_user_logged_in() ) {
			return;
		}

		$wp_admin_bar->add_node( [
			'id'     => 'visit_workspace',
			'title'  => __( 'Visit Workspace', 'gemboards' ),
			'href'   => home_url( Helper::get_settings( 'path', '' ) ),
			'meta'   => [
				'target' => '_blank',
				'title'  => 'Visit the workspace area',
			],
			'parent' => 'site-name',
		] );
	}
}
