<?php

class BWFCRM_API_Get_Export_Data extends BWFCRM_API_Base {
	public static $ins;

	public function __construct() {
		parent::__construct();
		$this->method       = WP_REST_Server::READABLE;
		$this->route        = 'contact/export/(?P<export_id>[\\d]+)';
		$this->request_args = array(
			'export_id' => array(
				'description' => __( 'Export ID to retrieve', 'wp-marketing-automations-pro' ),
				'type'        => 'integer',
			),
		);
	}

	public static function get_instance() {
		if ( null === self::$ins ) {
			self::$ins = new self();
		}

		return self::$ins;
	}

	public function process_api_call() {
		$export_id = $this->get_sanitized_arg( 'export_id', 'text_field' );

		if ( $export_id ) {
			BWFCRM_Common::ping_woofunnels_worker();
			$export = BWFAN_Model_Import_Export::get( $export_id );
			if ( $export ) {
				$temp = ! empty( $export['meta'] ) ? json_decode( $export['meta'], true ) : [];
				unset( $export['meta'] );
				if ( isset( $temp['file'] ) ) {
					$temp['filename'] = $temp['file'];
					if ( file_exists(BWFCRM_EXPORT_DIR . '/' . $temp['file'] ) ) {
						$temp['file'] = BWFCRM_EXPORT_URL . $temp['file'];
					}else{
						$temp['file'] = false;
					}
				} else {
					$temp['file'] = false;
				}
				$export = array_merge( $export, $temp );
				return $this->success_response( $export, __( 'Successfully fetched export data with id ', 'wp-marketing-automations-pro' ) . '#' . $export_id );
			}
		}

		$this->response_code = 400;
		return $this->error_response( __( 'Unable to get export data with id #' . $export_id, 'wp-marketing-automations-pro' ) );

	}
}

BWFCRM_API_Loader::register( 'BWFCRM_API_Get_Export_Data' );
