<?php
  class Notification_model extends CI_Model
  {
      var $appLiveChat = 10001;
      var $appMembersPro = 10002;
      var $appMembersLite = 10003;
      var $appAdvertising = 10004;
      var $appWishlistPlugin = 10005;
      var $appStores = 10006;
      var $appPublisher = 10007;
      var $appAnswer = 10008;
      var $appProject = 10009;
      var $appSuggest = 10010;
      var $appCRM = 10011;
      var $response = '';
      var $addToQueue = true;

      public function __construct()
      {
          parent::__construct();
      }

      #-------------------------------#
      # General Functions             #
      #-------------------------------#
      function postMessage($url, $requestString, $id = 0)
      {
          log_api_message('Notification Model', 'postMessage', 'Sending Information (' . $url . '): ' . $requestString);

          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_TIMEOUT, 10);
          curl_setopt($ch, CURLOPT_VERBOSE, 0);
          $headers = array("Cache-Control: no-cache", "Pragma: no-cache");
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

          $response = curl_exec($ch);
          $this->response = $response;
          log_api_message('Notification Model', 'postMessage', 'Response: ' . htmlentities($response));
          
          $error = '';
          
          if (curl_errno($ch))
          {
              if(!$id && $this->addToQueue)
              {
                  //saving the notification for try again
                  $pending = array('notification_url' => $url, 'notification_string' => $requestString, 'no_of_attempts' => 1);
                  $this->db->insert('tbl_api_pending_notification', $pending);
              }

              $curlErrorNo = curl_errno($ch);
              $curlErrorMessage = curl_error($ch);

              if($curlErrorNo || $curlErrorMessage)
              {
                  $error = $curlErrorNo . ': ' . $curlErrorMessage;
                  log_api_message('Notification Model', 'postMessage', $error);
                  return false;
              }
          }
          else
          {
              log_api_message('Notification Model', 'postMessage', 'Notification sent');
              curl_close($ch);
          }

          return true;
      }

      function sendFailedNotification()
      {
          log_api_message('Notification Model', 'sendFailedNotification', 'Resending failed notifications starts');
          $sql = 'SELECT * FROM tbl_api_pending_notification LIMIT 150';
          $query = $this->db->query($sql);
          $result = $query->result();

          if(count($result))
          {
              foreach($result as $row)
              {
                  if($this->postMessage($row->notification_url, $row->notification_string, $row->id) || $row->no_of_attempts == 4)
                  {
                      $sql = 'DELETE FROM tbl_api_pending_notification WHERE id = ' . $row->id;
                      $query = $this->db->query($sql);
                  }
                  else
                  {
                      $sql = 'UPDATE tbl_api_pending_notification
                             SET no_of_attempts = no_of_attempts + 1
                             WHERE id = ' . $row->id;
                      $query = $this->db->query($sql);
                  }
              }
              log_api_message('Notification Model', 'sendFailedNotification', 'Resending failed notifications ends');
          }
          else
          {
              log_api_message('Notification Model', 'sendFailedNotification', 'No notifications pending');
          }
      }

      function makeRequestString($data)
      {
          $request = '';

          if(!empty($data))
          {
              $r = array();

              foreach($data as $key => $value)
              {
                  $r[] = $key . '=' . urlencode($value);
              }
              $request = implode('&', $r);
          }

          return $request;
      }

      function getMerchantId($merchantRowId)
      {
          //DO NOT DELETE
          /*$sql = 'SELECT merchant_id FROM tbl_merchant WHERE merchant_row_id = ' . $merchantRowId;
          $q = $this->db->query($sql);
          $row = $q->row();

          if($row)
          {
              return $row->merchant_id;
          }

          */
          if($merchantRowId)
          {
              return 'MER-' . str_pad($merchantRowId, 5, '0', STR_PAD_LEFT);
          }

          return '';
      }

      function generateProfileId($recurringOrdersId)
      {
          return 'P-' . str_pad($recurringOrdersId, 11, '0', STR_PAD_LEFT);
      }

      function getAPIKey($appId)
      {
          if($appId)
          {
              $sql = 'SELECT app_key
                      FROM tbl_api_modules
                      WHERE app_id = ' . $this->db->escape($appId);
              $query = $this->db->query($sql);
              $row = $query->row();

              if($row)
              {
                  return $row->app_key;
              }
          }

          return '';
      }

      #-------------------------------#
      # PWC Members Pro Functions     #
      #-------------------------------#
      function sendMerchantSignUpNotificationToMembersPro($data)
      {
          $url = $this->config->item('nurl_members_pro_sign_up');

          if(!$url)
          {
              log_api_message('Notification on Merchant Signup', 'sendMerchantSignUpNotificationToMembersPro', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Sending Notification', 'PWCMembers', 'Merchant ID#' . $data['merchant_id']);
              $data['apikey'] = $this->getAPIKey($this->appMembersPro);

              $response = $this->makeRequestString($data);
              $this->postMessage($url, $response);
          }
      }

      function isUnderMerchantProCategory($categoryId, $parentCategory, $merchantRowId)
      {
          $sql = "SELECT category_id, category_description
                  FROM tbl_category
                  WHERE merchant_row_id = $merchantRowId
                  AND is_editable = 0
                  AND category_description IN ('Membership Pro', 'Membership Lite')";
          $query = $this->db->query($sql);
          $result = $query->result();

          if(!$result)
          {
              log_api_message('Category Check', 'isUnderMerchantProCategory', 'No category exists for membership pro or lite (Merchant: '.$merchantRowId.')');
              return false;
          }

          $memberProCategoryId = 0;
          $memberLiteCategoryId = 0;

          foreach($result as $row)
          {
              if($row->category_description == 'Membership Pro')
              {
                  $memberProCategoryId = $row->category_id;
              }
              else if($row->category_description == 'Membership Lite')
              {
                  $memberLiteCategoryId = $row->category_id;
              }
          }

          if($categoryId == $memberProCategoryId)
          {
              return true;
          }
          else if(!$parentCategory)
          {
              return false;
          }
          else if($parentCategory == $memberProCategoryId)
          {
              return true;
          }
          else // checking if membership pro is the ancestor
          {
              $currentParent = $parentCategory;

              while(true)
              {
                  $sql = "SELECT parent_category
                          FROM tbl_category
                          WHERE category_id = $currentParent";
                  $result = $this->db->query($sql);
                  $row = $result->row();

                  if($row)
                  {
                      if($row->parent_category == 0)
                      {
                          return false;
                      }
                      else if($row->parent_category == $memberProCategoryId)
                      {
                          return true;
                      }
                      $currentParent = $row->parent_category;
                  }
                  else
                  {
                      return false;
                  }
              }
          }
      }

      function sendNotificationToMembersProOnProductChange($productRowId, $status)
      {
          $sql = 'SELECT IFNULL(p.category_id, 0) AS category_id,
                        IFNULL(c.parent_category, 0) AS parent_category,
                        p.merchant_row_id,
                        p.product_description,
                        p.product_price,
                        p.enc_product_row_id
                  FROM tbl_product p
                  LEFT OUTER JOIN tbl_category c ON c.category_id = p.category_id
                  WHERE p.product_row_id = ' . $this->db->escape($productRowId);

          $query = $this->db->query($sql);
          $row = $query->row();

          if(!$row)
          {
              log_api_message('Notification on Product', 'sendNotificationToMembersProOnProductChange', 'No product found');
              return false;
          }
          else if(!$row->category_id)
          {
              log_api_message('Notification on Product', 'sendNotificationToMembersProOnProductChange', 'No category selected');
              return false;
          }
          else if(!$this->isUnderMerchantProCategory($row->category_id, $row->parent_category, $row->merchant_row_id))
          {
              log_api_message('Notification on Product', 'sendNotificationToMembersProOnProductChange', 'Category is not under Membership Pro:' . $row->merchant_row_id);
              return false;
          }


          if($status == $this->config->item('entity_deleted'))
          {
              $data['product_row_id'] = $productRowId;
              $data['apikey'] = $this->getAPIKey($this->appMembersPro);
              $data['status'] = 'deleted';
              $data['merchant_id'] = $this->getMerchantId($row->merchant_row_id);

              $url = $this->config->item('nurl_members_pro_product_delete');
          }
          else
          {
              $data = array('product_row_id' => $productRowId,
                            'description' => htmlentities($row->product_description, ENT_QUOTES),
                            'price' => $row->product_price,
                            'category_id' => $row->category_id,
                            'parent_category_id' => $row->parent_category,
                            'link_id' => $row->enc_product_row_id,
                            'apikey' => $this->getAPIKey($this->appMembersPro),
                            'merchant_id' => $this->getMerchantId($row->merchant_row_id));

              $data['status'] = $status == $this->config->item('entity_created') ? 'created' : 'updated';

              $url = $this->config->item('nurl_members_pro_product_update');
          }

          $response = $this->makeRequestString($data);

          if(!$response)
          {
              log_api_message('Notification on Product', 'sendNotificationToMembersProOnProductChange', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Product Notification', 'PWCMembers', 'Merchant ID# ' . $row->merchant_row_id);
              $this->postMessage($url, $response);
          }

          return true;
      }

      function sendNotificationOnOrderSuccess($order, $productList)
      {
          if(count($productList))
          {
              $found = false;
              foreach($productList as $product)
              {
                  if($product->category_id)
                  {
                      $sql = 'SELECT c.category_id,
                                    IFNULL(c.parent_category, 0) AS parent_category
                      FROM tbl_category c
                      WHERE c.category_id = ' . $product->category_id;

                      $query = $this->db->query($sql);
                      $row = $query->row();

                      if(!$row || !$row->category_id || !$this->isUnderMerchantProCategory($row->category_id, $row->parent_category, $order->merchant_row_id))
                      {
                          continue;
                      }

                      $found = true;
                      break;
                  }
              }

              if($found)
              {
                  $data['oid'] = $order->order_row_id;
                  $data['order_id'] = $order->order_id;
                  $data['merchant_id'] = $this->getMerchantId($order->merchant_row_id);
                  $data['apikey'] = $this->getAPIKey($this->appMembersPro);

                  $url = $this->config->item('nurl_members_pro_order');

                  $response = $this->makeRequestString($data);

                  if(!$response)
                  {
                      log_api_message('Notification on Order', 'sendNotificationOnOrderSuccess', 'Notification text is missing');
                  }
                  else
                  {
                      $this->postMessage($url, $response);
                  }
              }
          }
      }

      function sendRecurringNotificationToMpro($data)
      {
          log_api_message('Notification on Recurring Order', 'sendRecurringNotificationToMpro', 'sendRecurringNotificationToMpro Started');
          if(!$this->config->item('enable_member_pro_notification'))                                                           
          {
             log_api_message('Notification on Recurring Order', 'sendRecurringNotificationToMpro', 'Notification not enabled');
             return false;
          }
          $data['merchant_id'] = $this->getMerchantId($data['merchant_row_id']);
          $data['apikey'] = $this->getAPIKey($this->appMembersPro);
          $url = $this->config->item('nurl_members_pro_order_recurring');
          
          if(!$data['category_id'])
          {
             log_api_message('Notification on Recurring Order', 'sendRecurringNotificationToMpro', 'Category Id not found.');
             return false;
          }
          $sql = 'SELECT c.category_id, IFNULL(c.parent_category, 0) AS parent_category FROM tbl_category c WHERE c.category_id = ' . $data['category_id'];

          $query = $this->db->query($sql);
          $row = $query->row();

          if(!$this->isUnderMerchantProCategory($row->category_id, $row->parent_category, $data['merchant_row_id']))
          {
             log_api_message('Notification on Recurring Order', 'sendRecurringNotificationToMpro', 'Product is not under MPro Category.');
             return false;
          }

          $response = $this->makeRequestString($data);

          if(!$response)
              log_api_message('Notification on Recurring Order', 'sendRecurringNotificationToMpro', 'Notification text is missing');
          else
              $this->postMessage($url, $response);
      }
      
      /**
      *@desc Sends a notification if the ancestor of the category is 'Membership Pro'.
      */
      function sendNotificationToMembersProOnCategoryChange($merchantRowId, $categoryId, $parentCategory, $status)
      {
          if(!$parentCategory || !$this->isUnderMerchantProCategory($categoryId, $parentCategory, $merchantRowId))
          {
              return;
          }

          if($status == $this->config->item('entity_deleted'))
          {
              $data['category_id'] = $categoryId;
              $data['parent_category_id'] = $parentCategory;
              $data['apikey'] = $this->getAPIKey($this->appMembersPro);
              $data['status'] = 'deleted';

              $url = $this->config->item('nurl_members_pro_category_delete');
          }
          else
          {
              $sql = 'SELECT category_id,
                            parent_category AS parent_category_id,
                            category_description
                      FROM tbl_category
                      WHERE category_id = ' . $categoryId .'
                      AND merchant_row_id = ' . $merchantRowId;

              $query = $this->db->query($sql);
              $data = $query->row_array();
              $data['apikey'] = $this->getAPIKey($this->appMembersPro);

              if($status == $this->config->item('entity_created'))
              {
                  $data['status'] = 'created';
              }
              else
              {
                  $data['status'] = 'updated';
              }

              $url = $this->config->item('nurl_members_pro_category_update');
          }

          $data['merchant_id'] = $this->getMerchantId($merchantRowId);

          $response = $this->makeRequestString($data);

          if(!$response)
          {
              log_api_message('Notification on Category', 'sendNotificationToMembersProOnCategoryChange', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Category Notification', 'PWCMembers', 'Merchant ID#' . $merchantRowId);
              $this->postMessage($url, $response);
          }
      }

      /**
      *@desc Notification on merchant's package change from merchant panel or super admin panel or a merchant is ugraded  from trial
      */
      function sendMerchantPackageChangeNotificationToMembersPro($data)
      {
          $url = $this->config->item('nurl_members_pro_package_change');

          if(!$url){
              log_api_message('Notification on Package Change', 'sendMerchantPackageChangeNotificationToMembersPro', 'Notification URL is missing');
          }
          else{
              $info['merchant_id'] = $this->getMerchantId($data['merchant_row_id']);
              $info['new_package_id'] = $data['package_id'];
              $info['subscription_type'] = $data['subscription_type'];

              log_api_message('Sending Notification', 'Members Pro', 'Merchant ID#' . $info['merchant_id']);
              $info['apikey'] = $this->getAPIKey($this->appMembersPro);

              $response = $this->makeRequestString($info);
              $this->postMessage($url, $response);
          }
      }

      #-------------------------------#
      # PWC CRM Functions             #
      #-------------------------------#

      /**
      *@desc Notification on order delete
      */
      function sendDeletOrderNotificationToCRM($orderRowId, $merchant_row_id)
      {
          $url = $this->config->item('nurl_crm_delete_order');

          if(!$url)
          {
              log_api_message('Notification on delete order', 'sendDeletOrderNotificationToCRM', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Notification on delete order', 'CRM', 'Merchant ID#' .$data->merchant_row_id);
              $reData['apikey'] = $this->getAPIKey($this->appCRM);
              $reData['merchant_id'] = $this->getMerchantId($merchant_row_id);

              if(is_array($orderRowId))
              {
                    foreach($orderRowId as $id)
                  {
                      $reData['order_unique_id'] = $id;
                      $response = $this->makeRequestString($reData);
                      $this->postMessage($url, $response);
                  }
              }
              else
              {
                  $reData['order_unique_id'] = $orderRowId;
                  $response = $this->makeRequestString($reData);
                  $this->postMessage($url, $response);
              }
          }
      }

      /**
      *@desc Notification on order refund/charge back
      */
      function sendRefundOrderNotificationToCRM($data)
      {
          $url = $this->config->item('nurl_crm_refund_order');

          if(!$url)
          {
              log_api_message('Notification on refund order', 'sendRefundOrderNotificationToCRM', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Notification on refund order', 'CRM', 'Merchant ID#' . $data['merchant_row_id']);
              $reData['apikey'] = $this->getAPIKey($this->appCRM);
              $reData['merchant_id'] = $this->getMerchantId($data['merchant_row_id']);
              $reData['order_unique_id'] = $data['order_row_id'];
              $reData['refund_total'] = $data['refund_total'];
              $reData['refund_shipping_total'] = $data['refund_shipping_total'];
              $reData['refund_sales_tax_total'] = $data['refund_sales_tax_total'];
              $reData['refund_product_total'] =  $data['refund_total']-$data['refund_shipping_total']-$data['refund_sales_tax_total'];
              $reData['type'] = $data['type'];
              $reData['refund_date'] = getCurrentDateTimeForDB();
              $response = $this->makeRequestString($reData);
              $this->postMessage($url, $response);
          }
      }

      /**
      *@desc Notification on recurring order refund/charge back
      */
      function sendRecurringRefundOrderNotificationToCRM($data)
      {
          $url = $this->config->item('nurl_crm_recurring_refund_order');

          if(!$url)
          {
              log_api_message('Notification on recurring refund order', 'sendRecurringRefundOrderNotificationToCRM', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Notification on recurring refund order', 'CRM', 'Merchant ID#' . $data['merchant_row_id']);
              $reData['apikey'] = $this->getAPIKey($this->appCRM);
              $reData['merchant_id'] = $this->getMerchantId($data['merchant_row_id']);
              $reData['order_unique_id'] = $data['order_row_id'];
              $reData['recurring_profile_id'] = $this->generateProfileId($data['recurring_orders_id']);
              $reData['refund_total'] = $data['refund_total'];
              $reData['refund_shipping_total'] = $data['refund_shipping_total'];
              $reData['refund_sales_tax_total'] = $data['refund_sales_tax_total'];
              $reData['refund_product_total'] =  $data['refund_total']-$data['refund_shipping_total']-$data['refund_sales_tax_total'];
              $reData['type'] = $data['type'];
              $reData['refund_date'] = getCurrentDateTimeForDB();
              $response = $this->makeRequestString($reData);
              $this->postMessage($url, $response);
          }
      }

      /**
      *@desc Notification on merchant sign up
      */
      function sendMerchantSignUpNotificationToCRM($data)
      {
          $url = $this->config->item('nurl_crm_sign_up');

          if(!$url)
          {
              log_api_message('Notification on Merchant Signup', 'sendMerchantSignUpNotificationToCRM', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Sending Notification', 'CRM', 'Merchant ID#' . $data['merchant_id']);
              $data['apikey'] = $this->getAPIKey($this->appCRM);

              $response = $this->makeRequestString($data);
              $this->postMessage($url, $response);
          }
      }


      function sendPWPSignUpNotificationToCRM($data)
      {
          $url = $this->config->item('nurl_crm_pwp_package_upgrade');

          if(!$url)
          {
              log_api_message('Notification on PWP Signup', 'sendPWPSignUpNotificationToCRM', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Sending Notification', 'CRM', 'Merchant ID#' . $data['merchant_id']);
              $data['apikey'] = $this->getAPIKey($this->appCRM);

              $response = $this->makeRequestString($data);
              $this->postMessage($url, $response);
          }
      }

      function sendPWPSignUpNotificationToPWP($data)
      {
          $url = $this->config->item('nurl_pwp_package_upgrade');

          if(!$url)
          {
              log_api_message('Notification on PWP Signup', 'sendPWPSignUpNotificationToPWP', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Sending Notification', 'CRM', 'Merchant ID#' . $data['merchant_id']);
              $data['apikey'] = $this->getAPIKey($this->appCRM);

              $response = $this->makeRequestString($data);
              $this->postMessage($url, $response);
          }
      }



      /**
      *@desc Notification on merchant's package change from merchant panel or super admin panel or after trial upgrade
      */
      function sendMerchantPackageChangeNotificationToCRM($data)
      {
          $url = $this->config->item('nurl_crm_package_change');

          if(!$url){
              log_api_message('Notification on Package Change', 'sendMerchantPackageChangeNotificationToCRM', 'Notification URL is missing');
          }
          else{
              $info['merchant_id'] = $this->getMerchantId($data['merchant_row_id']);
              $info['new_package_id'] = $data['package_id'];
              $info['subscription_type'] = $data['subscription_type'];
              $info['active_or_not'] = isset($data['active_or_not']) ? $data['active_or_not'] : 1;

              if(isset($data['company_name']))
              {
                  $info['company_name'] = $data['company_name'];
              }
              log_api_message('Sending Notification', 'CRM', 'Merchant ID#' . $info['merchant_id']);
              $info['apikey'] = $this->getAPIKey($this->appCRM);

              $response = $this->makeRequestString($info);
              $this->postMessage($url, $response);
          }
      }



      function notifyCrmOnProductChange($notification, $merchantRowId)
      {
          $url = $this->config->item('nurl_crm_product');

          if(!$url)
          {
              log_api_message('Notification on Product Change', 'notifyCrmOnProductChange', 'Notification URL is missing');
              return;
          }

          $notification['merchant_id'] = $this->getMerchantId($merchantRowId);
          $notification['apikey'] = $this->getAPIKey($this->appCRM);

          $response = $this->makeRequestString($notification);

          if(!$response)
          {
              log_api_message('Notification on Product Change', 'notifyCrmOnProductChange', 'Notification text is missing');
          }
          else
          {
              $this->postMessage($url, $response);
          }
      }

      function notifyCrmOnOrderSuccess($merchantRowId, $orderRowId, $recurringOrdersId = 0, $url = '')
      {
          $url = empty($url) ? $this->config->item('nurl_crm_order') : $url;

          if(!$url)
          {
              log_api_message('Notification on Order Change', 'notifyCrmOnOrderSuccess', 'Notification URL is missing');
              return;
          }

          if($recurringOrdersId)
          {
              $notification['recurring_profile_id'] = $this->generateProfileId($recurringOrdersId);
              $notification['is_subscription'] = 1;
          }
          else
          {
              $notification['recurring_profile_id'] = 0;
              $notification['is_subscription'] = 0;
          }

          $notification['order_unique_id'] = $orderRowId;
          $notification['merchant_id'] = $this->getMerchantId($merchantRowId);

          $notification['apikey'] = $this->getAPIKey($this->appCRM);

          $response = $this->makeRequestString($notification);

          if(!$response)
          {
              log_api_message('Notification on Order Change', 'notifyCrmOnOrderSuccess', 'Notification text is missing');
          }
          else
          {
              $this->postMessage($url, $response);
          }
      }

      function sendCRMExpressCheckoutCustomerNotification($notification, $merchantRowId)
      {
          $url = $this->config->item('nurl_crm_express_checkout_customer');
          if(!$url)
          {
              log_api_message('Notification on Express checkout Customer', 'sendCRMExpressCheckoutCustomerNotification', 'Notification URL is missing');
              return;
          }
          $notification['merchant_id'] = $this->getMerchantId($merchantRowId);

          $notification['apikey'] = $this->getAPIKey($this->appCRM);
          $requestString = $this->makeRequestString($notification);
          if(!$requestString)
          {
              log_api_message('Notification on Express Checkout Customer Information', 'sendCRMExpressCheckoutCustomerNotification', 'Notification text is missing');
          }
          else
          {
              $this->postMessage($url, $requestString);
              return $this->response;
          }
      }

      #-------------------------------#
      # PWC Project Manager Functions    #
      #-------------------------------#
      function sendMerchantSignUpNotificationToProject($data)
      {
          $url = $this->config->item('nurl_project_sign_up');

          if(!$url)
          {
              log_api_message('Notification on Merchant Signup', 'sendMerchantSignUpNotificationToProject', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Sending Notification', 'Project', 'Merchant ID#' . $data['merchant_id']);
              $data['apikey'] = $this->getAPIKey($this->appProject);

              $response = $this->makeRequestString($data);
              $this->postMessage($url, $response);
          }
      }

      /**
      *@desc Notification on merchant's package change from merchant panel or super admin panel or a merchant is ugraded  from trial
      */
      function sendMerchantPackageChangeNotificationToProject($data)
      {
          $url = $this->config->item('nurl_project_package_change');

          if(!$url){
              log_api_message('Notification on Package Change', 'sendMerchantPackageChangeNotificationToProject', 'Notification URL is missing');
          }
          else{
              $info['merchant_id'] = $this->getMerchantId($data['merchant_row_id']);
              $info['new_package_id'] = $data['package_id'];
              $info['subscription_type'] = $data['subscription_type'];

              log_api_message('Sending Notification', 'CRM', 'Merchant ID#' . $info['merchant_id']);
              $info['apikey'] = $this->getAPIKey($this->appProject);

              $response = $this->makeRequestString($info);
              $this->postMessage($url, $response);
          }
      }

      function isUnderTaskManagerCategory($categoryId, $parentCategory, $merchantRowId)
      {
          $sql = 'SELECT category_id, category_description
                  FROM tbl_category
                  WHERE merchant_row_id = ' . $merchantRowId . '
                  AND is_editable = 0
                  AND category_description = \'Task Manager\'
                  LIMIT 1';
          $query = $this->db->query($sql);
          $tmCategory = $query->row();

          if(!$tmCategory)
          {
              log_api_message('Category Check', 'isUnderTaskManagerCategory', 'No category exists for task manager (Merchant: '.$merchantRowId.')');
              return false;
          }

          if($categoryId == $tmCategory->category_id)
          {
              return true;
          }
          else if(!$parentCategory)
          {
              return false;
          }
          else if($parentCategory == $tmCategory->category_id)
          {
              return true;
          }
          else // checking if task manager is the ancestor
          {
              $currentParent = $parentCategory;

              while(true)
              {
                  $sql = 'SELECT parent_category
                          FROM tbl_category
                          WHERE category_id = ' . $currentParent;
                  $result = $this->db->query($sql);
                  $row = $result->row();

                  if($row)
                  {
                      if($row->parent_category == 0)
                      {
                          return false;
                      }
                      else if($row->parent_category == $tmCategory->category_id)
                      {
                          return true;
                      }
                      $currentParent = $row->parent_category;
                  }
                  else
                  {
                      return false;
                  }
              }
          }
      }

      function sendNotificationToProjectOnProductChange($productRowId, $status)
      {
          $sql = 'SELECT IFNULL(p.category_id, 0) AS category_id,
                        IFNULL(c.parent_category, 0) AS parent_category,
                        p.merchant_row_id,
                        p.product_description,
                        p.product_price,
                        p.enc_product_row_id
                  FROM tbl_product p
                  LEFT OUTER JOIN tbl_category c ON c.category_id = p.category_id
                  WHERE p.product_row_id = ' . $this->db->escape($productRowId);

          $query = $this->db->query($sql);
          $row = $query->row();

          if(!$row)
          {
              log_api_message('Notification on Product', 'sendNotificationToProjectOnProductChange', 'No product found');
              return false;
          }
          else if(!$row->category_id)
          {
              log_api_message('Notification on Product', 'sendNotificationToProjectOnProductChange', 'No category selected');
              return false;
          }
          else if(!$this->isUnderTaskManagerCategory($row->category_id, $row->parent_category, $row->merchant_row_id))
          {
              log_api_message('Notification on Product', 'sendNotificationToProjectOnProductChange', 'Category is not under Task Manager');
              return false;
          }

          if($status == $this->config->item('entity_deleted'))
          {
              $data['product_row_id'] = $productRowId;
              $data['apikey'] = $this->getAPIKey($this->appProject);
              $data['status'] = 'deleted';
              $data['merchant_id'] = $this->getMerchantId($row->merchant_row_id);

              $url = $this->config->item('nurl_project_product_delete');
          }
          else
          {
              $data = array('product_row_id' => $productRowId,
                            'description' => htmlentities($row->product_description, ENT_QUOTES),
                            'price' => $row->product_price,
                            'category_id' => $row->category_id,
                            'parent_category_id' => $row->parent_category,
                            'link_id' => $row->enc_product_row_id,
                            'apikey' => $this->getAPIKey($this->appProject),
                            'merchant_id' => $this->getMerchantId($row->merchant_row_id));

              $data['status'] = $status == $this->config->item('entity_created') ? 'created' : 'updated';

              $url = $this->config->item('nurl_project_product_update');
          }

          $response = $this->makeRequestString($data);

          if(!$response)
          {
              log_api_message('Notification on Product', 'sendNotificationToProjectOnProductChange', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Product Notification', 'Task Manager', 'Merchant ID# ' . $row->merchant_row_id);
              $this->postMessage($url, $response);
          }

          return true;
      }

      function notifyProjectOnOrderSuccess($order, $productList)
      {
          if(count($productList))
          {
              $found = false;
              foreach($productList as $product)
              {
                  if($product->category_id)
                  {
                      $sql = 'SELECT c.category_id, 0,
                                    IFNULL(c.parent_category, 0) AS parent_category
                      FROM tbl_category c
                      WHERE c.category_id = ' . $product->category_id;

                      $query = $this->db->query($sql);
                      $row = $query->row();

                      if(!$row || !$row->category_id || !$this->isUnderTaskManagerCategory($row->category_id, $row->parent_category, $order->merchant_row_id))
                      {
                          continue;
                      }

                      $found = true;
                      break;
                  }
              }

              if($found)
              {
                  $data['oid'] = $order->order_row_id;
                  $data['order_id'] = $order->order_id;
                  $data['merchant_id'] = $this->getMerchantId($order->merchant_row_id);;
                  $data['apikey'] = $this->getAPIKey($this->appProject);

                  $url = $this->config->item('nurl_project_order');

                  $response = $this->makeRequestString($data);

                  if(!$response)
                  {
                      log_api_message('Notification on Order', 'notifyProjectOnOrderSuccess', 'Notification text is missing');
                  }
                  else
                  {
                      $this->postMessage($url, $response);
                  }
              }
          }
      }

      function notifyProjectOnRecurringProfileAdd($data, $status){
          if(!empty($data['category_id'])){
              $this->db->select('parent_category');
              $this->db->where('category_id', $data['category_id']);
              $query = $this->db->get('tbl_category');
              $row = $query->row();
              if($this->isUnderTaskManagerCategory($data['category_id'], $row->parent_category, $data['merchant_row_id'])){
                  $notify['apikey'] = $this->getAPIKey($this->appProject);
                  $notify['merchant_id'] = $this->getMerchantId($data['merchant_row_id']);
                  $notify['oid'] = $data['order_row_id'];
                  $notify['profile_id'] = $this->generateProfileId($data['recurring_orders_id']);
                  $notify['product_id'] = $data['product_id'];
                  $notify['product_name'] = $data['product_description'];
                  $notify['quantity'] = $data['product_quantity'];
                  $notify['recurring_price'] = $data['recurring_price'];
                  $notify['recurrin_logic'] = $data['recurring_logic'];
                  $notify['recurring_pattern'] = $data['recurring_pattern'];
                  $notify['recurring_cycle'] = $data['recurring_cycle'];
                  $notify['recurring_count'] = $data['recurring_count'];
                  $notify['recurring_start_duration'] = $data['recurring_start_duration'];
                  $notify['recurring_start_date'] = $data['recurring_start_date'];
                  $notify['recurring_end_date'] = $data['recurring_end_date'];
                  $notify['recurring_day_of_week'] = $data['recurring_day_of_week'];
                  $notify['recurring_day_of_month'] = $data['recurring_day_of_month'];
                  $notify['recurring_week_of_month'] = $data['recurring_week_of_month'];
                  $notify['recurring_monthly_option'] = $data['recurring_monthly_option'];
                  $notify['date_of_next_charge'] = $data['date_of_next_charge'];
                  $notify['status'] = $status == $this->config->item('entity_created') ? 'created' : ($status == $this->config->item('entity_updated') ? 'updated' : 'deleted');

                  $url = $this->config->item('nurl_project_recurring_create');

                  $response = $this->makeRequestString($notify);

                  if(!$response){
                      log_api_message('Notification on Recurring Order Add', 'notifyProjectOnRecurringProfileAdd', 'Notification text is missing');
                  }
                  else{
                      $this->postMessage($url, $response);
                  }
              }
          }
      }

      #-------------------------------#
      # PWC Members Lite Functions    #
      #-------------------------------#
      function sendMerchantSignUpNotificationToMembersLite($data)
      {
          $url = $this->config->item('nurl_members_lite_sign_up');

          if(!$url)
          {
              log_api_message('Notification on Merchant Signup', 'sendMerchantSignUpNotificationToMembersLite', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Sending Notification', 'Members Lite', 'Merchant ID#' . $data['merchant_id']);
              $data['apikey'] = $this->getAPIKey($this->appMembersLite);

              $response = $this->makeRequestString($data);
              $this->postMessage($url, $response);
          }
      }

      #-------------------------------#
      # PWC Advertising Functions     #
      #-------------------------------#
      function sendMerchantSignUpNotificationToAdvertising($data)
      {
          $url = $this->config->item('nurl_advertising_sign_up');

          if(!$url)
          {
              log_api_message('Notification on Merchant Signup', 'sendMerchantSignUpNotificationToAdvertising', 'Notification URL is missing');
          }
          else
          {
              log_api_message('Sending Notification', 'Advertising', 'Merchant ID#' . $data['merchant_id']);

              $data['apikey'] = $this->getAPIKey($this->appAdvertising);

              $response = $this->makeRequestString($data);
              $this->postMessage($url, $response);
          }
      }

      #-------------------------------#
      # PWC Stores Functions          #
      #-------------------------------#

      /**
      *@desc Returns notification URL for PWC Stores
      */
      function getStoresNotificationURL($merchantRowId)
      {
          $sql = 'SELECT IFNULL(stores_notification_url, \'\') AS stores_notification_url
                  FROM tbl_merchant
                  WHERE merchant_row_id = ' . $merchantRowId;
          $query = $this->db->query($sql);
          $row = $query->row();

          return $row->stores_notification_url;
      }

      function sendNotificationOnCategoryChange($merchantRowId, $categoryId, $parentCategory, $status)
      {
          $url = $this->getStoresNotificationURL($merchantRowId);

          if(!$url)
          {
              return false;
          }

          if($status == $this->config->item('entity_deleted'))
          {
              $data['category_id'] = $categoryId;
              $data['parent_category_id'] = $parentCategory;
              $data['status'] = 'deleted';
          }
          else
          {
              $sql = 'SELECT category_id,
                            parent_category AS parent_category_id,
                            category_description,
                            level,
                            hasChild AS has_child,
                            is_editable,
                            create_date AS created_on,
                            modified_on
                      FROM tbl_category
                      WHERE category_id = ' . $categoryId . '
                      AND merchant_row_id = ' . $merchantRowId;

              $query = $this->db->query($sql);
              $data = $query->row_array();

              if($status == $this->config->item('entity_created'))
              {
                  $data['status'] = 'created';
              }
              else
              {
                  $data['status'] = 'updated';
              }
          }

          $data['merchant_id'] = $this->getMerchantId($merchantRowId);

          $data['apikey'] = $this->getAPIKey($this->appStores);
          $data['entity'] = 'category';

          $response = $this->makeRequestString($data);

          if(!$response)
          {
              log_api_message('Notification on Category', 'sendNotificationOnCategoryChange', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Category Notification', $data['apikey'], 'Merchant ID#' . $merchantRowId);
              $this->postMessage($url, $response);
          }
      }

      /**
      *@desc Sends notification on product add, edit, delete
      *
      * @param int $productRowId
      * @param string $status
      * @param string $key - api key
      */
      function sendNotificationOnProductChange($productRowId, $status)
      {
          $sql = 'SELECT p.product_row_id,
                        IFNULL(p.category_id, 0) AS category_id,
                        p.merchant_row_id,
                        p.product_description,
                        p.product_price,
                        p.product_price_private,
                        p.product_price_wholeseller,
                        p.product_price_distributor,
                        p.product_code,
                        p.enc_product_row_id,
                        p.product_image,
                        p.clear_cart,
                        p.enable_sales_price,
                        p.product_sale_price,
                        p.sale_price_start_date,
                        p.sale_price_end_date,
                        p.sale_tag_icon,
                        p.stateTaxRate,
                        p.countryTaxRate,
                        p.is_tax_applicable,
                        p.is_payable_later,
                        p.is_free,
                        plf.shortDesc,
                        plf.longDesc,
                        man.manufacturer_info AS manufactureinformation,
                        p.created_on,
                        p.modified_on,
                        p.free_shipping,
                        p.use_inventory,
                        p.current_inventory,
                        cb.currency,
                        p.qty_discount_vs_saleprice_option,
                        p.is_mass_attribute,
                        p.unit_credit
                  FROM tbl_product p
                  INNER JOIN tbl_cart_basic cb ON cb.merchant_row_id = p.merchant_row_id
                  LEFT OUTER JOIN tbl_product_look_and_feel plf ON plf.product_row_id = p.product_row_id
				  LEFT JOIN tbl_manufacturer man ON man.mfg_id = p.manufacturer_id
                  WHERE p.product_row_id = ' . $this->db->escape($productRowId);

          $query = $this->db->query($sql);
          $row = $query->row();

          if(!$row)
          {
              log_api_message('Notification on Product', 'sendNotificationOnProductChange', 'No product found');
              return false;
          }
          
          $url = $this->getStoresNotificationURL($row->merchant_row_id);

          if(!$url)
          {
              return false;
          }

          $data['merchant_id'] = $this->getMerchantId($row->merchant_row_id);

          if($status == $this->config->item('entity_deleted'))
          {
              $data['product_row_id'] = $productRowId;
              $data['status'] = 'deleted';
          }
          else
          {
              $sql = "SELECT *FROM tbl_quantity_discount WHERE product_row_id = " . $productRowId . " ORDER BY quantity_discount_id ASC";
              $query = $this->db->query($sql);
              $discounts = $query->result_array();
              foreach($discounts as $key => $item)
              {
                  $data['lower_limit_'       . ($key+1)] = $item['lower_limit'];
                  $data['upper_limit_'       . ($key+1)] = $item['upper_limit'];
                  $data['discount_amount_'   . ($key+1)] = $item['discount_amount'];
                  $data['discount_type_'     . ($key+1)] = $item['discount_type'];
              }

              $data['product_row_id']   = $productRowId;
              $data['product_name']     = htmlentities($row->product_description, ENT_QUOTES);
              $data['product_sku']      = $row->product_code;
              $data['price']            = $row->product_price;
              $data['product_price_private']     = $row->product_price_private;
              $data['product_price_wholeseller'] = $row->product_price_wholeseller;
              $data['product_price_distributor'] = $row->product_price_distributor;
              $data['currency']         = $row->currency;
              $data['category_id']      = $row->category_id;
              $data['link_id']          = $row->enc_product_row_id;
              $data['shortDesc']        = $row->shortDesc;
              $data['longDesc']         = $row->longDesc;
              $data['manufactureInfo']  = $row->manufactureinformation;

              $data['enable_sales_price']    = $row->enable_sales_price;
              $data['product_sale_price']    = $row->product_sale_price;
              $data['sale_tag_icon']         = $row->sale_tag_icon;

              if(substr($row->sale_price_start_date, 0, 4) > 1)
                $data['sale_price_start_date'] = $row->sale_price_start_date;
              if(substr($row->sale_price_end_date, 0, 4) > 1)
                $data['sale_price_end_date']   = $row->sale_price_end_date;


              $data['state_tax_rate']    = $row->stateTaxRate;
              $data['country_tax_rate']  = $row->countryTaxRate;
              $data['is_tax_applicable'] = $row->is_tax_applicable;
              $data['is_payable_later']  = $row->is_payable_later;
              $data['is_free']           = $row->is_free;
              $data['qty_discount_vs_saleprice_option'] = $row->qty_discount_vs_saleprice_option;
              $data['use_inventory']     = $row->use_inventory;
              $data['current_inventory'] = $row->current_inventory;
              $data['is_mass_attribute'] = $row->is_mass_attribute;
              $data['unit_credit']       = $row->unit_credit;
              
              if($row->clear_cart)
              {
                  $data['regular_buy_link'] = NONSECUREBASEURL . 'carts/shopping_cart/myShoppingCart/' . $row->enc_product_row_id . '/1.html';
                  $data['one_click_buy_link'] = NONSECUREBASEURL . 'carts/shopping_cart/oneClickProductBuy/' . $row->enc_product_row_id . '/1.html';
              }
              else
              {
                  $data['regular_buy_link'] = NONSECUREBASEURL . 'carts/shopping_cart/myShoppingCart/' . $row->enc_product_row_id . '.html';
                  $data['one_click_buy_link'] = NONSECUREBASEURL . 'carts/shopping_cart/oneClickProductBuy/' . $row->enc_product_row_id . '.html';
              }

              $data['product_image'] = $row->product_image ? NONSECUREBASEURL . $row->product_image : '';
              if($status == $this->config->item('entity_created'))
              {
                  $data['status'] = 'created';
              }
              elseif($status == $this->config->item('entity_deleted'))
              {
                  $data['status'] = 'deleted';
              }
              else
              {
                  $data['status'] = 'updated';

                  $recurringProfile = $this->product->getRecurringProfileByProductId($productRowId);
                  foreach($recurringProfile as $count => $profile)
                  {
                      unset($profile['recurring_profile_row_id']); 
                      foreach($profile as $key => $value)
                      {
                          $data[$key . '_' . ($count + 1)] = $value;                             
                      }
                  }    
              }
              //$data['status'] = $status == $this->config->item('entity_created') ? 'created' : 'updated';
              $data['created_on'] = $row->created_on;
              $data['modified_on'] = $row->modified_on;
              $data['free_shipping'] = $row->free_shipping;
          }

          $data['apikey'] = $this->getAPIKey($this->appStores);
          $data['entity'] = 'product';
          $response = $this->makeRequestString($data);

          if(!$response)
          {
              log_api_message('Notification on Product', 'sendNotificationOnProductChange', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Product Notification', $data['apikey'], 'Merchant ID# ' . $row->merchant_row_id);
              $this->postMessage($url, $response);
          }

          return true;
      }

      function sendNotificationToStoresOnManufacturerChange($merchantRowId, $info, $status)
      {
          $url = $this->getStoresNotificationURL($merchantRowId);

          if(!$url)
          {
              return false;
          }

          $data['manufacturer_id'] = $info['mfg_id'];
          if($status == $this->config->item('entity_deleted'))
          {
              $data['status'] = 'deleted';
          }
          else
          {
              $data['manufacturer_name'] = $info['mfg_name'];
              $data['manufacturer_info'] = $info['manufacturer_info'];
              $data['created_on'] = $info['creation_date'];

              if($status == $this->config->item('entity_created'))
              {
                  $data['status'] = 'created';
                  $data['modified_on'] = $info['creation_date'];
              }
              else
              {
                  $data['status'] = 'updated';
                  $data['modified_on'] = $info['modify_date'];
              }
          }

          $data['merchant_id'] = $this->getMerchantId($merchantRowId);
          $data['apikey'] = $this->getAPIKey($this->appStores);
          $data['entity'] = 'manufacturer';

          $response = $this->makeRequestString($data);

          if(!$response)
          {
              log_api_message('Notification on Category', 'sendNotificationToStoresOnManufacturerChange', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Category Notification', $data['apikey'], 'Merchant ID#' . $merchantRowId);
              $this->postMessage($url, $response);
          }
      }

      function sendNotificationOnSaveAttributeChange($data)
      {
          $merchantRowId = getCurrentMerchantId();
          $url = $this->getStoresNotificationURL($merchantRowId);
          if(!$url)
          {
              return false;
          }

          $data['apikey'] = $this->getAPIKey($this->appStores);

          $data['entity'] = 'attribute';
          $response = $this->makeRequestString($data);
          if(!$response)
          {
              log_api_message('Notification on Attribute Change', 'sendNotificationOnAtributeChange', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Attribute Notification', $data['apikey'], 'Merchant ID# ' . $merchantRowId);
              $this->postMessage($url, $response);
          }
          return true;
      }

      function sendNotificationOnSaveAttributeGroupChange($data)
      {
          $merchantRowId = getCurrentMerchantId();
          $data['merchant_id'] = $this->getMerchantId($merchantRowId);
          $url = $this->getStoresNotificationURL($merchantRowId);
          if(!$url)
          {
              return false;
          }

          $data['apikey'] = $this->getAPIKey($this->appStores);

          $data['entity'] = 'attributegroup';
          $response = $this->makeRequestString($data);
          if(!$response)
          {
              log_api_message('Notification on Attribute Group', 'sendNotificationOnAttributeGroupChange', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Attribute Group Notification', $data['apikey'], 'Merchant ID# ' . $merchantRowId);
              $this->postMessage($url, $response);
          }

          return true;
      }

      function sendNotificationOnAttributeAssign($data)
      {
          $merchantRowId = getCurrentMerchantId();
          $url = $this->getStoresNotificationURL($merchantRowId);
          if(!$url)
          {
              return false;
          }

          $data['apikey'] = $this->getAPIKey($this->appStores);

          $data['entity'] = 'attribute';
          $response = $this->makeRequestString($data);
          if(!$response)
          {
              log_api_message('Notification on Attribute Assign', 'sendNotificationOnAttributeAssign', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Attribute Assign Notification', 'sendNotificationOnAttributeAssign', 'Merchant ID# ' . $merchantRowId);
              $this->postMessage($url, $response);
          }

          return true;
      }


      function sendNotificationOnSales($data)
      {
          $url = $this->getStoresNotificationURL($data['merchant_row_id']);
          if(!$url)
          {
              return false;
          }

          $data['apikey'] = $this->getAPIKey($this->appStores);

          $data['entity'] = 'product';
          $response = $this->makeRequestString($data);
          if(!$response)
          {
              log_api_message('Notification on Sales', 'sendNotificationOnSales', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending Sales Notification', $data['apikey'], 'Merchant ID# ' . $data['merchant_row_id']);
              $this->postMessage($url, $response);
          }

          return true;
      }


      function sendNotificationToStoresOnBasicOptionChange($merchantRowId, $data)
      {
          $url = $this->getStoresNotificationURL($merchantRowId);

          if(!$url)
          {
              return false;
          }

          $data['merchant_id'] = $this->getMerchantId($merchantRowId);
          $data['apikey'] = $this->getAPIKey($this->appStores);
          $data['entity'] = 'basic';

          $response = $this->makeRequestString($data);

          log_api_message('Sending Category Notification', $data['apikey'], 'Merchant ID#' . $merchantRowId);
          $this->postMessage($url, $response);
      }

      #-------------------------------#
      # Wishlist Functions            #
      #-------------------------------#
      function sendWishListNotification($data, $url, $merchant_row_id)
      {
          $response = $this->makeRequestString($data);
          if(!$response)
          {
              log_api_message('Notification on Wish List URL', 'sendWishListNotification', 'Notification text is missing');
          }
          else
          {
              $this->postMessage($url, $response);
          }
      }

      function notifyCrmOnAffiliate($merchantRowId, $affiliateRowId, $funnelId, $delete = 0)
      {
          if(!$funnelId)
            return false;

          $url = $this->config->item('nurl_crm_affiliate');

          if(!$url)
          {
              log_api_message('Notification on Affiliate', 'notifyCrmOnAffiliate', 'Notification URL is missing');
              return;
          }

          if($delete)
              $notification['delete']   = 1;

          //$notification['funnel_id'] = $funnelId;

          $notification['affiliate_id'] = $affiliateRowId;
          $notification['merchant_id'] = $this->getMerchantId($merchantRowId);

          $notification['apikey'] = $this->getAPIKey($this->appCRM);

          $response = $this->makeRequestString($notification);

          if(!$response)
          {
              log_api_message('Notification on Affiliate', 'notifyCrmOnAffiliate', 'Notification text is missing');
          }
          else
          {
              $this->postMessage($url, $response);
          }
      }

      function sendMerchantProfileNotification($merchantRowId)
      {
          $sql = "SELECT *FROM tbl_merchant WHERE merchant_row_id = " . $merchantRowId;
          $query = $this->db->query($sql);
          $data = $query->row_array();

          $data['new_package_id'] = $data['package_id'];
          $data['active_or_not']  = $data['active_status'];
          if($this->config->item('enable_crm_notification'))
          {
             log_api_message('Sending Notification', 'CRM', 'Merchant ID#' . $data['merchant_id']);
             $data['company_name'] = $data['show_company_name'] ? $data['company_name'] : '';
             $data['apikey'] = $this->getAPIKey($this->appCRM);
             $response = $this->makeRequestString($data);
             $this->postMessage($this->config->item('nurl_crm_package_change'), $response);
          }
          if($this->config->item('enable_member_pro_notification'))
          {
             log_api_message('Sending Notification', 'MPRO', 'Merchant ID#' . $data['merchant_id']);
             $data['apikey'] = $this->getAPIKey($this->appMembersPro);
             $response = $this->makeRequestString($data);
             $this->postMessage($this->config->item('nurl_members_pro_package_change'), $response);
          }
          if($this->config->item('enable_project_notification'))
          {                    
             log_api_message('Sending Notification', 'PM', 'Merchant ID#' . $data['merchant_id']);
             $data['entity'] = 'manage_account';
             $data['status'] = 'update';
             $data['apikey'] = $this->getAPIKey($this->appProject);
             $response = $this->makeRequestString($data);
             $this->postMessage($this->config->item('nurl_pm_add_update_staff'), $response);
          }
          /*
          if($this->config->item('enable_stores_notification'))
          {
             log_api_message('Sending Notification', 'STORE', 'Merchant ID#' . $data['merchant_id']);
             $data['apikey'] = $this->getAPIKey($this->appStores);
             $response = $this->makeRequestString($data);
             $this->postMessage($this->config->item('nurl_crm_package_change'), $response);
          }
          if($this->config->item('enable_project_notification'))
          {
             log_api_message('Sending Notification', 'PM', 'Merchant ID#' . $data['merchant_id']);
             $data['apikey'] = $this->getAPIKey($this->appProject);
             $response = $this->makeRequestString($data);
             $this->postMessage($this->config->item('nurl_project_package_change'), $response);
          }
          */
      }


      function sendStaffProfileNotification($merchantRowId, $action)
      {
      	  
      	  
          if($action == 'delete') {
            $data['merchant_row_id'] = $merchantRowId;
          } else {
              $sql = "SELECT *FROM tbl_merchant WHERE merchant_row_id = " . $merchantRowId;
              $query = $this->db->query($sql);
              $data = $query->row_array();
          }

          $data['entity'] = 'manage_account';
          $data['status'] = $action;

          $merchantRowId = getCurrentMerchantId();

          //die('I am in sendStaffProfileNotification: '.$merchantRowId);
          // Send to PM
          if($this->config->item('enable_project_notification'))
          {
             $data['apikey'] = $this->getAPIKey($this->appProject);
             $response = $this->makeRequestString($data);
             
             
             
              if(!$response) {
                    log_api_message('Notification on Manage Account To PM', 'sendNotificationOnAccountChange', 'Notification text is missing');
              }else {
              	
                    log_api_message('Sending Account Notification TO PM URL:', $this->config->item('nurl_pm_add_update_staff'), 'Merchant Row ID#' . $merchantRowId );
                    
                    $response_msg = $this->postMessage($this->config->item('nurl_pm_add_update_staff'), $response);
                    
                    //echo 'URL:'.$this->config->item('nurl_pm_add_update_staff').'<BR/>';
                    
                    ob_start();
                    
                    echo '<pre>';
                    print_r($response);
                    echo '</pre>';
                    
                    echo '<br/>Response Msg:'.$response_msg;
                    
                    $logdata = ob_get_contents();
                    ob_end_clean();
                    
                    $fp = fopen( 'logs/'.date('d-m-Y H:i').'_API.txt', 'w+' );
                    fwrite( $fp,  $logdata);
                    fclose( $fp );
              }
          }

      }

      function sendBookingNotificationToCRM($data)
      {
    
          if(!$this->config->item('enable_crm_notification'))
             return false;

          $url = $this->config->item('nurl_crm_booking');
          $data['apikey'] = $this->getAPIKey($this->appCRM);
          $requestString = $this->makeRequestString($data);

          if(!$requestString)
          {
            log_api_message('Notification on Customer Booking From Coach portal', 'sendNotificationOnBookingAdd', 'Notification text is missing');
          }
          else
          {
              log_api_message('Sending booking Info', $data['apikey'], 'Request_String# ' . $requestString);
              $this->postMessage($url, $requestString);
          }
		  return $this->response;
      }

      function coachJumpFromCrmToPortal($coach_row_id, $merchant_row_id, $randHashCoach)
      {
         $apiKey = $this->getAPIKey($this->appCRM);
         $data = array('apikey' => $apiKey,
                       'coachRowId' => $coach_row_id,
                       'merchantRowId' => $merchant_row_id,
                       'randHashCoach' => $randHashCoach);

         $url = $this->config->item('nurl_crm_coach_authenticate');
         $requestString = $this->makeRequestString($data);
         $this->postMessage($url, $requestString);
         return $this->response;
      }

  function staffLoginToCoreFromAnyModule($account_row_id, $merchant_row_id, $randHashCoach, $moduleId) {

      /* For Crm use module Counter,
        CRM: moduleId = 1
        Store: moduleId = 2
        Project Manager: moduleId = 3
        Live Chat: moduleId = 4
        Member Pro: moduleId = 5
       */

      switch($moduleId) {

        case 1:
            $apiKey = $this->getAPIKey($this->appCRM);
            $url = $this->config->item('nurl_crm_staff_authenticate');
            break;

        case 2:
            $apiKey = $this->getAPIKey($this->$appStores);
            break;

        case 3:
            $apiKey = $this->getAPIKey($this->appProject);
            break;

        case 4:
            $apiKey = $this->getAPIKey($this->$appLiveChat);
            break;
        default:
            $apiKey = $this->getAPIKey($this->appMembersPro);
            break;
      }

      $data = array('apikey' => $apiKey,
                       'accountRowId' => $account_row_id,
                       'merchantRowId' => $merchant_row_id,
                       'randHashCoach' => $randHashCoach);

     $requestString = $this->makeRequestString($data);
     $this->postMessage($url, $requestString);
     return $this->response;

   }
   
   function customerInfoToCRM($data)
   {
     $url = $this->config->item('nurl_crm_customer_add');
     $data['apikey'] = $this->getAPIKey($this->appCRM);
     $requestString = $this->makeRequestString($data);
     //dumpVar($requestString);
     $this->postMessage($url, $requestString);
     return $this->response;       
   }
}
?>