<?php

namespace GemBoards\Entities;

use GemBoards\Classes\AbstractEntity;
use GemBoards\Classes\Exception\GemboardsException;


class Notification extends AbstractEntity {

	protected string $table       = 'gemboards_notifications';
	protected string $object_type = 'notification';

	protected array $data = [
		'from_user_id' => 0,
		'object_id'    => 0,
		'object_type'  => 'board',
		'event_type'   => '',
		'message'      => '',
		'meta'         => '',
		'created_at'   => '',
	];

	public function get_from_user_id( string $context = 'view' ): int {
		return (int) $this->get_prop( 'from_user_id', $context );
	}

	public function get_object_id( string $context = 'view' ) {
		return $this->get_prop( 'object_id', $context );
	}

	public function get_notification_object_type( string $context = 'view' ) {
		return $this->get_prop( 'object_type', $context );
	}

	public function get_event_type( string $context = 'view' ) {
		return $this->get_prop( 'event_type', $context );
	}

	public function get_message( string $context = 'view' ) {
		return $this->get_prop( 'message', $context );
	}

	public function get_notification_meta( string $context = 'view' ) {
		return $this->get_prop( 'meta', $context );
	}

	public function get_date_created( string $context = 'view' ) {
		return $this->get_prop( 'created_at', $context );
	}

	public function get_notified_users() {
		try {
			return ( new NotifiedUser( [
				'per_page' => - 1,
				'where'    => [
					[
						'key'   => 'notification_id',
						'value' => $this->get_id(),
					],
				],
			] ) );
		} catch ( GemboardsException $e ) {
			return [];
		}
	}

	public function set_from_user_id( int $from_user_id ): void {
		$this->set_prop( 'from_user_id', $from_user_id );
	}

	public function set_object_id( ?int $object_id ): void {
		$this->set_prop( 'object_id', $object_id );
	}

	public function set_notification_object_type( string $object_type ): void {
		$this->set_prop( 'object_type', $object_type );
	}

	public function set_event_type( string $event_type ): void {
		$this->set_prop( 'event_type', $event_type );
	}

	public function set_message( string $message ): void {
		$this->set_prop( 'message', $message );
	}

	public function set_meta( $meta ) {
		$this->set_notification_meta( $meta );
	}

	public function set_notification_meta( $meta ): void {
		$this->set_prop( 'meta', is_string( $meta ) ? json_decode( $meta ) : $meta );
	}

	protected function prepare_for_db( string $context = 'create' ): array {
		$data                        = parent::prepare_for_db( $context );
		$data['data']['object_type'] = $this->get_notification_object_type();
		$data['data']['meta']        = wp_json_encode( $this->get_notification_meta() );

		return $data;
	}

}
