<?php

namespace GemBoards\utils\traits;

use Exception;
use GemBoards\Classes\Exception\GemboardsException;
use GemBoards\Entities\Folder;
use GemBoards\Entities\Role;
use GemBoards\Entities\UserInvitation;

trait Project {

	public static function get_project( int $id ) {
		try {
			return new \GemBoards\Entities\Project( $id );
		} catch ( GemBoardsException | Exception $e ) {
			return false;
		}
	}

	public static function get_folder( int $id ) {
		try {
			return new Folder( $id );
		} catch ( GemBoardsException | Exception $e ) {
			return false;
		}
	}

	public static function get_role( int $id ) {
		try {
			return new Role( $id );
		} catch ( GemBoardsException | Exception $e ) {
			return false;
		}
	}

	public static function get_user_project_role( int $project_id, int $user_id ) {
		if ( ! $project_id || ! $user_id ) {
			return false;
		}

		global $wpdb;

		$cache_key = "project_role:$project_id:$user_id";
		$id        = wp_cache_get( $cache_key, 'gemboards_projects' );

		if ( false !== $id ) {
			return self::get_role( $id );
		}

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
		$id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT object_id FROM {$wpdb->prefix}gemboards_roles WHERE object_id = %d AND object_type = 'project' AND user_id = %d LIMIT 1;", $project_id, $user_id ) );
		// phpcs:enable

		wp_cache_set( $cache_key, $id, 'gemboards_projects', DAY_IN_SECONDS );

		if ( ! $id ) {
			return false;
		}

		try {
			return new Role( $id );
		} catch ( GemBoardsException | Exception $e ) {
			return false;
		}
	}

	public static function get_user_invitation( int $id ) {
		try {
			return new UserInvitation( $id );
		} catch ( GemBoardsException | Exception $e ) {
			return false;
		}
	}

	public static function get_invitation_id_from_hash( string $hash ) {
		$cache_group   = 'gemboards_user_invitations';
		$last_changed  = wp_cache_get_last_changed( $cache_group );
		$cache_key     = "user_invitation_id_{$hash}:$last_changed";
		$invitation_id = wp_cache_get( $cache_key, $cache_group );

		if ( false === $invitation_id ) {
			global $wpdb;
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
			$invitation_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}gemboards_user_invitations WHERE hash = %s", $hash ) );
			// phpcs:enable
			$invitation_id = absint( $invitation_id );
			wp_cache_set( $cache_key, $invitation_id, $cache_group );
		}

		return $invitation_id;
	}
}
