<?php

namespace GP_Entry_Blocks;

use GFAPI;
use GFCommon;

class Permissions {

	/**
	 * Checks if user can edit/delete an entry. If the user is logged in and they are the creator then they will
	 * be able to edit/delete the entry.
	 *
	 * @param array|int $entry Entry or the ID of the entry to check.
	 *
	 * @return bool
	 */
	public function can_current_user_edit_entry( $entry ) {

		if ( is_numeric( $entry ) ) {
			$entry = GFAPI::get_entry( $entry );
		}

		if ( ! $entry || is_wp_error( $entry ) ) {
			return false;
		}

		$can_user_edit_entry = false;
		$current_user        = get_current_user_id();

		if ( GFCommon::current_user_can_any( 'gravityforms_edit_entries' ) ) {
			$can_user_edit_entry = true;
		}

		if ( $current_user > 0 && $current_user === (int) $entry['created_by'] ) {
			$can_user_edit_entry = true;
		}

		/**
		 * Filter whether the current user has permission to edit/delete the given entry.
		 *
		 * @param bool $can_user_edit_entry Can the current user edit/delete the given entry?
		 * @param array $entry Current entry.
		 * @param \WP_User $user Current user.
		 *
		 * @since 1.0
		 */
		$can_user_edit_entry = apply_filters( 'gpeb_can_user_edit_entry', $can_user_edit_entry, $entry, $current_user );

		return $can_user_edit_entry;

	}

}
