<?php

namespace Simple_Giveaways;

/**
 * Class SG_Action_Visit
 */
class SG_Action_Image extends SG_Extra_Action {

	/**
	 * Is this action using the action button.
	 *
	 * @var bool
	 */
	protected $has_action_button = false;

	/**
	 * Is the form complete button disabled at first?
	 *
	 * @var bool
	 */
	protected $submit_disabled = false;

	/**
	 * SG_Action_Visit constructor.
	 */
	public function __construct() {
		$this->slug        = 'image';
		$this->category    = 'general';
		$this->title       = __( 'Upload an Image', 'giveasap' );
		$this->description = __( 'Rewards the user for uploading an image.', 'giveasap' );
		$this->icon        = 'fal fa-image';
	}

	/**
	 * This function is used when completing the action.
	 *
	 * @return bool
	 */
	public function needs_validation() {
		return false;
	}

	/**
	 * This is the value that we will show on the Entries table.
	 */
	public function get_value_for_entries_table( $data ) {

		if ( isset( $data['attachment_id'] ) ) {
			$image = wp_get_attachment_image_src( $data['attachment_id'], 'full' );
			return '<a class="sg-image-popup-link" href="' . esc_url_raw( $image[0] ) . '">' . wp_get_attachment_image( $data['attachment_id'], 'medium' ) . '</a>';
		}
		return '';
	}


	/**
	 * GForm Public
	 */
	public function form_public_content() {
		$data = $this->get_data();
		if ( $this->is_completed() ) {
			$att_id = isset( $data['data']['attachment_id'] ) ? $data['data']['attachment_id'] : false;
			if ( $att_id ) {
				echo wp_get_attachment_image( $att_id, 'full' );
			}
			return;
		}
		?>
		<input type="file" name="image" />
		<?php
	}

	/**
	 * @param array $action
	 *
	 * @return array|\WP_Error
	 */
	public function complete_action( $action, $data = array() ) {
        $attachment_id = Helpers::upload_image( 'image' );

		if ( is_wp_error( $attachment_id ) ) {
			return $attachment_id;
		}

		return array( 'attachment_id' => $attachment_id );
	}

}