<?php

namespace Limb_Chatbot\Includes\Data_Objects;

use Exception;
use Limb_Chatbot\Includes\Services\Data_Object_Collection;

/**
 * Class Chatbot_Meta
 *
 * Handles metadata operations related to chatbots,
 * adapting the underlying meta system to use 'post_id' internally
 * while allowing external use of 'chatbot_id' for clarity.
 *
 * @package Limb_Chatbot\Includes\Data_Objects
 * @since 1.0.0
 */
class Chatbot_Meta extends WP_Meta_Data_Object {

	/**
	 * Meta key constant used to flag an error on save.
	 */
	const KEY_ERROR_ON_SAVE = '_error_on_save';

	/**
	 * Create a new Chatbot_Meta record.
	 *
	 * Supports using 'chatbot_id' as an alias for 'post_id'.
	 *
	 * @param array $data Data to create the meta record.
	 * @return static Newly created Chatbot_Meta instance.
	 */
	public static function create( $data ) {
		$data['post_id'] = $data['chatbot_id'] ?? $data['post_id'];
		unset( $data['chatbot_id'] );

		return parent::create( $data );
	}


	/**
	 * Update Chatbot_Meta records matching conditions.
	 *
	 * Supports using 'chatbot_id' as an alias for 'post_id'.
	 *
	 * @param  array  $where  Conditions for update.
	 * @param  array  $data  Data to update.
	 *
	 * @return Chatbot_Meta True on success, false otherwise.
	 * @throws Exception
	 */
	public static function update( $where, $data ) {
		$where['post_id'] = $where['chatbot_id'] ?? $where['post_id'];
		unset( $where['chatbot_id'] );

		return parent::update( $where, $data );
	}

	/**
	 * Retrieve Chatbot_Meta records matching conditions.
	 *
	 * Supports using 'chatbot_id' as an alias for 'post_id'.
	 *
	 * @param array $where Conditions for query.
	 * @param mixed ...$args Additional arguments for query.
	 * @return Data_Object_Collection Collection of Chatbot_Meta objects.
	 */
	public static function where( $where, ...$args ): Data_Object_Collection {
		if ( isset( $where['chatbot_id'] ) ) {
			$where['post_id'] = $where['chatbot_id'];
			unset( $where['chatbot_id'] );
		}

		return parent::where( $where, $args );
	}

	/**
	 * Delete Chatbot_Meta records matching conditions.
	 *
	 * Supports using 'chatbot_id' as an alias for 'post_id'.
	 *
	 * @param array $where Conditions for deletion.
	 * @return bool True on success, false otherwise.
	 */
	public static function delete( $where ): bool {
		if ( isset( $where['chatbot_id'] ) ) {
			$where['post_id'] = $where['chatbot_id'];
			unset( $where['chatbot_id'] );
		}

		return parent::delete( $where );
	}
}