<?php

class MaTemplateEngine extends MaSingleton{
    /**
     *
     * @var WC_Order_Item_Meta
     */
    protected $_itemMeta;
    /**
     *
     * @var WC_Order 
     */
    protected $_order;
    /**
     *
     * @var WC_Product 
     */
    protected $_currentProduct;
    /**
     *
     * @var array 
     */
    protected $_currentItem;
    protected $_startSymbol = "{{";
    protected $_endSymbol = "}}";
    
    protected $_globalVars = array();
    /**
     * For using this vars in template you need to write {{order.$key}}
     * @var array
     */
    protected $_orderFields = array(
        //Outputs the date of the order
        'date', 
        //Outputs the date and time of the order
        'datetime',
        //Outputs the order total minus the tax and shipping amounts
        'subtotal',
        //Outputs the tax amount of the order
        'tax',
        //Outputs the payment gateway or payment method used
        'pay_method',
        //Outputs the billing address for the specified order
        'billing_address',
        //Outputs the shipping address for the specified order
        'shipping_address',
        //Outputs order total tax included
        'total',
        //Displays the billing phone number of the customer
        'billing_phone',
        //Displays the shipping phone number for the customer
        'shipping_phone',
        //Display the order number
        'number',
        // Displays shipping first name
        'shipping_first_name',
        // Display shipping first name
        'shipping_last_name',
        // Displays shipping fullname formated
        'shipping_fullname',
        // Display billing first name
        'billing_first_name',
        // Displays billing last name
        'billing_last_name',
        // display billing fullname formated
        'billing_fullname',
        // displays order username 
        'username',
        // Display userfirst name
        'user_first_name',
        // displays user last name
        'user_last_name',
        // Displays shipping country 
        'shipping_country',
        'billing_country',
        //Displays shipping city
        
        'shipping_city',
        'billing_city',
        // Dipslyas shipping postcode
        'shipping_postcode',
        'billing_postcode',
        'shipping_total',
        'shipping_method',
        'discount',
        'pay_now_link'
        
        
        
    );
    protected $_productFields = array(
        //Display product price
        'price',
        // Display product qunatity
        'quantity',
        // Display Product name
        'name',
        // Display product description
        'decription',
        // Display product short description
        'short_description',
        // Display product sku
        'code',
        // Dipslya product src
        'img_src',
        // Display product subtotal
        'subtotal',
        // Display product url
        'url',
        'number',
        
    );
    protected  $_orderReplaceVars = null;
    protected  $_productReplaceVars = null;


    public function setOrder($order){
        $this->_order = $order;
        if(is_null($this->_orderReplaceVars)){
            $this->initOrderReplaceVars();
        }
    }
    public function setCurrentItem($item){
        $this->_currentItem = $item;
    }
    public function setCurrentProduct($product){
        $this->_currentProduct = $product;
    }
    
    public function setItemMeta($itemMeta){
        $this->_itemMeta = $itemMeta;
    }
    
    
    
    public function parseTemplate($template){
        foreach ($this->_globalVars as $var){
            
            $template = str_replace( $this->_startSymbol .$var['key']. $this->_endSymbol, $var['value'], $template);
        }
        return $template;
    }
    public function initGlobalVars($vars, $templateKey){
        foreach ($vars as $section => $props){
            foreach ($props as $var => $value ){
                $path = $section . '.';
                $path.= $var;
                if(!$value['multipleEmails']){
                    $path .='.val';
                    $this->_globalVars[] = array(
                        'key' => $path,
                        'value' => $value['val']
                    );
                }else{
                    $path .= '.'  . $templateKey . '.val';
                    $this->_globalVars[] = array(
                        'key' => $path,
                        'value' => $value[$templateKey]['val']
                    );
                }
                
            }
        }
    }
    
    
    protected function _orderDate(){
        $date = new DateTime($this->_order->order_date);
        return $date->format('F j,Y');
        //return $this->_order->order_date;
    }
    protected function _orderDatetime(){
        return $this->_order->order_date;
    }
    protected function _orderSubtotal(){
        return wc_price($this->_order->get_subtotal(), array('currency' => $this->_order->get_order_currency()));
    }
    protected function _orderTotal(){
        return wc_price($this->_order->get_total(), array('currency' => $this->_order->get_order_currency()));
    }
    protected function _orderTax(){
        return wc_price($this->_order->get_tax_totals(), array('currency' => $this->_order->get_order_currency()));
    }
    protected function _orderPayMethod(){
        return $this->_order->payment_method_title;
    }
    protected function _orderBillingAddress(){
        return $this->_order->get_formatted_billing_address();
    }
    protected  function _orderShippingAddress(){
        return $this->_order->get_formatted_shipping_address();
    }
    protected function _orderBillingPhone(){
        return $this->_order->billing_phone;
    }
    protected function _itemPrice(){
        return wc_price($this->_currentProduct->price, array('currency' => $this->_order->get_order_currency()));
    }
    protected  function _itemQuantity(){
        return apply_filters('woocommerce_email_order_item_quantity', $this->_currentItem['qty'], $this->_currentItem);
    }
    protected function _itemName(){
        return apply_filters('woocommerce_order_item_name', $this->_currentItem['name'], $this->_currentItem, false);
    }
    protected function _itemDecription(){
        return $this->_currentProduct->post->post_content;
    }
    protected function _itemShortDescription(){
        return $this->_currentProduct->post->post_excerpt;
    }
    protected function _itemCode(){
        return $this->_currentProduct->get_sku();
    }
    protected function _itemImgSrc(){
        return current(wp_get_attachment_image_src($this->_currentProduct->get_image_id(), 'thumbnail'));
    }
    protected function _itemSubtotal(){
        return $this->_order->get_formatted_line_subtotal($this->_currentItem);
    }
    protected function _itemUrl(){
        return get_permalink($this->_currentProduct->id);
    }
    protected function _orderNumber(){
        return $this->_order->get_order_number();
    }
    protected  function _itemNumber(){
        return '#' . $this->_currentProduct->id;
    }
    protected  function _orderDiscount(){
        return $this->_order->get_total_discount();
    }


    protected function _orderShippingFullname(){
        return $this->_order->get_formatted_shipping_full_name();
    }
    
    protected function _orderBillingFullname(){
        return $this->_order->get_formatted_billing_full_name();
    }
    
    protected function _orderShippingTotal(){
        return $this->_order->get_shipping_to_display();
    }
    protected function _orderShippingMethod(){
        
        return !$this->_order->get_shipping_method() ? $this->_orderShippingTotal() : $this->_order->get_shipping_method();
    }
    protected function _orderPayNowLink(){
        return $this->_order->get_checkout_payment_url();
    }


    public function parseProductTemplate($text){
        foreach ($this->_productReplaceVars as $var => $value){
            $text = str_replace($var, $value, $text);
        }
        return $text;
    }
    public function parseOrderVariables($text){
       
        foreach ($this->_orderReplaceVars as $var => $value){
            $text = str_replace($var, $value, $text);
        }
        return $text;
    }
    
    public function initOrderReplaceVars($order = null){
        if(!is_null($order)){
            $this->_order = $order;
        }
        
        foreach ($this->_orderFields as $field){
           
            $varKey = $this->_startSymbol . 'order.' . $field . $this->_endSymbol;
            $parts = explode('_', $field);
            
            $methodName = '_order';
            for ($i = 0; $i < count($parts); $i++){
                $methodName .= ucfirst($parts[$i]);
            }
           
           
            if(method_exists($this, $methodName)){
                $this->_orderReplaceVars[$varKey]  = $this->$methodName();
            }else{
                
                if(isset($this->_order->$field)){
                    $this->_orderReplaceVars[$varKey]  = $this->_order->$field;
                }elseif(method_exists($this->_order, $field)){
                    $this->_orderReplaceVars[$varKey]  = $this->_order->$field();
                }
            }
        }
        
        
        
    }
    public function initProductReplaceVars($product = null){
        if(!is_null($product)){
            $this->_currentProduct = $product;
            
        }
        
        foreach ($this->_productFields as $field){
            $varKey = $this->_startSymbol . 'item.'  . $field . $this->_endSymbol;
            $parts = explode('_', $field);
            $methodName = '_item';
            for ($i = 0; $i < count($parts); $i++){
                $methodName .= ucfirst($parts[$i]);
            }
            if(method_exists($this, $methodName)){
                $this->_productReplaceVars[$varKey]  = $this->$methodName();
            }else{
                
                if(isset($this->_currentProduct->$field)){
                    $this->_productReplaceVars[$varKey]  = $this->_currentProduct->$field;
                }elseif(method_exists($this->_currentProduct, $field)){
                    $this->_productReplaceVars[$varKey]  = $this->_currentProduct->$field();
                }
            }
            
        }
        
    }
   
    


}

