<?php

namespace GemBoards;

use GemBoards\Utils\Helper;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class RewriteRules {
	public static function init() {
		$self = new self();
		add_action( 'init', array( $self, 'add_rewrite_rules' ) );
		add_filter( 'query_vars', array( $self, 'set_query_vars' ) );
	}

	public function add_rewrite_rules() {
		// Agile Method

		// Project
		// └── Sprints
		//     └── Boards (views of sprint tasks)

		// === Workspace Root ===
		$path = Helper::get_settings( 'path', 'workspace' );
		add_rewrite_rule(
			"^$path/?$",
			"index.php?gemboards_app_route=$path",
			'top'
		);

		// === Boards ===
		add_rewrite_rule(
			"^$path/boards/?$",
			'index.php?gemboards_app_route=boards',
			'top'
		);

		add_rewrite_rule(
			"^$path/boards/([0-9]+)/?$",
			'index.php?gemboards_app_route=boards&board_id=$matches[1]',
			'top'
		);

		add_rewrite_rule(
			"^$path/boards/([0-9]+)/backlog/?$",
			'index.php?gemboards_app_route=boards/backlog&board_id=$matches[1]',
			'top'
		);

		// === Projects & Sprints ===
		add_rewrite_rule(
			"^$path/projects/([0-9]+)/sprints/?$",
			'index.php?gemboards_app_route=projects/sprints&project_id=$matches[1]',
			'top'
		);

		add_rewrite_rule(
			"^$path/projects/([0-9]+)/sprints/([0-9]+)/?$",
			'index.php?gemboards_app_route=projects/sprints/view&project_id=$matches[1]&sprint_id=$matches[2]',
			'top'
		);

		add_rewrite_rule(
			"^$path/projects/([0-9]+)/sprints/([0-9]+)/board/?$",
			'index.php?gemboards_app_route=projects/sprints/board&project_id=$matches[1]&sprint_id=$matches[2]',
			'top'
		);

		add_rewrite_rule(
			"^$path/projects/([0-9]+)/?$",
			'index.php?gemboards_app_route=projects&project_id=$matches[1]',
			'top'
		);

		add_rewrite_rule(
			"^$path/projects/([0-9]+)/folders/([0-9]+)/?$",
			'index.php?gemboards_app_route=projects&project_id=$matches[1]&folder_id=$matches[2]',
			'top'
		);

		// === Teams ===
		add_rewrite_rule(
			"^$path/team/([0-9]+)/?$",
			'index.php?gemboards_app_route=team&team_id=$matches[1]',
			'top'
		);
		// === Profile ===
		add_rewrite_rule(
			"^$path/profile/?$",
			'index.php?gemboards_app_route=profile',
			'top'
		);

		// Settings
		add_rewrite_rule(
			"^$path/settings/?$",
			'index.php?gemboards_app_route=settings',
			'top'
		);

		add_rewrite_rule(
			"^$path/login/?$",
			'index.php?gemboards_app_route=login',
			'top'
		);
	}

	public function set_query_vars( $vars ) {
		$vars[] = 'gemboards_app_route';
		$vars[] = 'board_id';
		$vars[] = 'project_id';
		$vars[] = 'sprint_id';
		$vars[] = 'team_id';

		return $vars;
	}
}
