<?php

class WP_Tymber_Shop_Api extends Wp_Tymber_Shop_Request {
	private $namespace;

	public function __construct( $namespace = 'tymber/v1' ) {
		$this->namespace = $namespace;
	}

	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/update-version',
			array(
				'methods'  => 'POST',
				'callback' => array( $this, 'update_version' ),
			)
		);
	}

	public function update_version( $request ) {
		$token     = $request->get_param( 'token' ) ?? '';
		$version   = $request->get_param( 'version' );
		$store_ids = $request->get_param( 'store_ids' ) ?? '';

		if ( empty( $token ) ) {
			wp_send_json_error( '`token` param missing', 403 );
		}

		if ( ! empty( $store_ids ) ) {
			update_option( '_tymber-store_ids', $store_ids );
			wp_send_json_success( 'Store IDs updated.', 200 );
		}

		if ( empty( $version ) ) {
			wp_send_json_error( '`version` param missing', 403 );
		}

		if ( ! function_exists( 'carbon_get_theme_option' ) ) {
			wp_send_json_error( 'Not implemented - carbon error', 501 );
		}

		if ( carbon_get_theme_option( 'tymber-api_token' ) !== $token ) {
			wp_send_json_error( 'Invalid Token', 403 );
		}

		wp_send_json_error( 'Something went wrong. Not updated on customer website!', 500 );
	}
}
