<?xml version="1.0" encoding="UTF-8"?>

<modification>
    <name>Change-MP-Paths</name>
    <version>1.0.0</version>
    <code>All SEF urls</code>
    <author>Webkul</author>
    <link>http://webkul.com</link>

    <file path="catalog/controller/startup/seo_url.php">
        <operation>
            <search><![CDATA[
                $this->request->get['route'] = 'error/not_found';
                ]]></search>
            <add position="before" offset="1"><![CDATA[
                }elseif($this->config->get('marketplace_useseo') AND $this->request->get['_route_']=='Marketplace-Collection'){
                    $this->request->get['route'] =  'customerpartner/profile/collection';
                }elseif ($this->config->get('marketplace_useseo') AND is_array($this->config->get('marketplace_SefUrlsvalue')) AND (in_array($this->request->get['_route_'],$this->config->get('marketplace_SefUrlsvalue')) || in_array(current(explode('/',$this->request->get['_route_'])),$this->config->get('marketplace_SefUrlsvalue')) )) {
                    $_route_ = explode('/',$this->request->get['_route_']);

                    $sefKey = array_search($_route_[0],$this->config->get('marketplace_SefUrlsvalue'));

                    $wkSefUrlspath = $this->config->get('marketplace_SefUrlspath');

                    if(isset($wkSefUrlspath[$sefKey])) {

                        if($wkSefUrlspath[$sefKey]=='customerpartner/profile' AND isset($_route_[1])) {

                            $query = $this->db->query("SELECT customer_id FROM " . DB_PREFIX . "customerpartner_to_customer WHERE `screenname` = '" . $this->db->escape($_route_[1]) . "'");
                            if ($query->num_rows) {
                                if($query->row['customer_id']){
                                   $this->request->get['id'] = $query->row['customer_id'];
                                }
                            }
                        $this->request->get['route'] = 'customerpartner/profile';

                    } elseif($wkSefUrlspath[$sefKey]=='product/product' && in_array('product/product',$this->config->get('marketplace_SefUrlspath'))) {
                    $new_route = str_replace($this->config->get('marketplace_product_seo_page_ext'),'',$this->request->get['_route_']);
                    $product_name = false;
                    if($this->config->get('marketplace_product_seo_format')) {
                        if($this->config->get('marketplace_product_seo_format')=='1') {
                            $mpparts = explode('/', $new_route);
                            if(isset($mpparts[1]) ) {
                                $product_name = $mpparts[1];
                            }
                        } else if($this->config->get('marketplace_product_seo_format')=='2') {
                           $mpparts = explode('-',$new_route,2);
                            if(isset($mpparts[1]))
                                $product_name = $mpparts[1];
                        } else if($this->config->get('marketplace_product_seo_format')=='3') {
                            $mpparts = explode('/',$new_route);
                            if($mpparts[1])
                                $product_name = $mpparts[1];
                        }
                    }
                    if ($product_name) {
                        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($product_name) . "'");

                        if ($query->num_rows) {
                            $url = explode('=', $query->row['query']);

                            if ($url[0] == 'product_id') {
                                $this->request->get['product_id'] = $url[1];
                            }
                        }

                        if(!$query->num_rows AND $this->config->get('marketplace_product_seo_product_name')) {
                            $product_name = str_replace('-', ' ', $product_name);
                            $query = $this->db->query("SELECT pd.product_id FROM ".DB_PREFIX."product_description pd WHERE pd.name = '".$this->db->escape($product_name)."' AND pd.language_id = '".$this->config->get('config_language_id')."'");

                            if ($query->num_rows)
                                $this->request->get['product_id'] = $query->row['product_id'];
                        }

                        $this->request->get['route'] = 'product/product';

                    }

                }else{
                    $this->request->get['route'] =  $wkSefUrlspath[$sefKey];
                }

            }
            ]]></add>
        </operation>

        <operation>

            <search><![CDATA[} elseif ($key == 'path') {]]></search>
            <add position="before"><![CDATA[

                }elseif($this->config->get('marketplace_useseo') AND $data['route'] == 'customerpartner/profile/collection'){

                    $url .= '/Marketplace-Collection' ;
                    unset($data[$key]);
                }elseif($this->config->get('marketplace_useseo') AND $data['route'] == 'product/product' AND isset($data['product_id']) AND is_array($this->config->get('marketplace_SefUrlspath')) AND in_array($data['route'],$this->config->get('marketplace_SefUrlspath')) ) {
                    $sellerDetail = '';
                    $sellerDetails = $this->db->query("SELECT c2c.screenname,c2c.companyname,c.firstname as sellername FROM ".DB_PREFIX."customerpartner_to_product c2p LEFT JOIN ".DB_PREFIX."product p ON (p.product_id=c2p.product_id) LEFT JOIN ".DB_PREFIX."customerpartner_to_customer c2c ON (c2p.customer_id=c2c.customer_id) LEFT JOIN ".DB_PREFIX."customer c ON (c.customer_id=c2c.customer_id) WHERE c2p.product_id = '".$data['product_id']."' ")->row;

                    if(isset($sellerDetails[$this->config->get('marketplace_product_seo_name')]) && $sellerDetails[$this->config->get('marketplace_product_seo_name')] ) {
                        $sellerDetail = $sellerDetails[$this->config->get('marketplace_product_seo_name')];
                    } else {
                        $sellerDetail = $this->config->get('marketplace_product_seo_default_name');
                    }
                    $keyword = $this->db->query("SELECT keyword FROM ".DB_PREFIX."url_alias WHERE query = 'product_id=" . (int)$data['product_id'] . "' ")->row;

                    if(isset($keyword['keyword']) && $keyword['keyword']) {
                        $keyword = $keyword['keyword'];
                        unset($data['product_id']);
                    } else if($this->config->get('marketplace_product_seo_name')) {

                        $key_word = $this->db->query("SELECT name FROM ".DB_PREFIX."product_description pd WHERE product_id = '".$data['product_id']."' AND language_id = '".$this->config->get('config_language_id')."' ")->row;

                        if(isset($key_word['name'])) {
                            $keyword = str_replace(' ','-',$key_word['name']);
                        } else {
                            $keyword = '';
                        }
                    }
                    $sefKey = array_search($data['route'],$this->config->get('marketplace_SefUrlspath'));
                    $wkSefUrlsvalue = $this->config->get('marketplace_SefUrlsvalue');
                    if(isset($wkSefUrlsvalue[$sefKey]) && $wkSefUrlsvalue[$sefKey]) {
                        $url .= '/'.$wkSefUrlsvalue[$sefKey];
                    } else {
                        $url .= '';
                    }
                    if($sellerDetail) {
                        if($this->config->get('marketplace_product_seo_format') == '1') {
                            $url .= '/'.$keyword;
                        } else if($this->config->get('marketplace_product_seo_format') == '2') {
                            $url .= '/'.str_replace('-','',$sellerDetail).'-'.$keyword;
                        } else if ($this->config->get('marketplace_product_seo_format') == '3') {
                            $url .= '/'.$keyword.'/'.str_replace('-','',$sellerDetail);
                        }
                        if($this->config->get('marketplace_product_seo_page_ext')) {
                            $url .= $this->config->get('marketplace_product_seo_page_ext');
                        }
                        unset($data[$key]);
                    } else {

                        $sefKey = array_search($data['route'],$this->config->get('marketplace_SefUrlspath'));
                        $wkSefUrlsvalue = $this->config->get('marketplace_SefUrlsvalue');

                        if(isset($wkSefUrlsvalue[$sefKey])){
                            if($keyword){
                                $url .=  '/'.$keyword;
                            }
                            if($this->config->get('marketplace_product_seo_page_ext')) {
                                $url .= $this->config->get('marketplace_product_seo_page_ext');
                            }
                            unset($data[$key]);
                        }
                    }
                    unset($data['product_id']);
                } elseif ($this->config->get('marketplace_useseo') AND is_array($this->config->get('marketplace_SefUrlspath')) AND in_array($data['route'],$this->config->get('marketplace_SefUrlspath'))) {
                    $sefKey = array_search($data['route'],$this->config->get('marketplace_SefUrlspath'));

                    $wkSefUrlsvalue = $this->config->get('marketplace_SefUrlsvalue');
                    if(isset($wkSefUrlsvalue[$sefKey])){
                        if($data['route']=='customerpartner/profile'){
                            if($key == 'id'){
                                $url .=  '/'.$wkSefUrlsvalue[$sefKey];

                                $query = $this->db->query("SELECT screenname FROM " . DB_PREFIX . "customerpartner_to_customer WHERE `customer_id` = '" . (int)$data[$key] . "'");
                                if ($query->num_rows) {

                                   if(trim($query->row['screenname'])){
                                      $url .= '/' . $query->row['screenname'];
                                    }else{
                                      $url .= '';
                                    }
                                    unset($data[$key]);
                                }
                            }
                        }elseif(($data['route'] != 'product/product') && ($data['route'] != 'customerpartner/profile')){
                            $url .=  '/'.$wkSefUrlsvalue[$sefKey];
                            unset($data[$key]);
                        }
                    }

            ]]></add>
        </operation>
    </file>

    <file path="catalog/controller/checkout/confirm.php">
        <operation>
            <search><![CDATA[
                'price'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']),
            ]]></search>
            <add position="replace"><![CDATA[
                'price'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'))+$product['commission_amount'], $this->session->data['currency']),
            ]]></add>
        </operation>

        <operation>
            <search><![CDATA[
                'total'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'], $this->session->data['currency']),
            ]]></search>
            <add position="replace"><![CDATA[
                'total'      => $this->currency->format(($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'))+$product['commission_amount']) * $product['quantity'], $this->session->data['currency']),
            ]]></add>
        </operation>
    </file>

    <file path="system/library/cart/cart.php">

      <operation>
          <search><![CDATA[
            public function getProducts() {
          ]]></search>
          <add position="before"><![CDATA[
            public function calculateCommission($product,$customer_id) {

              if($product) {
                $categories_array = $this->db->query("SELECT p2c.category_id,c.parent_id FROM ".DB_PREFIX."product_to_category p2c LEFT JOIN ".DB_PREFIX."category c ON (p2c.category_id = c.category_id) WHERE p2c.product_id = '".(int)$product['product_id']."' ORDER BY p2c.product_id ");

                if($this->config->get('marketplace_commissionworkedon'))
                  $categories = $categories_array->rows;
                else
                  $categories = array($categories_array->row);

                //get commission array for priority
                $commission = $this->config->get('marketplace_boxcommission');
                $commission_amount = 0;
                $commission_type = '';

                if($commission)
                  foreach($commission as $various) {
                    switch ($various) {
                      case 'category': //get all parent category according to product and process
                        if(isset($categories[0]) && $categories[0]){

                          foreach($categories as $category) {
                            if($category['parent_id']==0){
                              $category_commission = $query = $this->db->query("SELECT * FROM ".DB_PREFIX."customerpartner_commission_category WHERE category_id = '" . (int)$category['category_id'] . "'")->row;
                              if($category_commission){
                                $commission_amount += ( $category_commission['percentage'] ? ($category_commission['percentage']*$product['product_total']/100) : 0 ) + $category_commission['fixed'];
                              }
                            }
                          }
                          $commission_type = 'Category Based';
                          if($commission_amount)
                            break;
                        }

                      case 'category_child': //get all child category according to product and process
                        if(isset($categories[0]) && $categories[0]){

                          foreach($categories as $category){
                            if($category['parent_id'] > 0){
                              $category_commission = $query = $this->db->query("SELECT * FROM ".DB_PREFIX."customerpartner_commission_category WHERE category_id = '" . (int)$category['category_id'] . "'")->row;
                              if($category_commission){
                                $commission_amount += ( $category_commission['percentage'] ? ($category_commission['percentage']*$product['product_total']/100) : 0 ) + $category_commission['fixed'];
                              }
                            }
                          }

                          $commission_type = 'Category Child Based';
                          if($commission_amount)
                            break;
                        }

                      default: //just get all amount and process on that (precentage based)
                        $customer_commission = $query = $this->db->query("SELECT commission FROM ".DB_PREFIX."customerpartner_to_customer WHERE customer_id = '" . (int)$customer_id . "'")->row;
                        if($customer_commission) {
                          $commission_amount += $customer_commission['commission'] ? ($customer_commission['commission']*$product['product_total']/100) : 0;
                        }

                        $commission_type = 'Partner Fixed Based';
                        break;
                    }
                    if($commission_amount)
                      break;
                  }
                $return_array = array(
                  'commission' => $commission_amount,
                  'customer' => $product['product_total']- $commission_amount,
                  'type' => $commission_type,
                );
                return($return_array);
              }
            }
          ]]></add>
      </operation>

      <operation>
          <search><![CDATA[
            $product_data[] = array(
          ]]></search>
          <add position="before"><![CDATA[
            $commission_amount = 0;
            if ($this->config->get('marketplace_status')) {
               $check_seller_product = $this->db->query("SELECT * FROM ".DB_PREFIX."customerpartner_to_product WHERE product_id = '".$product_query->row['product_id']."'")->row;
               if ($check_seller_product) {
                if ($this->config->get('marketplace_commission_tax')) {
                  $commission_array = $this->calculateCommission(array('product_id'=> $product_query->row['product_id'], 'product_total'=> $this->tax->calculate(($price + $option_price), $product_query->row['tax_class_id'], $this->config->get('config_tax'))),$check_seller_product['customer_id']);
                }else{
                  $commission_array = $this->calculateCommission(array('product_id'=>$product_query->row['product_id'], 'product_total'=>($price + $option_price)),$check_seller_product['customer_id']);
                }

                if($commission_array && isset($commission_array['commission']) && $this->config->get('marketplace_commission_unit_price')){
                      $commission_amount = $commission_array['commission'];
                }
              }
            }
          ]]></add>
      </operation>

      <operation>
          <search><![CDATA[
            'price'           => ($price + $option_price),
          ]]></search>
          <add position="after"><![CDATA[
            'commission_amount'  => $commission_amount,
          ]]></add>
      </operation>

      <operation>
          <search><![CDATA[
            'total'           => ($price + $option_price) * $cart['quantity'],
          ]]></search>
          <add position="replace"><![CDATA[
            'total'           => ($price + $option_price + $commission_amount) * $cart['quantity'],
          ]]></add>
      </operation>

        <operation>
            <search><![CDATA[
                $total += $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'];
            ]]></search>
            <add position="replace"><![CDATA[
                $total += ($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'))+$product['commission_amount']) * $product['quantity'];
            ]]></add>
        </operation>

    </file>

    <file path="admin/model/sale/order.php">
        <operation>
            <search><![CDATA[
                public function deleteOrder($order_id) {
            ]]></search>
        <add position="after"><![CDATA[
          $str = '%order_id_:' . $order_id . '_';

          $this->db->query("DELETE FROM ".DB_PREFIX."customer_activity WHERE data LIKE '" . $str . "'");

          if($this->config->get('marketplace_status')) {

          $transaction = $this->db->query("SELECT * FROM " . DB_PREFIX . "customerpartner_to_transaction")->rows;

          if ($transaction) {
            foreach ($transaction as $key => $value) {

              $order_ids = explode(',',$value['order_id']);

              if ($order_ids && in_array($order_id,$order_ids)) {

                $paid_amount = $this->db->query("SELECT SUM(customer) AS paid_amount FROM " . DB_PREFIX . "customerpartner_to_order WHERE order_id = " . (int)$order_id . " AND customer_id = ". $value['customer_id'])->row;

                if (isset($paid_amount['paid_amount']) && $paid_amount['paid_amount']) {
                  if ($paid_amount['paid_amount'] == $value['amount']) {
                    $this->db->query("DELETE FROM ".DB_PREFIX."customerpartner_to_transaction WHERE id = '".(int)$value['id']."' ");
                  } else {
                    $amount = $value['amount'] - $paid_amount['paid_amount'];

                    $text = substr($value['text'],0,1) . $amount;

                    $this->db->query("UPDATE ".DB_PREFIX."customerpartner_to_transaction SET amount = " . $amount . ", text = '" . $text . "' WHERE id = '".(int)$value['id']."' ");
                  }
                }
              }
            }
          }

            $this->db->query("DELETE FROM ".DB_PREFIX."mp_customer_activity WHERE data LIKE '" . $str . "'");

            $this->db->query("DELETE FROM ".DB_PREFIX."customerpartner_to_order WHERE order_id = '".(int)$order_id."' ");
               $this->db->query("DELETE FROM ".DB_PREFIX."customerpartner_to_order_status WHERE order_id = '".(int)$order_id."' ");
               $this->db->query("DELETE FROM ".DB_PREFIX."customerpartner_sold_tracking WHERE order_id = '".(int)$order_id."' ");
          }
        ]]></add>
        </operation>
    </file>
    <file path="admin/view/template/catalog/product_form.tpl">
        <operation>
            <search><![CDATA[
              $('input[name=\'category\']').val('');
            ]]></search>
            <add position="before"><![CDATA[
              addCategoryAttribute(item);
            ]]></add>
        </operation>

        <operation>
            <search><![CDATA[
                function addAttribute() {
            ]]></search>
            <add position="before"><![CDATA[
              function addCategoryAttribute(item)  {

                if (item.value) {
                  $.ajax({
                    url: 'index.php?route=customerpartner/categorymapping/categoryAttribute&token=<?php echo $token; ?>&category_id=' + item.value,
                    dataType: 'json',
                    success: function(json) {
                      $.each(json, function() {
                          addAttribute();
                          var category_attribute_row = attribute_row -1;
                          $('input[name=\'product_attribute[' + category_attribute_row + '][name]\']').val(this.name);
                          $('input[name=\'product_attribute[' + category_attribute_row + '][attribute_id]\']').val(this.attribute_id);
                      });
                    }
                  });
                }
              }
            ]]></add>
        </operation>
    </file>
    <file path="catalog/controller/checkout/shipping_method.php">
      <operation>
        <search><![CDATA[
          $this->response->setOutput($this->load->view('checkout/shipping_method', $data));
        ]]></search>
        <add position="before"><![CDATA[
          if (isset($data['shipping_methods']) && isset($data['shipping_methods']['wk_custom_shipping']) && isset($this->session->data['seller_custom_shipping']) && $this->session->data['seller_custom_shipping'] && $this->config->get('wk_custom_shipping_seller_status')) {
            $data['seller_custom_shipping'] = $this->session->data['seller_custom_shipping'];
            $data['text_seller_name'] = $this->language->get('text_seller_name');
            $data['text_seller_shipping'] = $this->language->get('text_seller_shipping');
          }
        ]]></add>
        </operation>
    </file>

    <file path="catalog/language/*/checkout/checkout.php">
      <operation>
        <search><![CDATA[
          // Text
        ]]></search>
        <add position="after"><![CDATA[
          $_['text_seller_name']                      = 'Seller Name';
          $_['text_seller_shipping']                      = 'Shipping Applied';
        ]]></add>
        </operation>
    </file>

    <file path="catalog/view/theme/*/template/checkout/shipping_method.tpl">
      <operation>
        <search><![CDATA[
          <?php echo $quote['title']; ?> - <?php echo $quote['text']; ?></label>
        ]]></search>
        <add position="after" offset="1"><![CDATA[
          <?php if($quote['code'] == 'wk_custom_shipping.wk_custom_shipping'){ ?>
            <?php if(isset($seller_custom_shipping) && $seller_custom_shipping){ ?>
              <div class="table-responsive" style="width:50%;">
                <table class="table table-stripped table-bordered table-hover">
                  <thead>
                    <tr>
                      <th class="text-left"><?php echo $text_seller_name; ?></th>
                      <th class="text-right"><?php echo $text_seller_shipping; ?></th>
                    </tr>
                  </thead>
                  <tbody>
                  <?php foreach ($seller_custom_shipping as $key => $value) { ?>
                    <tr>
                        <td class="text-left"><?php echo $key; ?></td>
                        <td class="text-right"><?php echo $value; ?></td>
                    </tr>
                  <?php } ?>
                  </tbody>
                </table>
              </div>
            <?php } ?>
          <?php } ?>
        ]]></add>
      </operation>
    </file>
    <file path="catalog/model/journal2/checkout.php">
        <operation>
            <search><![CDATA[
              if ($product['image']) {
            ]]></search>
        <add position="before"><![CDATA[
          if(isset($product['commission_amount']))
            $product['price'] = $product['price'] + $product['commission_amount'];
        ]]></add>
        </operation>

        <operation>
            <search><![CDATA[
              $this->order_data['products'][] = array(
            ]]></search>
        <add position="before"><![CDATA[
          if(isset($product['commission_amount']))
            $product['price'] = $product['price'] + $product['commission_amount'];
        ]]></add>
        </operation>
    </file>
</modification>
