<?php
if (!defined( 'ABSPATH' )) exit;
class woo2app_core_api_customers {
	public function __construct(){
		add_action( 'init', array( $this , 'woo2app_api_regular_url' ));
		add_filter( 'query_vars', array( $this , 'woo2app_api_query_vars' ));
		add_action( 'parse_request', array( $this , 'woo2app_api_parse_request' ));
	}
	function woo2app_api_regular_url(){
		add_rewrite_rule('', 'index.php?POST_customer', 'top');
		add_rewrite_rule('', 'index.php?PUT_customer', 'top');
		add_rewrite_rule('', 'index.php?GET_login', 'top');
		add_rewrite_rule('', 'index.php?woo2app_current_balance', 'top');
		add_rewrite_rule('', 'index.php?get_transaction_woo_wallet', 'top');
	}
	function woo2app_api_query_vars($query_vars){
		$query_vars[] = 'POST_customer';
		$query_vars[] = 'PUT_customer';
		$query_vars[] = 'GET_login';
		$query_vars[] = 'woo2app_current_balance';
		$query_vars[] = 'get_transaction_woo_wallet';
		return $query_vars;
	}
	function woo2app_api_parse_request(&$wp){
		if ( array_key_exists( 'POST_customer', $wp->query_vars ) ) {
			$this->woo2app_POST_customer();
			exit();
		}
		if ( array_key_exists( 'PUT_customer', $wp->query_vars ) ) {
			$this->woo2app_PUT_customer();
			exit();
		}
		if ( array_key_exists( 'GET_login', $wp->query_vars ) ) {
			$this->woo2app_GET_login();
			exit();
		}
		if ( array_key_exists( 'woo2app_current_balance', $wp->query_vars ) ) {
			$this->woo2app_current_balance();
			exit();
		}
		if ( array_key_exists( 'get_transaction_woo_wallet', $wp->query_vars ) ) {
			$this->get_transaction_woo_wallet();
			exit();
		}
		return;
	}
	private function woo2app_current_balance(){
		header('Content-Type: application/json; charset=utf-8');
		if(isset($_GET['u_id'])){
			$u_id = $_GET['u_id'];
			include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
			if ( is_plugin_active( 'woo-wallet/woo-wallet.php' )) {
				$b = (int)$balance = woo_wallet()->wallet->get_wallet_balance( $u_id, 'edit' );
				echo '"' . $b . '"';
			}
		}
	}
	private function get_transaction_woo_wallet(){
		header('Content-Type: application/json; charset=utf-8');
		if(isset($_GET['u_id'])){
			$u_id = $_GET['u_id'];
			include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
			if ( is_plugin_active( 'woo-wallet/woo-wallet.php' )) {
				$data = get_wallet_transactions( array( 'user_id' => $u_id ) );
				echo json_encode($data);
			}
		}
	}
	function woo2app_POST_customer(){
		ob_start();
		$in = $_POST['in'];
		$slashless = stripcslashes($in);
		$url_json = urldecode($slashless);
		$json = (array)  json_decode($url_json);
		//var_dump($json);return;
		$email = $json["email"];
		$first_name = $json["first_name"];
		$last_name = $json["last_name"];
		//$username = $json["user_name"];
		//$password = $json["password"];
		$username = $json['user_name'] ? $json['user_name'] : $json['nameKarbari'];
		$password = $json['password'] ? $json['password'] : $json['ramz'];
		$phone = $json["phone"];
		$address = $json["address"];
		$city = $json["city"];
		$state = $json["state"];
		$postcode = $json["postcode"];
		$data_customer = array( "customer" => array(
			'email' => $email,
			'first_name' => $first_name,
			'last_name' => $last_name,
			'username' => $username,
			'password' => $password,
			'billing_address' => array(
				'first_name' => $first_name,
				'last_name' => $last_name,
				'address_1' => $address,
				'city' => $city,
				'state' => $state,
				'postcode' => $postcode,
				'email' => $email,
				'phone' => $phone
			),
			'shipping_address' => array(
				'first_name' => $first_name,
				'last_name' => $last_name,
				'address_1' => $address,
				'city' => $city,
				'state' => $state,
				'postcode' => $postcode,
			)
		)
		);
		$array = $this->create_customer( $data_customer);
		if(isset($array->errors)){
			ob_clean();
			$result = array();
			foreach ($array->errors as $key ) {
				$result['error'] = -2;
				$result['msg'] = $key[0];
			}
			echo json_encode($result);
		}elseif(isset($array['customer'])){
			ob_clean();
			echo json_encode(array("error" => 1 , 'msg' => 'Registration was successful.'));
		}
		return $array;
	}
	function woo2app_PUT_customer(){
		ob_start();
		$in = $_POST['in'];
		$slashes = stripcslashes($in);
		$url_json = urldecode($slashes);
		$json = (array)  json_decode($url_json);
		$id = $json['id'];
		//$pass = $json["password"];
		$pass = $json['password'] ? $json['password'] : $json['ramz'];
		$first_name = $json["first_name"];
		$last_name = $json["last_name"];
		$address = $json["address"];
		$city = $json['city'];
		$state = $json['state'];
		$postcode = $json['postcode'];
		$phone = $json['phone'];
		$data_customer = array( "customer" => array(
			'first_name' => $first_name,
			'last_name' => $last_name,
			'billing_address' => array(
				'first_name' => $first_name,
				'last_name' => $last_name,
				'address_1' => $address,
				'city' => $city,
				'state' => $state,
				'postcode' => $postcode,
				'phone' => $phone
			),
			'shipping_address' => array(
				'first_name' => $first_name,
				'last_name' => $last_name,
				'address_1' => $address,
				'city' => $city,
				'state' => $state,
				'postcode' => $postcode,
			)
		)
		);
		$user = get_user_by( 'id', $id );
		if ( $user && !empty($pass) &&
		     (
			     wp_check_password( $pass, $user->data->user_pass, $user->ID )
			     || get_user_meta($user->ID , 'gid' , true) == $pass
		     )
		)
		{
			$array = $this->edit_customer( $id , $data_customer );
			if($array["customer"]){
				ob_clean();
				echo json_encode(array("error" => 1 , 'msg' => 'User info has been successfully edited.'));
				return;
			}
		}
		elseif (!$user){
			ob_clean();
			echo json_encode(array("error" => -2 , 'msg' => 'User ID is not correct.'));
			return;
		}
		elseif(!wp_check_password( $pass, $user->data->user_pass, $user->ID)){
			ob_clean();
			echo json_encode(array("error" => -3 , 'msg' => 'Password is not correct.'));
			return;
		}
		return array("error" => -4 , 'msg' => 'The information is not correct');
	}
	function woo2app_GET_login() {
		header('Content-Type: application/json; charset=utf-8');
		ob_start();
		if ( ! empty( $_GET["in"] ) ) {
			$customer = "";
			$in = $_GET["in"];
			$slashless = stripcslashes( $in );
			$url_json = urldecode( $slashless );
			$json = (array) json_decode( $url_json );
			//$user = $json["user_name"];
			//$pass =  $json["password"];
			$user = $json['user_name'] ? $json['user_name'] : $json['nameKarbari'];
			$pass = $json['password'] ? $json['password'] : $json['ramz'];
			$flag = 0;
			$s = 0;
			$hami_check = "";
			if(get_user_by( 'login', $user ) == true){
				$hami_check = get_user_by( 'login', $user );
				$s = 1;
			}
			elseif(get_user_by( 'email', $user ) == true ){
				$hami_check = get_user_by( 'email', $user );
				$s = 1;
			}
			else{
				$flag = - 2;
			}
			if($s == 1 &&  ! wp_check_password( $pass, $hami_check->data->user_pass, $hami_check->ID )){
				$flag = -3;
			}
			if ( $s == 1 && wp_check_password( $pass, $hami_check->data->user_pass, $hami_check->ID )) {
				if ( $user != "" && $pass != "" ) {
					$flag = 1;
					$json = $this->get_customer( $hami_check->ID );
					$customer = array(
						"id" => $json[ "customer" ][ "id" ],
						"first_name" => $json[ "customer" ][ "first_name" ],
						"last_name" => $json[ "customer" ][ "last_name" ],
						"phone" => $json[ "customer" ][ "billing_address" ][ "phone" ],
						"address" => $json[ "customer" ][ "billing_address" ][ "address_1" ],
						"city" => $json[ "customer" ][ "billing_address" ][ "city" ],
						"email" => $json[ "customer" ][ "email" ],
						"state" => $json[ "customer" ][ "billing_address" ][ "state" ],
						"postcode" => $json[ "customer" ][ "billing_address" ][ "postcode" ] ,
						"role" => $json[ "customer" ][ "role" ],
					);
				}//end
			}

			$out = array( "error" => $flag, "customer" => $customer );
			ob_clean();
			echo json_encode( $out );
			return;
		}
	}
	//--------------------------------------------------------------------------------------------
	public function create_customer( $data ) {
		if ( ! isset( $data['customer'] ) ) {
			//throw new WC_API_Exception( 'woocommerce_api_missing_customer_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'customer' ), 400 );
		}
		$data = $data['customer'];
		// Checks with can create new users.
		if ( ! current_user_can( 'create_users' ) ) {
			//throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_customer', __( 'You do not have permission to create this customer', 'woocommerce' ), 401 );
		}
		$data = apply_filters( 'woocommerce_api_create_customer_data', $data, $this );
		// Checks with the email is missing.
		if ( ! isset( $data['email'] ) ) {
			//throw new WC_API_Exception( 'woocommerce_api_missing_customer_email', sprintf( __( 'Missing parameter %s', 'woocommerce' ), 'email' ), 400 );
		}
		// Sets the username.
		$data['username'] = ! empty( $data['username'] ) ? $data['username'] : '';
		// Sets the password.
		$data['password'] = ! empty( $data['password'] ) ? $data['password'] : '';
		// Attempts to create the new customer
		//$id = wc_create_new_customer( $data['email'], $data['username'], $data['password'] );
		$new_customer_data = apply_filters( 'woocommerce_new_customer_data', array(
			'user_login' => $data['username'],
			'user_pass'  => $data['password'],
			'user_email' => $data['email'],
			'role'       => woo2app_get_role(),
		) );
		$id = wp_insert_user( $new_customer_data );
		// var_dump($customer_id);
		// return;
		// Checks for an error in the customer creation.
		if ( is_wp_error( $id ) ) {
			//throw new WC_API_Exception( $id->get_error_code(), $id->get_error_message(), 400 );
		}
		// Added customer data.
		$this->update_customer_data( $id, $data );
		do_action( 'woocommerce_api_create_customer', $id, $data );
		//$this->send_status( 201 );
		return $this->get_customer( $id );
	}
	protected function update_customer_data( $id, $data ) {
		// Customer first name.
		if ( isset( $data['first_name'] ) ) {
			update_user_meta( $id, 'first_name', wc_clean( $data['first_name'] ) );
		}
		// Customer last name.
		if ( isset( $data['last_name'] ) ) {
			update_user_meta( $id, 'last_name', wc_clean( $data['last_name'] ) );
		}
		// Customer billing address.
		if ( isset( $data['billing_address'] ) ) {
			foreach ( $this->get_customer_billing_address() as $address ) {
				if ( isset( $data['billing_address'][ $address ] ) ) {
					update_user_meta( $id, 'billing_' . $address, wc_clean( $data['billing_address'][ $address ] ) );
				}
			}
		}
		// Customer shipping address.
		if ( isset( $data['shipping_address'] ) ) {
			foreach ( $this->get_customer_shipping_address() as $address ) {
				if ( isset( $data['shipping_address'][ $address ] ) ) {
					update_user_meta( $id, 'shipping_' . $address, wc_clean( $data['shipping_address'][ $address ] ) );
				}
			}
		}
		do_action( 'woocommerce_api_update_customer_data', $id, $data );
	}
	protected function get_customer_billing_address() {
		$billing_address = apply_filters( 'woocommerce_api_customer_billing_address', array(
			'first_name',
			'last_name',
			'company',
			'address_1',
			'address_2',
			'city',
			'state',
			'postcode',
			'country',
			'email',
			'phone',
		) );
		return $billing_address;
	}
	protected function get_customer_shipping_address() {
		$shipping_address = apply_filters( 'woocommerce_api_customer_shipping_address', array(
			'first_name',
			'last_name',
			'company',
			'address_1',
			'address_2',
			'city',
			'state',
			'postcode',
			'country',
		) );
		return $shipping_address;
	}
	public function format_datetime( $timestamp, $convert_to_utc = false ) {
		if ( $convert_to_utc ) {
			$timezone = new DateTimeZone( wc_timezone_string() );
		} else {
			$timezone = new DateTimeZone( 'UTC' );
		}
		try {
			if ( is_numeric( $timestamp ) ) {
				$date = new DateTime( "@{$timestamp}" );
			} else {
				$date = new DateTime( $timestamp, $timezone );
			}
			// convert to UTC by adjusting the time based on the offset of the site's timezone
			if ( $convert_to_utc ) {
				$date->modify( -1 * $date->getOffset() . ' seconds' );
			}
		} catch ( Exception $e ) {
			$date = new DateTime( '@0' );
		}
		return $date->format( 'Y-m-d\TH:i:s\Z' );
	}
	private function get_avatar_url( $email ) {
		$avatar_html = get_avatar( $email );
		// Get the URL of the avatar from the provided HTML
		preg_match( '/src=["|\'](.+)[\&|"|\']/U', $avatar_html, $matches );
		if ( isset( $matches[1] ) && ! empty( $matches[1] ) ) {
			return esc_url_raw( $matches[1] );
		}
		return null;
	}
	public function get_customer( $id, $fields = null ) {
		global $wpdb;
		//$id = $this->validate_request( $id, 'customer', 'read' );
		if ( is_wp_error( $id ) ) {
			return $id;
		}
		$customer = new WP_User( $id );
		// Get info about user's last order
		$last_order = $wpdb->get_row( "SELECT id, post_date_gmt
			FROM $wpdb->posts AS posts
			LEFT JOIN {$wpdb->postmeta} AS meta on posts.ID = meta.post_id
			WHERE meta.meta_key = '_customer_user'
			AND   meta.meta_value = {$customer->ID}
			AND   posts.post_type = 'shop_order'
			AND   posts.post_status IN ( '" . implode( "','", array_keys( wc_get_order_statuses() ) ) . "' )
			ORDER BY posts.ID DESC
			" );
		$roles = array_values( $customer->roles );
		$customer_data = array(
			'id'               => $customer->ID,
			'created_at'       => $this->format_datetime( $customer->user_registered ),
			'last_update'      => $this->format_datetime( get_user_meta( $customer->ID, 'last_update', true ) ),
			'email'            => $customer->user_email,
			'first_name'       => $customer->first_name,
			'last_name'        => $customer->last_name,
			'username'         => $customer->user_login,
			'role'             => $roles[0],
			'last_order_id'    => is_object( $last_order ) ? $last_order->id : null,
			'last_order_date'  => is_object( $last_order ) ? $this->format_datetime( $last_order->post_date_gmt ) : null,
			'orders_count'     => wc_get_customer_order_count( $customer->ID ),
			'total_spent'      => wc_format_decimal( wc_get_customer_total_spent( $customer->ID ), 2 ),
			'avatar_url'       => $this->get_avatar_url( $customer->customer_email ),
			'billing_address'  => array(
				'first_name' => $customer->billing_first_name,
				'last_name'  => $customer->billing_last_name,
				'company'    => $customer->billing_company,
				'address_1'  => $customer->billing_address_1,
				'address_2'  => $customer->billing_address_2,
				'city'       => $customer->billing_city,
				'state'      => $customer->billing_state,
				'postcode'   => $customer->billing_postcode,
				'country'    => $customer->billing_country,
				'email'      => $customer->billing_email,
				'phone'      => $customer->billing_phone,
			),
			'shipping_address' => array(
				'first_name' => $customer->shipping_first_name,
				'last_name'  => $customer->shipping_last_name,
				'company'    => $customer->shipping_company,
				'address_1'  => $customer->shipping_address_1,
				'address_2'  => $customer->shipping_address_2,
				'city'       => $customer->shipping_city,
				'state'      => $customer->shipping_state,
				'postcode'   => $customer->shipping_postcode,
				'country'    => $customer->shipping_country,
			),
		);
		return array( 'customer' => apply_filters( 'woocommerce_api_customer_response', $customer_data, $customer, $fields, ""/*$this->server*/ ) );
	}
	public function edit_customer( $id, $data ) {
		if ( ! isset( $data['customer'] ) ) {
			//throw new WC_API_Exception( 'woocommerce_api_missing_customer_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'customer' ), 400 );
		}
		$data = $data['customer'];
		// Validate the customer ID.
		//$id = $this->validate_request( $id, 'customer', 'edit' );
		// Return the validate error.
		if ( is_wp_error( $id ) ) {
			//throw new WC_API_Exception( $id->get_error_code(), $id->get_error_message(), 400 );
		}
		$data = apply_filters( 'woocommerce_api_edit_customer_data', $data, $this );
		// Customer email.
		if ( isset( $data['email'] ) ) {
			wp_update_user( array( 'ID' => $id, 'user_email' => ( $data['email'] ) ) );
		}
		// Customer password.
		if ( isset( $data['password'] ) ) {
			wp_update_user( array( 'ID' => $id, 'user_pass' => wc_clean( $data['password'] ) ) );
		}
		// Update customer data.
		$this->update_customer_data( $id, $data );
		do_action( 'woocommerce_api_edit_customer', $id, $data );
		return $this->get_customer( $id );
	}
}