<?php

namespace GemBoards;

use GemBoards\Utils\Helper;

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

class Database {

	public static function init() {
		$self = new self();
		add_action( 'init', [ $self, 'register_post_type' ] );
		add_action( 'init', [ $self, 'add_role' ] );
		add_action( 'init', [ $self, 'register_taxonomy' ] );
		add_action( 'init', [ $self, 'register_taxonomy_meta' ] );
		add_action( 'init', [ $self, 'create_initial_labels' ] );
		add_action( 'init', [ $self, 'register_user_meta' ] );
	}

	public static function create_initial_custom_table() {
		if ( ! function_exists( 'dbDelta' ) ) {
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		}

		global $wpdb;
		$prefix          = $wpdb->prefix;
		$charset_collate = $wpdb->get_charset_collate();
		Database\CreateBoardsTable::up( $prefix, $charset_collate );
		Database\CreateColumnsTable::up( $prefix, $charset_collate );
		Database\CreateCardsTable::up( $prefix, $charset_collate );
		Database\CreateCardAssigneesTable::up( $prefix, $charset_collate );
		Database\CreateTaskAttachmentsTable::up( $prefix, $charset_collate );
		Database\CreateNotificationTable::up( $prefix, $charset_collate );
		Database\CreateNotifiedUsersTable::up( $prefix, $charset_collate );
		Database\CreateFoldersTable::up( $prefix, $charset_collate );
		Database\CreateProjectsTable::up( $prefix, $charset_collate );
		Database\CreatePermissionsTable::up( $prefix, $charset_collate );
		Database\CreateUserInvitationTable::up( $prefix, $charset_collate );
		Database\CreateFavouriteBoardsTable::up( $prefix, $charset_collate );
		Database\CreateBoardVisitsTable::up( $prefix, $charset_collate );
		Database\CreateBookmarksTable::up( $prefix, $charset_collate );
	}

	public static function add_role() {
		add_role(
			'gemboards_admin',
			__( 'GemBoards Admin', 'gemboards' ),
			array(
				'read' => true,
			)
		);
	}

	public function register_post_type() {
		$post_type = GEMBOARDS_PLUGIN_SLUG . '_task';
		register_post_type( $post_type, [
			'label'                 => 'Task',
			'public'                => true,
			'publicly_queryable'    => false,
			'show_ui'               => false,
			'show_in_menu'          => false,
			'show_in_admin_bar'     => false,
			'show_in_nav_menus'     => false,
			'hierarchical'          => false,
			'supports'              => array( 'title', 'editor', 'author', 'excerpt', 'custom-fields', 'comments' ),
			'show_in_rest'          => true,
			'rest_base'             => $post_type,
			'rest_namespace'        => GEMBOARDS_PLUGIN_SLUG . '/v1',
			'rest_controller_class' => 'WP_REST_Posts_Controller',
			'capability_type'       => 'post',
			'capabilities'          => array(
				'edit_post'          => 'edit_gemboards_task',
				'read_post'          => 'read_gemboards_task',
				'delete_post'        => 'delete_gemboards_task',
				'delete_posts'       => 'delete_gemboards_tasks',
				'edit_posts'         => 'edit_gemboards_tasks',
				'edit_others_posts'  => 'edit_others_gemboards_tasks',
				'publish_posts'      => 'publish_gemboards_tasks',
				'read_private_posts' => 'read_private_gemboards_tasks',
				'create_posts'       => 'edit_gemboards_tasks',
			),
		] );
	}

	public function register_taxonomy() {
		$post_type = GEMBOARDS_PLUGIN_SLUG . '_task';

		register_taxonomy( GEMBOARDS_PLUGIN_SLUG . '_priority', $post_type, [
			'label'          => 'Priority',
			'public'         => true,
			'hierarchical'   => false,
			'rest_namespace' => GEMBOARDS_PLUGIN_SLUG . '/v1',
			'show_in_rest'   => true,
		] );

		register_taxonomy( GEMBOARDS_PLUGIN_SLUG . '_label', $post_type, [
			'label'          => 'Labels',
			'public'         => true,
			'hierarchical'   => false,
			'rest_namespace' => GEMBOARDS_PLUGIN_SLUG . '/v1',
			'show_in_rest'   => true,
			'capabilities'   => [
				'manage_terms' => 'manage_gemboards_labels',
				'edit_terms'   => 'manage_gemboards_labels',
				'delete_terms' => 'manage_gemboards_labels',
				'assign_terms' => 'manage_gemboards_labels',
			],
		] );
	}

	public function register_taxonomy_meta() {
		$taxonomy = GEMBOARDS_PLUGIN_SLUG . '_label';

		register_term_meta( $taxonomy, 'bg_color', [
			'type'              => 'string',
			'description'       => 'Background color',
			'single'            => true,
			'sanitize_callback' => 'sanitize_hex_color',
			'show_in_rest'      => true,
		] );

		register_term_meta( $taxonomy, 'text_color', [
			'type'              => 'string',
			'description'       => 'Text color',
			'single'            => true,
			'sanitize_callback' => 'sanitize_hex_color',
			'show_in_rest'      => true,
		] );
	}

	public function create_initial_labels() {
		$is_created = get_option( 'gemboards_initial_labels_created', false );

		if ( $is_created ) {
			return;
		}

		$taxonomy = GEMBOARDS_PLUGIN_SLUG . '_label';
		$labels   = Helper::config( 'default_labels' );

		if ( empty( $labels ) ) {
			update_option( 'gemboards_initial_labels_created', true );

			return;
		}

		$all_created_successfully = true;

		foreach ( $labels as $label ) {
			if ( ! term_exists( $label['title'], $taxonomy ) ) {
				$term = wp_insert_term( $label['title'], $taxonomy, [
					'slug' => sanitize_title( $label['title'] ),
				] );

				if ( is_wp_error( $term ) ) {
					$all_created_successfully = false;
					continue;
				}

				$term_id = $term['term_id'];
				update_term_meta( $term_id, 'bg_color', $label['bg_color'] );
				update_term_meta( $term_id, 'text_color', $label['text_color'] );
			}
		}

		if ( $all_created_successfully ) {
			update_option( 'gemboards_initial_labels_created', true );
		}
	}

	public function register_user_meta() {
		register_meta( 'user', 'gemboards_avatar', [
			'type'          => 'string',
			'description'   => __( 'Gemboards user avatar for the user', 'gemboards' ),
			'single'        => true,
			'show_in_rest'  => true,
			'auth_callback' => fn() => current_user_can( 'edit_user', get_current_user_id() ),
		] );
		register_meta( 'user', 'gemboards_recently_open', [
			'type'          => 'array',
			'description'   => __( 'Gemboards user recently opened boards', 'gemboards' ),
			'single'        => true,
			'show_in_rest'  => [
				'type'   => 'array',
				'schema' => [
					'items' => [
						'type'       => 'object',
						'properties' => [
							'board_id'   => [
								'type'        => 'integer',
								'description' => __( 'Board ID', 'gemboards' ),
							],
							'board_type' => [
								'type'        => 'string',
								'description' => __( 'Board type', 'gemboards' ),
							],
						],
					],
				],
			],
			'auth_callback' => fn() => current_user_can( 'edit_user', get_current_user_id() ),
		] );
	}
}
