<?php
/**
 * Setup Reaction Component
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Components;

defined( 'ABSPATH' ) || die( 'Shame on you' );

if ( ! class_exists( '\\Dekode\\Nisje\\Components\\Reaction' ) && class_exists( '\\Dekode\\Nisje\\Components\\Component' ) ) {

	/**
	 * Reaction Component Class
	 */
	class Reaction extends Component {
		/**
		 * Constructor
		 */
		public function __construct() {
			$path               = trailingslashit( dirname( __FILE__ ) );
			$name               = 'reaction';
			$this->settings_key = 'nisje_reaction';
			$this->db_version   = 1;

			parent::start(
				$name,
				esc_html__( 'Reaction', 'nisje' ),
				$path
			);
		}

		/**
		 * Global variables
		 */
		public function includes() {
			$this->include_file( 'helper-functions.php' );
			$this->include_file( 'classes/class-nisje-reaction.php' );
		}

		/**
		 * Global variables
		 */
		public function setup_globals() {
			global $wpdb;

			$settings = get_option( $this->settings_key );
			if ( is_array( $settings ) && ! empty( $settings ) ) {
				foreach ( $settings as $key => $value ) {
					$this->settings[ $key ] = $value;
				}
			}

			// Setup default reaction.
			$defaults = [
				'reaction_types' => [
					1 => [
						'name'        => 'like',
						'emoji'       => 0x2764,
						'description' => __( 'Liked an update', 'nisje' ),
						'label'       => __( 'Likes', 'nisje' ),
					],
				],
				'name'           => $this->name,
				'cache_key'      => 'nisje_reactions',
			];

			// Setup db table.
			$wpdb->nisje_reactions = $wpdb->prefix . 'nisje_reactions';

			$this->settings = wp_parse_args( $this->settings, $defaults );
		}

		/**
		 * Updates
		 */
		public function updates() {
			global $wpdb;

			require_once ABSPATH . '/wp-admin/includes/upgrade.php';

			$charset_collate = '';
			if ( ! empty( $wpdb->charset ) ) {
				$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
			}

			if ( ! empty( $wpdb->collate ) ) {
				$charset_collate .= " COLLATE $wpdb->collate";
			}

			$sql = 'CREATE TABLE IF NOT EXISTS ' . $wpdb->nisje_reactions . " (
				id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
				object_id bigint(20) unsigned NOT NULL,
				user_id bigint(20) unsigned NOT NULL,
				object_type varchar(20) NOT NULL DEFAULT 'post',
				reaction_type_id bigint(20) unsigned NOT NULL,
				date_created datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
				date_modified datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
				PRIMARY KEY (id),
				KEY reactions (object_id, user_id, object_type),
				KEY reactions_type (object_id, user_id, object_type, reaction_type_id)
			) $charset_collate;";
			dbDelta( $sql );

			$this->settings['db_version'] = $this->db_version;
			$this->save_options();
		}

		/**
		 * Setup filters.
		 */
		public function setup_filters() {
			/**
			 * Add caching.
			 * add_action( 'nisje_add_reaction', [ $this, 'update_cache_add' ], 10, 4 );
			 * add_action( 'nisje_remove_reaction', [ $this, 'update_cache_remove' ], 10, 4 );
			 */
		}

		/**
		 * Register REST Endpoints
		 */
		public function register_rest_routes() {
			$this->include_file( 'rest-handlers/extend-comment.php' );
			$this->include_file( 'rest-handlers/class-reaction-controller.php' );
			$this->include_file( 'rest-handlers/class-reactions-controller.php' );

			$controller = new \Dekode\Nisje\Components\Rest\Reaction_Controller();
			$controller->register_routes();

			$controller = new \Dekode\Nisje\Components\Rest\Reactions_Controller();
			$controller->register_routes();
		}

		/**
		 * Update meta cache counter.
		 *
		 * @param int    $object_id        Object ID.
		 * @param int    $user_id          User ID.
		 * @param string $object_type      Object Type.
		 * @param string $reaction_type_id Reaction type ID.
		 *
		 * @return void
		 */
		public function update_cache_add( $object_id, $user_id, $object_type, $reaction_type_id ) {
			$counter = get_metadata( $object_type, $object_id, nisje_get_setting( 'cache_key', 'reaction' ), true );

			if ( ! is_array( $counter ) ) {
				$counter = [];
			} else {
				if ( ! isset( $counter[ $reaction_type_id ] ) ) {
					$counter[ $reaction_type_id ] = 0;
				}
			}

			$counter[ $reaction_type_id ] = (int) $counter[ $reaction_type_id ] + 1;

			update_metadata( $object_type, $object_id, nisje_get_setting( 'cache_key', 'reaction' ), $counter );
		}

		/**
		 * Update meta cache counter.
		 *
		 * @param int    $object_id        Object ID.
		 * @param int    $user_id          User ID.
		 * @param string $object_type      Object Type.
		 * @param string $reaction_type_id Reaction type ID.
		 *
		 * @return void
		 */
		public function update_cache_remove( $object_id, $user_id, $object_type, $reaction_type_id ) {
			$counter = get_metadata( $object_type, $object_id, nisje_get_setting( 'cache_key', 'reaction' ), true );

			if ( ! is_array( $counter ) ) {
				$counter = [];
			} else {
				if ( ! isset( $counter[ $reaction_type_id ] ) ) {
					$counter[ $reaction_type_id ] = 0;
				}
			}

			if ( 0 < (int) $counter[ $reaction_type_id ] ) {
				$counter[ $reaction_type_id ] = (int) $counter[ $reaction_type_id ] - 1;
			}

			update_metadata( $object_type, $object_id, nisje_get_setting( 'cache_key', 'reaction' ), $counter );
		}
	}
}
