<?php
if(!defined('ABSPATH')){ exit; }

if(!class_exists('WCFE_WC_API_Handler')):

class WCFE_WC_API_Handler extends WCFE_Checkout_Fields_Utils{

	public function __construct() {
		add_filter("woocommerce_webhook_payload", array( $this, 'woo_webhook_payload' ), 10, 4);
	}
	
	public function woo_webhook_payload($payload, $resource, $resource_id, $id) {
		$sections = $this->get_checkout_sections();
		
		if($resource === "order"){
			$order_id = $payload["order"]["id"];
			$user_id  = $payload["order"]["customer"]["id"];
			
			if($sections && is_array($sections)){
				foreach($sections as $sname => $section){
					if($sname === "billing" || $sname === "shipping"){
						$sname = $sname."_address";
					}
					
					if(WCFE_Section_Utils::is_valid_section($section)){
						$fields = WCFE_Section_Utils::get_fields($section);
						if($fields){
							foreach($fields as $name => $field){	
								if(WCFE_Field_Utils::is_enabled($field) && WCFE_Field_Utils::is_custom_field($field)){
									if($field->get_property('order_meta')){
										$order_meta = get_post_meta( $order_id, $name, true );
										$payload["order"][$sname][$name] = $order_meta;
									}
									
									if($field->get_property('user_meta')){
										$user_meta = get_user_meta( $user_id, $name, true );
										$payload["order"]["customer"][$sname][$name] = $user_meta;
									}
								}
							}
						}
					}
				}
			}	
								
		}else if($resource === "customer"){
			$user_id = $payload["customer"]["id"];
			
			if($sections && is_array($sections)){
				foreach($sections as $sname => $section){
					if($sname === "billing" || $sname === "shipping"){
						$sname = $sname."_address";
					}
					
					if(WCFE_Section_Utils::is_valid_section($section)){
						$fields = WCFE_Section_Utils::get_fields($section);
						if($fields){
							foreach($fields as $name => $field){	
								if( WCFE_Field_Utils::is_enabled($field) && WCFE_Field_Utils::is_custom_field($field) && $field->get_property('user_meta') ){
									$value = get_user_meta( $user_id, $name, true );
									$payload["customer"][$name] = $value;
								}
							}
						}
					}
				}
			}
		}
	
		return $payload;
	}

}

endif;