<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class WaicAction_wp_update_post_image extends WaicAction {
	protected $_code = 'wp_update_post_image';
	protected $_order = 12;
	
	public function __construct( $block = null ) {
		$this->_name = __('Update Post Featured image', 'ai-copilot-content-generator');
		//$this->_desc = __('Only filled fields will be updated.', 'ai-copilot-content-generator');
		$this->setBlock($block);
	}
	public function getSettings() {
		if (empty($this->_settings)) {
			$this->setSettings();
		}
		return $this->_settings;
	}
	
	public function setSettings() {
		$this->_settings = array(
			'id' => array(
				'type' => 'input',
				'label' => __('Post ID *', 'ai-copilot-content-generator'),
				'default' => '',
				'variables' => true,
			),
			'image' => array(
				'type' => 'input',
				'label' => __('Image ID *', 'ai-copilot-content-generator'),
				'default' => '',
				'variables' => true,
			),
			'alt' => array(
				'type' => 'input',
				'label' => __('Image Alt', 'ai-copilot-content-generator'),
				'default' => '',
				'variables' => true,
			),
		);
	}
	public function getVariables() {
		if (empty($this->_variables)) {
			$this->setVariables();
		}
		return $this->_variables;
	}
	public function setVariables() {
		$this->_variables = $this->getPostVariables();
		return $this->_variables;
	}
	public function getResults( $taskId, $variables, $step = 0 ) {
		$error = '';
		$postId = (int) $this->replaceVariables($this->getParam('id'), $variables);
		$image = (int) $this->replaceVariables($this->getParam('image'), $variables);
		
		if (empty($postId)) {
			$error = 'Post ID needed';
		} else if (empty($image)) {
			$error = 'Image ID needed';
		} else {
			$post = get_post($postId);
			if (!$post) {
				$error = 'Post not found (ID=' . $postId . ')';
			}
		}
		if (empty($error)) {
			$alt = $this->replaceVariables($this->getParam('alt'), $variables);
			if (empty($alt)) {
				$alt = $post->post_title;
			}
			$error = $this->addPostImage($postId, $image, $alt);
		}
		
		$this->_results = array(
			'result' => array('waic_post_id' => $postId, 'image_id' => $image, 'alt' => $alt),
			'error' => $error,
			'status' => empty($error) ? 3 : 7,
		);
		return $this->_results;
	}
}
