<?php

namespace GemBoards\Ajax;

use GemBoards\Classes\AbstractAjaxHandler;
use GemBoards\RewriteRules;
use GemBoards\Settings\Base;

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

class Setting extends AbstractAjaxHandler {

	public function __construct() {
		$this->actions = [
			'get_profile_settings'    => [
				'callback' => [ $this, 'get_profile_settings' ],
			],
			'update_profile_settings' => [
				'callback' => [ $this, 'update_profile_settings' ],
				'fields'   => [
					'first_name'           => 'string',
					'last_name'            => 'string',
					'email'                => 'email',
					'avatar_attachment_id' => 'int',
				],
			],
			'get_settings'            => [
				'callback' => [ $this, 'get_settings' ],
			],
			'update_settings'         => [
				'callback'   => [ $this, 'update_settings' ],
				'capability' => 'manage_gemboards',
				'fields'     => [
					'title'                 => 'string',
					'path'                  => 'string',
					'logo'                  => 'int',
					'load_on_entire_site'   => 'boolean',
					'notification_position' => 'string',
					'permissions'           => [
						'update_projects' => [
							'guest'   => 'boolean',
							'member'  => 'boolean',
							'manager' => 'boolean',
							'admin'   => 'boolean',
						],
						'view_projects'   => [
							'guest'   => 'boolean',
							'member'  => 'boolean',
							'manager' => 'boolean',
							'admin'   => 'boolean',
						],
						'manage_tasks'    => [
							'guest'   => 'boolean',
							'member'  => 'boolean',
							'manager' => 'boolean',
							'admin'   => 'boolean',
						],
						'manage_stages'   => [
							'guest'   => 'boolean',
							'member'  => 'boolean',
							'manager' => 'boolean',
							'admin'   => 'boolean',
						],
						'allow_comments'  => [
							'guest'   => 'boolean',
							'member'  => 'boolean',
							'manager' => 'boolean',
							'admin'   => 'boolean',
						],
					],
					'notifications'         => [
						'assign_tasks'   => [
							'gemboards' => 'boolean',
							'email'     => 'boolean',
						],
						'unassign_tasks' => [
							'gemboards' => 'boolean',
							'email'     => 'boolean',
						],
						'stage_changes'  => [
							'gemboards' => 'boolean',
							'email'     => 'boolean',
						],
						'new_comment'    => [
							'gemboards' => 'boolean',
							'email'     => 'boolean',
						],
						'mention_user'    => [
							'gemboards' => 'boolean',
							'email'     => 'boolean',
						],
					],
				],
			],
		];
	}

	public function get_profile_settings() {
		$user   = wp_get_current_user();
		$avatar = get_user_meta( $user->ID, 'gemboards_avatar', true );
		if ( empty( $avatar ) ) {
			$avatar_url = get_avatar_url( $user->ID );
		} else {
			$avatar_url = wp_get_attachment_image_url( $avatar );
		}

		wp_send_json_success( [
			'first_name' => $user->first_name,
			'last_name'  => $user->last_name,
			'email'      => $user->user_email,
			'avatar'     => [
				'url'           => $avatar_url,
				'type'          => empty( $avatar_url ) ? 'gravatar' : 'custom',
				'attachment_id' => absint( $avatar ),
			],
		] );
	}

	public function update_profile_settings( array $payload ) {
		$user = wp_get_current_user();

		$existing_user = get_user_by( 'email', $payload['email'] );
		if ( $existing_user && $existing_user->ID !== $user->ID ) {
			wp_send_json_error( [
				'message' => __( 'This email is already registered.', 'gemboards' ),
			] );
		}

		$attachment_id = absint( $payload['avatar_attachment_id'] ?? '' );
		if ( $attachment_id ) {
			$attachment_url = wp_get_attachment_url( $attachment_id );
			if ( ! $attachment_url ) {
				wp_send_json_error( [
					'message' => __( 'Invalid profile image selected!', 'gemboards' ),
				] );
			}
			update_user_meta( $user->ID, 'gemboards_avatar', $attachment_id );
		} else {
			delete_user_meta( $user->ID, 'gemboards_avatar' );
		}

		$result = wp_update_user( [
			'ID'         => $user->ID,
			'first_name' => $payload['first_name'],
			'last_name'  => $payload['last_name'],
			'user_email' => $payload['email'],
		] );
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [
				'message' => $result->get_error_message(),
			] );
		}

		$this->get_profile_settings();
	}

	public function get_settings() {
		$default_data  = Base::get_settings_default_data();
		$saved_data    = Base::get_settings_saved_data();
		$settings_data = wp_parse_args( $saved_data, $default_data );

		if ( empty( $settings_data['logo'] ) ) {
			$settings_data['logo'] = str_replace( rtrim( site_url(), '/' ), '', plugins_url( '/assets/images/logo.svg', GEMBOARDS_PLUGIN_FILE ) );
		}

		if ( ! current_user_can( 'manage_gemboards' ) ) {
			unset( $settings_data['notifications'] );
			unset( $settings_data['permissions'] );
		}

		wp_send_json_success( $settings_data );
	}

	public function update_settings( array $payload ) {
		Base::save_settings( $payload );
		$GLOBALS['gemboards_settings'] = json_decode( get_option( GEMBOARDS_SETTINGS_NAME, '{}' ) );
		( new RewriteRules() )->add_rewrite_rules();
		flush_rewrite_rules();
		wp_send_json_success( $this->get_settings() );
	}

}
