<?php

namespace GemBoards\Collections;

use GemBoards\Classes\AbstractCollection;
use GemBoards\Classes\Exception\GemboardsException;
use GemBoards\Classes\Exception\GemboardsInvalidArgumentException;
use GemBoards\Entities\Board;
use GemBoards\Utils\Helper;

class BoardCollection extends AbstractCollection {

	protected string $table = 'gemboards_boards';

	protected string $object_type = 'board';

	protected string $primary_key = 'id';

	protected string $order_by = 'id'; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase

	protected string $order       = 'ASC';
	protected string $return_type = Board::class; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase

	/**
	 * @param int $user_id
	 * @param string $status
	 *
	 * @return Board[]
	 */
	public static function get_boards_for_user( int $user_id = 0, string $status = 'active' ): array {
		if ( ! $user_id ) {
			$user_id = get_current_user_id();
		}
		if ( ! $user_id ) {
			return [];
		}

		if ( current_user_can( 'manage_gemboards' ) ) {
			try {
				return ( new self( [
					'per_page' => - 1,
					'where'    => [
						[
							'key'   => 'board_status',
							'value' => $status,
						],
					],
				] ) )->get_results();
			} catch ( GemboardsInvalidArgumentException $e ) {
				Helper::error_log( $e->getMessage() );
				return [];
			}
		}

		$cache_key   = "gemboards_boards_for_user_$user_id";
		$cache_group = 'gemboards_boards';
		$has_cache   = wp_cache_get( $cache_key, $cache_group );
		if ( $has_cache ) {
			$results = $has_cache;
		} else {
			global $wpdb;
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
			$results = $wpdb->get_results(
				$wpdb->prepare( "SELECT board.id from {$wpdb->prefix}gemboards_boards board INNER JOIN {$wpdb->prefix}gemboards_roles role ON role.object_id = board.project_id AND role.object_type = 'project' AND role.user_id = %d WHERE board.board_status = %s GROUP BY board.id", $user_id, $status )
			);
			// phpcs:enable
		}

		$boards = [];
		foreach ( $results as $result ) {
			try {
				$board    = new Board( absint( $result->id ) );
				$boards[] = $board;
			} catch ( GemboardsException $e ) {
				continue;
			}
		}

		wp_cache_set( $cache_key, $boards, $cache_group );

		return $boards;
	}
}
