<?php

namespace GemBoards\hooks;

use GemBoards\Classes\AbstractEntity;
use GemBoards\Classes\Exception\GemboardsInvalidArgumentException;
use GemBoards\Collections\RoleCollection;
use GemBoards\Entities\Board;
use GemBoards\Entities\Folder;
use GemBoards\Entities\Project;
use GemBoards\Entities\Role;
use GemBoards\Utils\Helper;


if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // if accessed directly, exit


class Menu {

	public static function init() {
		$self    = new self();
		$objects = [
			'project',
			'folder',
			'board',
			'role',
		];
		foreach ( $objects as $object_type ) {
			add_action( "gemboards/$object_type/after/object_save", [ $self, 'clear_cache' ] );
			add_action( "gemboards/$object_type/deleted", [ $self, 'clear_cache_after_deleted' ], 10, 2 );
		}
	}

	public function clear_cache( AbstractEntity $entity ) {
		$cache_group = 'gemboards_workspace_user_menu';
		$project_id  = null;

		if ( $entity instanceof Project ) {
			$project_id = $entity->get_id();
		} elseif ( $entity instanceof Board || $entity instanceof Folder ) {
			$project_id = $entity->get_project_id();
		} elseif ( $entity instanceof Role ) {
			$user_id   = $entity->get_user_id();
			$cache_key = 'menu_for_user_' . $user_id;
			wp_cache_delete( $cache_key, $cache_group );

			return;
		}

		if ( ! $project_id ) {
			return;
		}

		try {
			$roles = new RoleCollection( [
				'per_page' => - 1,
				'where'    => [
					[
						'key'   => 'object_type',
						'value' => 'project',
					],
					[
						'key'   => 'object_id',
						'value' => $project_id,
					],
				],
			] );
			foreach ( $roles as $role ) {
				$user_id   = $role->get_user_id();
				$cache_key = 'menu_for_user_' . $user_id;
				wp_cache_delete( $cache_key, $cache_group );
			}
		} catch ( GemboardsInvalidArgumentException $e ) {
			Helper::error_log( $e->getMessage() );
		}

		if ( current_user_can( 'manage_gemboards' ) ) {
			$cache_key = 'menu_for_user_' . get_current_user_id();
			wp_cache_delete( $cache_key, $cache_group );
		}
	}

	public function clear_cache_after_deleted( int $entity_id, AbstractEntity $entity ) {
		$this->clear_cache( $entity );
	}

}
