<?php
if (!defined('BASEPATH'))
  exit('No direct script access allowed');
/**
 * The global CI helpers 


 */
if (!function_exists('CI')) {

  function CI() {
    if (!function_exists('get_instance'))
      return FALSE;
    $CI = &get_instance();
    return $CI;
  }

}

if (!function_exists('getDateFormat')) {

  function getDateFormat($date, $format, $seperator1 = ",") {
    switch ($format) {
      case 1: // (Ymd)->(dmY) 06 Dec, 2010 
        $arr_date = explode($seperator1, $date);
        $arr_date = strtotime($arr_date[0]);
        $ret_date = date("d M" . $seperator1 . " Y", $arr_date);
        break;

      case 2: // (Ymd)->(dmY) 06 December, 2010
        $arr_date = explode($seperator1, $date);
        $arr_date = strtotime($arr_date[0]);
        $ret_date = date("d F" . $seperator1 . " Y", $arr_date);
        break;

      case 3: // (Ymd)->(dmY) Mon Dec 06, 2010 
        $arr_date = explode($seperator1, $date);
        $arr_date = strtotime($arr_date[0]);
        $ret_date = date("D M d" . $seperator1 . " Y", $arr_date);
        break;

      case 4: // (Ymd)->(dmY) Monday December 06, 2010 
        $arr_date = explode($seperator1, $date);
        $arr_date = strtotime($arr_date[0]);
        $ret_date = date("l F d" . $seperator1 . " Y", $arr_date);
        break;

      case 5: // (Ymd)->(dmY) Monday December 06, 2010, 03:04:00 
        $arr_time1 = explode(" ", $date);
        $arr_date = strtotime($date);
        $ret_date = date("l F d" . $seperator1 . " Y" . $seperator1 . " h:i:s", $arr_date);
        break;

      case 6: // (Ymd)->(dmY) Monday December 06, 2010, 15:03:PM 
        $arr_time1 = explode(" ", $date);
        $arr_date = strtotime($date);
        $ret_date = date("l F d" . $seperator1 . " Y" . $seperator1 . " H:i:A", $arr_date);
        break;

      case 7: // (Ymd)->(dmY) Monday December 06, 2010, 15:03:PM 
        $arr_time1 = explode(" ", $date);
        $arr_date = strtotime($date);
        $ret_date = date("d M" . $seperator1 . " Y" . $seperator1 . " H:i:A", $arr_date);
        break;

      case 8: // (Ymd)->(dmY) Monday December 06, 2010, 03:04:00 
        $arr_time1 = explode(" ", $date);
        $arr_date = strtotime($date);
        $ret_date = date("d M" . $seperator1 . " Y" . $seperator1 . " h:i", $arr_date);
        break;
      case 9: // (Ymd)->(dmY) Monday December 06, 2010 
        $arr_date = explode($seperator1, $date);
        $arr_date = strtotime($arr_date[0]);
        $ret_date = date("M d" . $seperator1 . " Y", $arr_date);
        break;
      case 10: // (Ymd)->(dmY) Monday December 06, 2010 
        $arr_date = explode($seperator1, $date);
        $arr_date = strtotime($arr_date[0]);
        $ret_date = date("M d" . $seperator1 . " Y [l]", $arr_date);
        break;
      case 11: // (Ymd)->(dmY) Monday December 06, 2010 
        $arr_date = explode($seperator1, $date);
        $arr_date = strtotime($arr_date[0]);
        $ret_date = date("d-M-Y", $arr_date);
        break;
    }
    return $ret_date;
  }

}


if (!function_exists('humanTiming')) {

  function humanTiming($time) {
    $CI = CI();
    $p = "";
    $currtent_time = strtotime($CI->config->item('date_time_format'));
    $diff = (int) abs($currtent_time - $time);
    $tokens = array(
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    foreach ($tokens as $unit => $text) {
      if ($diff < $unit)
        continue;
      $numberOfUnits = round($diff / $unit);
      return $p = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
    }
    return ($p == '' ? '1 seconds' : $p);
  }

}


/* * **********************************************************
  1.Convert Nested Array to Single Array
  2.If $key is not empty then key will be preserved but
  value will be overwrite if occur more than once

 * ********************************************************** */

if (!function_exists('array_flatten')) {

  function array_flatten($array, $return, $key = '') {
    if (is_array($array)) {
      foreach ($array as $ky => $val) {
        $key = ($key !== '' ? $ky : '');

        $return = array_flatten($val, $return, $key);
      }
    } else {
      if ($key != '') {
        $return[$key] = $array;
      } else {
        $return[] = $array;
      }
    }
    return $return;
  }

}

/*
  find one array
  $arr1 =  array('0'=>'1','1'=>'2')
  $arr2 =  = array('1' =>'Boarding Job','2' =>'Night Job','3'=>'Daily Job');
  $result ==> Boarding Job,Night Job
 */

function getArrayValueBykey($arr1, $arr2) {
  $res = array();
  if (is_array($arr1) && is_array($arr2)) {
    foreach ($arr1 as $key => $val) {
      if ($val != "") {
        $res[] = $arr2[$val];
      }
    }
  }
  return $res;
}

if (!function_exists('getAge')) {

  function getAge($dob) {
    $age = 31536000;  //days secon 86400X365
    $birth = strtotime($dob); // Start as time
    $current = strtotime(date('Y')); // End as time
    if ($current > $birth) {
      $finalAge = round(($current - $birth) / $age) + 1;
    }
    return $finalAge;
  }

}



//$in_string = " hi  this dkmphp  net india  wenlink india  development fun company php delhi";
//$spam_word_arr = array('php','net','fun');
if (!function_exists('check_spam_words')) {

  function check_spam_words($spam_word_arr, $in_string) {
    $is_spam_found = false;
    if (is_array($spam_word_arr) && $in_string != "") {
      foreach ($spam_word_arr as $val) {
        if (preg_match("/\b$val\b/i", $in_string)) {
          $is_spam_found = true;
          break;
        }
      }
    }
    return $is_spam_found;
  }

}

if (!function_exists('file_ext')) {

  function file_ext($file) {
    $file_ext = strtolower(strrchr($file, '.'));
    $file_ext = substr($file_ext, 1);
    return $file_ext;
  }

}


if (!function_exists('applyFilter')) {

  function applyFilter($type, $val) {
    switch ($type) {
      case 'NUMERIC_GT_ZERO':
        $val = preg_replace("~^0*~", "", trim($val));
        return preg_match("~^[1-9][0-9]*$~i", $val) ? $val : 0;
        break;
      case 'NUMERIC_WT_ZERO':
        return preg_match("~^[0-9]*$~i", trim($val)) ? $val : -1;
        break;
    }
  }

}

if (!function_exists('removeImage')) {

  function removeImage($cfgs) {
    if ($cfgs['source_dir'] != '' && $cfgs['source_file'] != '') {
      $pathImage = UPLOAD_DIR . "/" . $cfgs['source_dir'] . "/" . $cfgs['source_file'];
      if (file_exists($pathImage)) {
        unlink($pathImage);
      }
    }
  }

}


if (!function_exists('trace')) {

  function trace() {
    list($callee) = debug_backtrace();
    $arguments = func_get_args();
    $total_arguments = count($arguments);
    echo '<fieldset style="background: #fefefe !important; border:3px red solid; padding:5px; font-family:Courier New,Courier, monospace;font-size:12px">';
    echo '<legend style="background:lightgrey; padding:6px;">' . $callee['file'] . ' @ line: ' . $callee['line'] . '</legend><pre>';
    $i = 0;
    foreach ($arguments as $argument) {
      echo '<br/><strong>Debug #' . ( ++$i) . ' of ' . $total_arguments . '</strong>: ';
      if ((is_array($argument) || is_object($argument)) && count($argument)) {
        print_r($argument);
      } else {
        var_dump($argument);
      }
    }
    echo '</pre>' . PHP_EOL;
    echo '</fieldset>' . PHP_EOL;
  }

}

if (!function_exists('find_paging_segment')) {

  function find_paging_segment($debug = FALSE) {
    $ci = CI();
    $segment_array = $ci->uri->segments;
    if ($debug) {
      trace($ci->uri->segments);
    }
    $key = array_search('pg', $segment_array);
    return $key + 1;
  }

}


if (!function_exists('make_missing_folder')) {

  function make_missing_folder($dir_to_create = "") {
    if (empty($dir_to_create))
      return;
    $dir_path = UPLOAD_DIR;
    $subdirs = explode("/", $dir_to_create);
    foreach ($subdirs as $dir) {
      if ($dir != "") {
        $dir_path = $dir_path . "/" . $dir;
        if (!file_exists($dir_path)) {
//echo $dir_path;
          mkdir($dir_path, 0755);
        } else {
          chmod($dir_path, 0755);
        }
      }
    }
  }

}

if (!function_exists('char_limiter')) {

  function char_limiter($str, $len, $suffix = '...') {
    $str = strip_tags($str);
    if (strlen($str) > $len) {
      $str = substr($str, 0, $len) . $suffix;
    }
    return $str;
  }

}

if (!function_exists('redirect_top')) {

  function redirect_top($url = '') {
    if (!strpos($url, 'ttp://') && !strpos($url, 'ttps://'))
      $url = base_url() . $url;
    if ($url == ''):
      ?>
      <script>
        top.$.fancybox.close();
        window.top.location.reload();
      </script>
      <?php
    else:
      ?>
      <script>
        top.$.fancybox.close();
        window.top.location.href = "<?php echo $url ?>";
      </script>
    <?php
    endif;
    exit;
  }

}


if (!function_exists('confirm_js_box')) {

  function confirm_js_box($txt = 'remove') {
    $var = "onclick=\"return confirm('Are you sure you want to $txt this record');\" ";
    return $var;
  }

}


if (!function_exists('make_select_box')) {

  function make_select_box($varg = array(), $result = array()) {
    $ci = CI();
    $var = "";
    $varg['default_text'] = !array_key_exists('default_text', $varg) ? "Select" : $varg['default_text'];
    $varg['id'] = !array_key_exists('id', $varg) ? $varg['name'] : $varg['id'];
    $opt_val_fld = !array_key_exists('opt_val_fld', $varg) ? $varg['opt_val_fld'] : 'key';
    $opt_txt_fld = !array_key_exists('opt_txt_fld', $varg) ? $varg['opt_txt_fld'] : 'value';
    $is_associative_array = !array_key_exists('associative', $varg) ? FALSE : $varg['associative'];
    $var .= '<select name="' . $varg['name'] . '" id="' . $varg['id'] . '" ' . $varg['format'] . '>';
    if ($varg['default_text'] != "") {
      $var .= '<option value="" selected="selected">' . $varg['default_text'] . '</option>';
    }
    foreach ($result as $key => $val) {
      if (is_array($val) && !empty($val)) {
        if (is_array($varg['current_selected_val'])) {
          $select_element = in_array($val[$opt_val_fld], $varg['current_selected_val']) ? "selected" : "";
        } else {
          $select_element = ( $varg['current_selected_val'] == $val[$opt_val_fld] ) ? "selected" : "";
        }
        $var .= '<option value="' . $val[$opt_val_fld] . '" ' . $select_element . '>' . ucfirst($val[$opt_txt_fld]) . '</option>';
      } else {
        $opt_val_fld = $opt_val_fld === 'key' ? $key : $val;
        $opt_txt_fld = $opt_txt_fld === 'key' ? $key : $val;
        if (is_array($varg['current_selected_val'])) {
          $select_element = in_array($opt_val_fld, $varg['current_selected_val']) ? "selected" : "";
        } else {
          $select_element = ( $varg['current_selected_val'] == $opt_val_fld ) ? "selected" : "";
        }
        $var .= '<option value="' . $opt_val_fld . '" ' . $select_element . '>' . $opt_txt_fld . '</option>';
      }
    }
    $var .= '</select>';
    return $var;
  }

}

function CountrySelectBox($varg = array()) {
  $CI = CI();
  $var = "";
  /*   * ********************************************************
    default_text 		=>Default Option Text
    name 		=> 			Dropdn name
    id 		=> 			Dropdn id (default to name)
    format      		=>	all extra attributes for the dpdn(style,class,event...)
    opt_val_fld     =>      DpDn option value field to be fetched from database
    opt_txt_fld     =>      DpDn option text field to be fetched from database

   * ********************************************************* */
  $varg['default_text'] = !array_key_exists('default_text', $varg) ? "Select Country" : $varg['default_text'];
  $varg['id'] = !array_key_exists('id', $varg) ? $varg['name'] : $varg['id'];
  $opt_val_fld = !array_key_exists('opt_val_fld', $varg) ? "name" : $varg['opt_val_fld'];
  $opt_txt_fld = !array_key_exists('opt_txt_fld', $varg) ? "name" : $varg['opt_txt_fld'];
  $var .= '<select name="' . $varg['name'] . '" id="' . $varg['id'] . '" ' . $varg['format'] . '>';
  if ($varg['default_text'] != "") {
    $var .= '<option value="" selected="selected">' . $varg['default_text'] . '</option>';
  }
  $contry_res = $CI->db->query("SELECT * FROM wps_countries_list WHERE 1")->result_array();
  foreach ($contry_res as $key => $val) {
    if (is_array($varg['current_selected_val'])) {
      $select_element = in_array($val[$opt_val_fld], $varg['current_selected_val']) ? "selected" : "";
    } else {
      $select_element = ( $varg['current_selected_val'] == $val[$opt_val_fld] ) ? "selected" : "";
    }
    $var .= '<option value="' . $val[$opt_val_fld] . '" ' . $select_element . '>' . ucfirst($val[$opt_txt_fld]) . '</option>';
  }
  $var .= '</select>';
  return $var;
}

if (!function_exists('city_options')) {

  function city_options($data_type = "", $selected_val = "") {
    $CI = CI();
    $qryStr = "";
    if ($data_type == "collection")
      $qryStr = "AND is_data_collection = '1'";
    if ($data_type == "operational")
      $qryStr = "AND is_data_available = '1'";
    $city_res = $CI->db->query("SELECT * FROM wps_city WHERE 1 " . $qryStr)->result_array();
//echo_sql();
    $var = "";
    foreach ($city_res as $key => $val) {
      $sel = ($val['id'] == $selected_val) ? 'selected' : '';
      $var .= '<option value="' . $val['id'] . '" ' . $sel . '>' . ucfirst($val['title']) . '</option>';
    }
//echo $var; die;
    return $var;
  }

}


if (!function_exists('get_content')) {

  function get_content($tbl = "wps_auto_respond_mails", $pageId) {
    $CI = CI();
    if ($pageId > 0) {
      $res = $CI->db->get_where($tbl, array('id' => $pageId))->row();
      if (is_object($res)) {
        return $res;
      }
    }
  }

}


if (!function_exists('get_site_email')) {

  function get_site_email() {
    $CI = CI();
    $CI->db->select('*');
    $CI->db->from('wps_admin');
    $CI->db->where('admin_id', '1');
    $query = $CI->db->get();
    if ($query->num_rows() > 0)
      return $query->row();
  }

}


if (!function_exists('category_link')) {

  function category_link($parent) {
    $ci = CI();
    $record_count = 0;
    $p = $ci->db->query("SELECT * FROM  wps_categories WHERE parent_id='$parent' and status='1'");
    $rsrow = $p->num_rows();
    if ($rsrow > 0) {
      $link_url = base_url() . "category/index/" . $parent;
    } else {
      $link_url = base_url() . "products/index/" . $parent;
    }
    return $link_url;
  }

}

function timeDiff($firstTime, $lastTime) {
  $time = $lastTime;
// convert to unix timestamps
  $firstTime = strtotime($firstTime);
  $lastTime = strtotime($lastTime);
  $rt = "";
// perform subtraction to get the difference (in seconds) between times
  $timeDiff = $firstTime - $lastTime;
// return the difference
  if ($timeDiff > 60) {
    if ($timeDiff > 60 && $timeDiff < 1440) {
      $timeDiff = $timeDiff / 60;
      $rt = ceil($timeDiff) . ' minutes ago';
    } elseif ($timeDiff > 1440 && $timeDiff < 86400) {
      $timeDiff = $timeDiff / (60 * 60);
      $rt = 'about ' . ceil($timeDiff) . ' hours ago';
    } elseif ($timeDiff > 86400 && $timeDiff < 172800) {
      $timeDiff = $timeDiff / (60 * 60 * 2);
      $tm = explode(' ', $time);
      $rt = "yesterday"; // at " . $tm[1];
    } else {
      $timeDiff = $timeDiff / (24 * 60 * 60);
      $rt = ceil($timeDiff) . " days ago";
    }
  } else {
    $rt = $timeDiff . " seconds ago";
  }
  return $rt;
}

if (!function_exists('my_array_column')) {

  function my_array_column(array $input, $columnKey, $indexKey = null) {
    $array = array();
    foreach ($input as $value) {
      if (!isset($value[$columnKey])) {
        trigger_error("Key \"$columnKey\" does not exist in array");
        return false;
      }
      if (is_null($indexKey)) {
        $array[] = $value[$columnKey];
      } else {
        if (!isset($value[$indexKey])) {
          trigger_error("Key \"$indexKey\" does not exist in array");
          return false;
        }
        if (!is_scalar($value[$indexKey])) {
          trigger_error("Key \"$indexKey\" does not contain scalar value");
          return false;
        }
        $array[$value[$indexKey]] = $value[$columnKey];
      }
    }
    return $array;
  }

}

//Find Product ID in Coupon Session Array
function findKey($array, $keySearch) { // check whether input is an array
  if (is_array($array)) {
    foreach ($array as $key => $item) {
      if (isset($item[$keySearch]) || findKey($item, $keySearch) === true) {
        return $key;
      }
    }
  }
}

//encryption
function encrypt($plainText, $key) {
  $secretKey = hextobin(md5($key));
  $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
  $openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
  $blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
  $plainPad = pkcs5_pad($plainText, $blockSize);
  if (mcrypt_generic_init($openMode, $secretKey, $initVector) != -1) {
    $encryptedText = mcrypt_generic($openMode, $plainPad);
    mcrypt_generic_deinit($openMode);
  }
  return bin2hex($encryptedText);
}

function decrypt($encryptedText, $key) {
  $secretKey = hextobin(md5($key));
  $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
  $encryptedText = hextobin($encryptedText);
  $openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
  mcrypt_generic_init($openMode, $secretKey, $initVector);
  $decryptedText = mdecrypt_generic($openMode, $encryptedText);
  $decryptedText = rtrim($decryptedText, "\0");
  mcrypt_generic_deinit($openMode);
  return $decryptedText;
}

//*********** Padding Function *********************
function pkcs5_pad($plainText, $blockSize) {
  $pad = $blockSize - (strlen($plainText) % $blockSize);
  return $plainText . str_repeat(chr($pad), $pad);
}

//********** Hexadecimal to Binary function for php 4.0 version ********
function hextobin($hexString) {
  $length = strlen($hexString);
  $binString = "";
  $count = 0;
  while ($count < $length) {
    $subString = substr($hexString, $count, 2);
    $packedString = pack("H*", $subString);
    if ($count == 0) {
      $binString = $packedString;
    } else {
      $binString .= $packedString;
    }

    $count += 2;
  }
  return $binString;
}

function clear_cache() {
  $path = UPLOAD_DIR . '/thumb-cache';
  $dir_handle = @opendir($path) or die("Unable to open folder");
  while (false !== ($file = readdir($dir_handle))) {
    if ($file != '.' && $file != '..') {
      unlink($path . '/' . $file);
    }
  }
  closedir($dir_handle);
}

function addMultiplePhotos($filesName, $destinationFolder) {
  $ci = CI();
  $fileName = $result = array();
//trace($_FILES[$filesName]);
  $cpt = count($_FILES[$filesName]['name']);
  if ($cpt <= 10) {
    $number_of_files = sizeof($_FILES[$filesName]['tmp_name']);
    $files = $_FILES[$filesName];
    $errors = array();

    for ($i = 0; $i < $number_of_files; $i++) {
      if ($_FILES[$filesName]['error'][$i] != 0)
        $errors[$i][] = 'Couldn\'t upload file ' . $_FILES[$filesName]['name'][$i];
    }
    if (sizeof($errors) == 0) {
      $ci->load->library('upload');
      for ($i = 0; $i < $number_of_files; $i++) {
        $_FILES['uploadedimage']['name'] = time() . $i . $files['name'][$i];
        $_FILES['uploadedimage']['type'] = $files['type'][$i];
        $_FILES['uploadedimage']['tmp_name'] = $files['tmp_name'][$i];
        $_FILES['uploadedimage']['error'] = $files['error'][$i];
        $_FILES['uploadedimage']['size'] = $files['size'][$i];
        $uploaded_data = $ci->upload->my_upload('uploadedimage', $destinationFolder);
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $fileName[] = $uploaded_data['upload_data']['file_name'];
        }
      }
      $fname = implode(",", $fileName);
      $result['files'] = $fname;
      $result['success'] = 'true';
    } else {
      $result['error'] = $errors;
      $result['success'] = 'false';
    }
  }
  return $result;
}

//Send SMS
function sendSms($mobilenos, $message) {
  $payload = file_get_contents('http://sms.webpulseindia.com/index.php/smsapi/httpapi/?uname=webpulseindia&password=webpulse@sk&sender=WPSIND&receiver=' . $mobilenos . '&route=TA&msgtype=1&sms=' . urlencode($message));
//echo $payload;
}

//Verify SMS
function verifySms($mobile, $otp) {
  $ci = CI();
  $cnt = count_record("wps_otp", "mobile_number = '" . $mobile . "' AND otp = '" . $otp . "' AND status = '0'");
  if ($cnt > 0) {
    $ci->db->query("UPDATE wps_otp SET status = '1' WHERE mobile_number = '" . $mobile . "' AND otp = '" . $otp . "'");
    echo '1';
  } else {
    echo 0;
  }
}

//Send Email to Admin
function sendAdminEnquiryEmail($subject = 'New Enquiry Received from naturaltherapyindia.com', $emailIds = array(), $dets = array(), $type = 'product') {
  $ci = CI();
  $ci->load->library('Dmailer');
  $admin = get_site_email();
  $content = get_content('wps_auto_respond_mails', '9');
  $subject = $content->email_subject;
  $body = $content->email_content;
  $product = array();
  if (isset($dets['productID'])) {
    $product = get_db_single_row('wps_products', 'product_name, unit_measurement', "products_id = '" . $dets['productID'] . "'");
    if ($type == 'category') {
      $product = get_db_single_row('wps_company_categories', 'category_name as product_name', "category_id = '" . $dets['productID'] . "'");
    }
  }
  $messurement = $ci->config->item('unit_measurement');

  $body = str_replace('{email}', $dets['emailAddress'], $body);
  $body = str_replace('{name}', $dets['fullName'], $body);
  $body = str_replace('{mobile}', $dets['mobileNumber'], $body);
  $body = str_replace('{message}', $dets['enquiryMessage'], $body);
  if (!empty($dets['productQuantity'])) {
    if ($type == 'category' || !isset($dets['productID'])) {
      $body = str_replace('{qty}', $dets['productQuantity'], $body);
    } else {
      $body = str_replace('{qty}', $dets['productQuantity'] . ' / ' . $messurement[$product['unit_measurement']], $body);
    }
  } else {
    $body = str_replace('{qty}', 'N.A', $body);
  }
  $body = str_replace('{pname}', (isset($product['product_name'])) ? $product['product_name'] : '', $body);
  $body = str_replace('{purl}', $dets['post_url'], $body);
  $body = str_replace('{admin_email}', $admin->admin_email, $body);
  $body = str_replace('{site_name}', $ci->config->item('site_name'), $body);
  $body = str_replace('{url}', base_url(), $body);

  foreach ($emailIds as $toEmail) {
    $mail_conf = array(
        'subject' => $subject,
        'to_email' => $toEmail,
        'from_email' => 'support@webpulse.co',
        'from_name' => 'naturaltherapyindia.com',
        'body_part' => $body
    );
//trace($mail_conf);
    $ci->dmailer->mail_notify($mail_conf);
  }
}

//Send Email to Admin
function sendCompEnquiryEmail($subject = 'New Enquiry Received from naturaltherapyindia.com', $emailIds = array(), $dets = array(), $type = 'product') {
  $ci = CI();
  $ci->load->library('Dmailer');
  $admin = get_site_email();
  //$content = get_content('wps_auto_respond_mails', '10');
  $content = file_get_contents(site_url() . 'mailer/enquiry-received.html');
  $subject = 'New Enquiry Received!';
  $body = $content;

  if($dets['productID']>0){
    $product = get_db_single_row('wps_products', 'product_name, unit_measurement', "products_id = '" . $dets['productID'] . "'");
    if ($type == 'category') {
      $product = get_db_single_row('wps_company_categories', 'category_name as product_name', "products_id = '" . $dets['productID'] . "'");
    }
    $product_name=$product['product_name'];
  }else{
    $product_name='';
  }

  $messurement = $ci->config->item('unit_measurement');

  $body = str_replace('{email}', $dets['emailAddress'], $body);
  $body = str_replace('{name}', $dets['fullName'], $body);
  $body = str_replace('{mobile}', $dets['mobileNumber'], $body);
  $body = str_replace('{message}', $dets['enquiryMessage'], $body);

    if($dets['productQuantity']>0){
      if ($type == 'category') {
          $body = str_replace('{qty}', $dets['productQuantity'], $body);
      } else {
          $body = str_replace('{qty}', $dets['productQuantity'] . ' / ' . $messurement[$product['unit_measurement']], $body);
      }
    }else{
      $body = str_replace('{qty}', '', $body);
    }

    if($product_name!=""){
      $body = str_replace('{pname}', $product_name, $body);
    }else{
      $body = str_replace('{pname}', '', $body);
    }
    
  $body = str_replace('{purl}', $dets['post_url'], $body);
  $body = str_replace('{admin_email}', $admin->admin_email, $body);
  $body = str_replace('{site_name}', $ci->config->item('site_name'), $body);
  $body = str_replace('{url}', base_url(), $body);

  foreach ($emailIds as $toEmail) {
    $mail_conf = array(
        'subject' => $subject,
        'to_email' => $toEmail,
        'from_email' => 'support@webpulse.co',
        'from_name' => 'naturaltherapyindia.com',
        'body_part' => $body
    );
//trace($mail_conf);
    $ci->dmailer->mail_notify($mail_conf);
  }
}

//Send Email to User
function sendUserEnquiryEmail($subject = 'Enquiry Received with Thanks @ naturaltherapyindia.com', $emailId, $dets = array(), $type = 'product') {
  $ci = CI();
  $ci->load->library('Dmailer');
  $admin = get_site_email();
  $content = get_content('wps_auto_respond_mails', '8');
  $subject = $content->email_subject;
  $body = $content->email_content;
  $product = array();
  if (!empty($dets['productID'])) {
    $product = get_db_single_row('wps_products', 'product_name, unit_measurement', "products_id = '" . $dets['productID'] . "'");
  }
  $messurement = $ci->config->item('unit_measurement');

  $body = str_replace('{email}', $dets['emailAddress'], $body);
  $body = str_replace('{name}', $dets['fullName'], $body);
  $body = str_replace('{mobile}', $dets['mobileNumber'], $body);
  $body = str_replace('{message}', $dets['enquiryMessage'], $body);
  if (!empty($dets['productQuantity'])) {
    if ($type == 'product' && !empty($dets['productID'])) {
      $body = str_replace('{qty}', $dets['productQuantity'] . ' / ' . $messurement[$product['unit_measurement']], $body);
    } else {
      $body = str_replace('{qty}', $dets['productQuantity'], $body);
    }
  } else {
    $body = str_replace('{qty}', 'N.A', $body);
  }
  $body = str_replace('{pname}', (!empty($dets['productID'])) ? $product['product_name'] : '', $body);
  $body = str_replace('{purl}', $dets['post_url'], $body);
  $body = str_replace('{admin_email}', $admin->admin_email, $body);
  $body = str_replace('{site_name}', $ci->config->item('site_name'), $body);
  $body = str_replace('{url}', base_url(), $body);

  $mail_conf = array(
      'subject' => $subject,
      'to_email' => $emailId,
      'from_email' => 'support@webpulse.co',
      'from_name' => 'naturaltherapyindia.com',
      'body_part' => $body
  );
  //trace($mail_conf);
  $ci->dmailer->mail_notify($mail_conf);
}

function create_time_range($start, $end, $interval = '30 mins', $format = '12') {
  $startTime = strtotime($start);
  $endTime = strtotime($end);
  $returnTimeFormat = ($format == '12') ? 'g:i:s ' : 'G:i:s';

  $current = time();
  $addTime = strtotime('+' . $interval, $current);
  $diff = $addTime - $current;

  $times = array();
  while ($startTime < $endTime) {
    $times[] = date($returnTimeFormat, $startTime);
    $startTime += $diff;
  }
  $times[] = date($returnTimeFormat, $startTime);
  return $times;
}

function createTemplateUrls($v) {
  $ci = CI();
  $compName = get_db_field_value('wps_customers', 'company_name', "WHERE customers_id = '" . $v . "'");
  $currentUrl = get_db_field_value('wps_customers', 'website_url', "WHERE customers_id = '" . $v . "'");
  $pageUrl = seo_url_title($compName);
  $actualUrl = ($currentUrl) ? $currentUrl : $pageUrl;

  $countCompUrl = count_record("wps_meta_tags", "entity_id = '" . $v . "' AND is_fixed = 'C' AND entity_type = 'wpstemplate'");
  if ($countCompUrl == 0) {

    //$ci->db->query("INSERT INTO wps_meta_tags SET entity_id = '" . $v . "', is_fixed = 'C', entity_type = 'wpstemplate', page_url = '" . $pageUrl . "', meta_title = '" . $compName . "  By getmanufacturers.com', meta_description = '" . $compName . "', meta_keyword = '" . $compName . "'");
      $sqls = "insert into wps_meta_tags (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqls,array($v, 'C', 'wpstemplate',$pageUrl,$compName,$compName,$compName));

    //inset infor company meta tags table
    //about
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '" . $v . "', is_fixed = 'N', entity_type = 'wpstemplate/about', page_url = '" . $pageUrl . "/about-us', meta_title = 'About - " . $compName . "', meta_description = 'About Us', meta_keyword = 'About Us'");
     $sqlABout = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlABout,array($v, 'N', 'wpstemplate/about',$pageUrl.'/about-us','About - '.$compName,'About Us - '.$compName,'About Us - '.$compName));

    //contact
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '" . $v . "', is_fixed = 'N', entity_type = 'wpstemplate/contactus', page_url = '" . $pageUrl . "/contact-us', meta_title = 'Contact Us', meta_description = 'Contact Us - " . $compName . "', meta_keyword = 'Contact Us - " . $compName . "'");
    $sqlContact = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlContact,array($v, 'N', 'wpstemplate/contactus',$pageUrl.'/contact-us','Contact Us - '.$compName,'Contact Us - '.$compName,'Contact Us - '.$compName));

    //blog
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '" . $v . "', is_fixed = 'N', entity_type = 'wpstemplate/blogs', page_url = '" . $pageUrl . "/blogs', meta_title = 'Blogs - " . $compName . "', meta_description = 'Blogs - " . $compName . "', meta_keyword = 'Blogs - " . $compName . "'");
      $sqlBlog = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlBlog,array($v, 'N', 'wpstemplate/blogs',$pageUrl.'/blogs','Blogs - '.$compName,'Blogs - '.$compName,'Blogs - '.$compName));

    //our client
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '" . $v . "', is_fixed = 'N', entity_type = 'wpstemplate/clients', page_url = '" . $pageUrl . "/clients', meta_title = 'Clients - " . $compName . "', meta_description = 'Clients - " . $compName . "', meta_keyword = 'Clients - " . $compName . "'");
    $sqlClient = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlClient,array($v, 'N', 'wpstemplate/clients',$pageUrl.'/clients','Clients - '.$compName,'Clients - '.$compName,'Clients - '.$compName));

    //career
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '" . $v . "', is_fixed = 'N', entity_type = 'wpstemplate/career', page_url = '" . $pageUrl . "/career', meta_title = 'Career - " . $compName . "', meta_description = 'Career - " . $compName . "', meta_keyword = 'Career - " . $compName . "'");
      $sqlCareer = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlCareer,array($v, 'N', 'wpstemplate/career',$pageUrl.'/career','Career - '.$compName,'Career - '.$compName,'Career - '.$compName));

    //photo gallery
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '" . $v . "', is_fixed = 'N', entity_type = 'wpstemplate/photo', page_url = '" . $pageUrl . "/career', meta_title = 'Photo Gallery - " . $compName . "', meta_description = 'Photo Gallery - " . $compName . "', meta_keyword = 'Photo Gallery - " . $compName . "'");
      $sqlPHOTOGAl = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlPHOTOGAl,array($v, 'N', 'wpstemplate/photo',$pageUrl.'/photo','Photo Gallery - '.$compName,'Photo Gallery - '.$compName,'Photo Gallery - '.$compName));

    //Video Gallery
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '" . $v . "', is_fixed = 'N', entity_type = 'wpstemplate/video', page_url = '" . $pageUrl . "/video', meta_title = 'Video Gallery - " . $compName . "', meta_description = 'Video Gallery - " . $compName . "', meta_keyword = 'Video Gallery - " . $compName . "'");
      $sqlVideoGAl = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlVideoGAl,array($v, 'N', 'wpstemplate/video',$pageUrl.'/video','Video Gallery - '.$compName,'Video Gallery - '.$compName,'Video Gallery - '.$compName));

    //our products
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '0', is_fixed = 'N', entity_type = 'wpstemplate/category', page_url = '" . $pageUrl . "/product-listing', meta_title = 'Our Products - " . $compName . "', meta_description = 'Our Products - " . $compName . "',meta_keyword = 'Our Products - " . $compName . "'");
     $sqlProducts = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlProducts,array('0', 'N', 'wpstemplate/category',$pageUrl.'/product-listing','Our Products - '.$compName,'Our Products - '.$compName,'Our Products - '.$compName));

     //our services
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '0', is_fixed = 'N', entity_type = 'wpstemplate/category', page_url = '" . $pageUrl . "/service-listing', meta_title = 'Our Services - " . $compName . "', meta_description = 'Our Services - " . $compName . "',meta_keyword = 'Our Services - " . $compName . "'");
     $sqlServices = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlServices,array('0', 'N', 'wpstemplate/category',$pageUrl.'/service-listing','Our Services - '.$compName,'Our Services - '.$compName,'Our Services - '.$compName));

    //Search Page
    //$ci->db->query("INSERT INTO wps_meta_tags_company SET entity_id = '" . $v . "', is_fixed = 'N', entity_type = 'wpstemplate/category/search', page_url = '" . $pageUrl . "/search', meta_title = 'Search Result - " . $compName . "', meta_description = 'Search Result - " . $compName . "', meta_keyword = 'Search Result - " . $compName . "'");
      $sqlSearch = "insert into wps_meta_tags_company (entity_id, is_fixed, entity_type,page_url,meta_title,meta_description,meta_keyword)
        values (?, ?, ?, ?, ?, ?, ?)";
     $ci->db->query($sqlSearch,array($v, 'N', 'wpstemplate/category/search',$pageUrl.'/search','Search Result - '.$compName,'Search Result - '.$compName,'Search Result - '.$compName));
  } else {
    $ci->db->query("UPDATE wps_meta_tags SET page_url = '" . $actualUrl . "' WHERE entity_id = '" . $v . "' AND is_fixed = 'C' AND entity_type = 'wpstemplate'");

    //Update Company URLs to run company URLs
    $countListCompUrl = count_record("wps_meta_tags_company", "companyId = '" . $v . "' AND is_fixed = 'N'");
    if ($countListCompUrl > 0 && $currentUrl != $actualUrl) {
      $urlList = $ci->db->query("SELECT meta_id, page_url FROM wps_meta_tags_company WHERE companyId = '" . $v . "'")->result_array();
      foreach ($urlList as $uVal) {
        $new_page_url = str_replace($currentUrl . '/', $actualUrl . '/', $uVal['page_url']);
        $ci->db->query("UPDATE wps_meta_tags_company SET page_url = '" . $new_page_url . "' WHERE meta_id = '" . $uVal['meta_id'] . "'");
      }
    }
    //End Here
  }
}

function createTemplateUrlsComp($v) {
  $ci = CI();
  $actualUrl = get_db_field_value('wps_customers', 'website_url', "WHERE customers_id = '" . $v . "'");
  $pageUrl = seo_url_title($ci->input->post('website_url'));
  $countCompUrl = count_record("wps_meta_tags", "entity_id = '" . $v . "' AND is_fixed = 'C' AND entity_type = 'wpstemplate'");
  if ($countCompUrl == 0) {
    
  } else {
    $ci->db->query("UPDATE wps_customers SET website_url = '" . $pageUrl . "' WHERE customers_id = '" . $v . "'");
    //insert in url table
    $ci->db->query("INSERT INTO wps_company_website_urls SET website_url = '" . $pageUrl . "', customers_id = '" . $v . "'");
    $ci->db->query("UPDATE wps_meta_tags SET page_url = '" . $pageUrl . "' WHERE entity_id = '" . $v . "' AND is_fixed = 'C' AND entity_type = 'wpstemplate'");
    //Update Company URLs to run company URLs
    $countListCompUrl = count_record("wps_meta_tags_company", "companyId = '" . $v . "' AND is_fixed = 'N'");
    if ($countListCompUrl > 0 && $pageUrl != $actualUrl) {
      $urlList = $ci->db->query("SELECT meta_id, page_url FROM wps_meta_tags_company WHERE companyId = '" . $v . "'")->result_array();
      foreach ($urlList as $uVal) {
        $new_page_url = str_replace($actualUrl . '/', $pageUrl . '/', $uVal['page_url']);
        $ci->db->query("UPDATE wps_meta_tags_company SET page_url = '" . $new_page_url . "' WHERE meta_id = '" . $uVal['meta_id'] . "'");
      }
    }
    //End Here
  }
}

function comp_url() { //Company website URL
  $ci = CI();
  $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  $uri_segments = explode('/', $uri_path);
  $st = $uri_segments[1];
  return base_url() . $st . '/';
}

function comp_settings() { //Company website URL
  $ci = CI();
  $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  $uri_segments = explode('/', $uri_path);
  $st = $uri_segments[1];
  $compArray = array();
  $prevCompanyURL = $ci->db->query("SELECT customers_id, website_url FROM wps_company_website_urls WHERE website_url='" . $st . "'")->row_array();
  if (is_array($prevCompanyURL) && !empty($prevCompanyURL)) {
    $companyID = $prevCompanyURL['customers_id'];
    $compArray = $ci->db->query("SELECT * FROM wps_website_settings WHERE customers_id='" . $companyID . "'")->row_array();
  }
  return $compArray;
}

function comp_contact() { //Company website URL
  $ci = CI();
  $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  $uri_segments = explode('/', $uri_path);
  $st = $uri_segments[1];
  $compArray = array();
  $prevCompanyURL = $ci->db->query("SELECT customers_id, website_url FROM wps_company_website_urls WHERE website_url='" . $st . "'")->row_array();
  if (is_array($prevCompanyURL) && !empty($prevCompanyURL)) {
    $companyID = $prevCompanyURL['customers_id'];
    $compArray = $ci->db->query("SELECT * FROM wps_customers WHERE customers_id='" . $companyID . "'")->row_array();
  }
  return $compArray;
}

function comp_facts() { //Company website URL
  $ci = CI();
  $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  $uri_segments = explode('/', $uri_path);
  $st = $uri_segments[1];
  $compArray = array();
  $prevCompanyURL = $ci->db->query("SELECT customers_id, website_url FROM wps_company_website_urls WHERE website_url='" . $st . "'")->row_array();
  if (is_array($prevCompanyURL) && !empty($prevCompanyURL)) {
    $companyID = $prevCompanyURL['customers_id'];
    $compArray = $ci->db->query("SELECT * FROM wps_customers_factsheet WHERE customers_id='" . $companyID . "'")->row_array();
  }
  return $compArray;
}

function comp_clients() {
  $ci = CI();
  $compC = comp_contact();
  $compSettings = comp_settings();
  $locations = explode(',', @$compSettings['location_serve']);

  $clients = $ci->db->query("SELECT * FROM wps_clients WHERE status='1' AND companyId = '" . $compC['customers_id'] . "'")->result_array();
  $mid_catId = ''; //$this->meta_info['entity_id'];
  $current_urls=base_url().substr($_SERVER['REQUEST_URI'],1);
  ?>
  <!-- Home Testimonials -->
  <section class="home_testimonials_webpulse">
    <div class="container">
      <div class="row">
          <div class="col-lg-offset-2 col-lg-8">
              <div class="section-title text-center">
                  <h2 class="title fz-32">Tell Us What Are You Looking For ?</h2>
                  <p class="sub-title">We have made it easy for clients to reach us
                      and get their solutions weaved</p>
              </div>
              <div class="contact-form">
                  <form action="" method="post" id="middle_contactus_form">
                      <div class="alert alert-warning MidEmessageBox1" style="display: none;">
                        <span class="MidEmessage1"></span>
                      </div>
                      <div class="alert alert-success MidSmessageBox1" style="display: none;">
                        <span class="MidSmessage1"></span>
                      </div>
                      <div class="row">
                          <div class="col-lg-6 col-md-6">
                             <div class="form-group">
                              <input type="text" class="form-control" placeholder="Full Name *" id="mname" name="name" required>
                              </div>
                          </div>
                          <div class="col-lg-6 col-md-6">
                              <div class="form-group">
                              <input type="email" class="form-control" placeholder="Email ID*" id="memail" name="email" required>
                              </div>
                          </div>
                          <div class="col-lg-6 col-md-6">
                              <div class="form-group">
                              <input type="text" class="form-control" placeholder="Mobile Number *" id="mmobile" name="mobile" required>
                          </div>
                          </div>
                          
                          <div class="col-lg-6 col-md-6">
                              <div class="form-group">
                              <input type="text" class="form-control mlocation" placeholder="Location *" name="location" id="autocomplete" onfocus="geolocate()" value="" pattern="[a-z A-Z]+" autocomplete="off" required>
                          </div>
                          </div>
                          <div class="col-lg-12">
                              <div class="form-group">
                              <textarea name="message" id="mmessage"class="form-control" placeholder="Kindly Describe Your Requirement..."></textarea>
                          </div>
                          </div>
                          <div class="col-lg-12 text-center">
                              <input type="hidden" name="mid_productId" id="mid_proId" value="<?php echo $mid_catId; ?>" />
                              <input type="hidden" name="mid_productCompID" id="mid_compId" value="<?php echo $compC['customers_id']; ?>" />
                              <input type="hidden" name="mid_type" id="mid_typeId" value="category" />
                              <input type="hidden" name="mid_postedUrl" id="mid_postedUrl" value="<?php echo $current_urls; ?>" />
                              <button type="submit" class="home_submit_btn">Submit</button>
                          </div>
                      </div>
                  </form>
                  <p class="form-messege"></p>
              </div>
          </div>
        <!--<div class="col-lg-12 col-md-12  col-sm-12 wow fadeInRight animated" data-wow-delay=".5s">
          <div class="global">
            <h3>We Serve </h3>
            <p>
              <img class="global_image" src="<?php echo theme_url(); ?>designer/images/home/country-flags.png" alt="We Serve All Over India" >
              <?php echo nl2br(@$compSettings['about_serviceability']); ?>
            </p>
            <p>
              <?php
              foreach ($locations as $loc) {
                ?>
                <a href="javascript:void(0);" class="btn btn-info"><?php echo $loc; ?></a>
                <?php
              }
              ?>
            </p>
          </div>
        </div>-->
      </div>
    </div>
  </section>
  <?php
  if (is_array($clients) && !empty($clients)) {
    ?>
    <!-- Home Clients -->
    <section class="webpulse_home_clients">
      <div class="container">
        <div class="products_heading wow fadeInDown animated" data-wow-delay=".1s">
          <h1>Our Clients</h1>
          <div class="separator separatorss"><span><i></i></span></div>
        </div>
        <div class="clearfix"></div>	
        <div class="trade_partner"> 
          <?php
          $wd = 0.1;
          foreach ($clients as $cVal) {
            $wd = $wd + 0.1
            ?>
            <div class="item wow fadeInDown animated" data-wow-delay="<?php echo $wd; ?>s">
              <div class="clients">
                <div class="image">
                  <img src="<?php echo get_image('clients/clients', $cVal['client_logo'], '160', '100', 'R'); ?>" alt="<?php echo $cVal['client_name']; ?>">
                </div>
              </div>
            </div>
            <?php
          }
          ?>
        </div>
      </div>
    </section>	
    <?php
  }
}

function compressImage($source, $destination, $quality) {
  $info = getimagesize($source);
  if ($info['mime'] == 'image/jpeg')
    $image = imagecreatefromjpeg($source);
  elseif ($info['mime'] == 'image/gif')
    $image = imagecreatefromgif($source);
  elseif ($info['mime'] == 'image/png')
    $image = imagecreatefrompng($source);

  imagejpeg($image, $destination, $quality);
  return $destination;
}

function deactivateAllProductsByMember($memberId) {
  $ci = CI();
  $ci->db->query("UPDATE wps_products SET status = '0' WHERE status='1' AND customers_id = '" . $memberId . "'");
}
function activateAllProductsByMember($memberId) {
  $ci = CI();
  $ci->db->query("UPDATE wps_products SET status = '1' WHERE status='0' AND customers_id = '" . $memberId . "'");
}

function deleteAllProductsByMember($memberId) {
  $ci = CI();
  $pres = $ci->db->query("SELECT products_id FROM wps_products WHERE customers_id = '" . $memberId . "'")->result_array();
  if (is_array($pres) && !empty($pres)) {
    foreach ($pres as $res) {
      $productId = $res['products_id'];
      $resPm = $ci->db->query("SELECT id, media FROM wps_products_media WHERE products_id = '" . $productId . "'")->result_array();
      foreach ($resPm as $pmRes) {
        $imageName = $pmRes['media'];
        $unlink_image = array('source_dir' => "product_images", 'source_file' => $imageName);
        $unlink_image1 = array('source_dir' => "product_images/thumb", 'source_file' => $imageName);
        //trace($unlink_image);
        removeImage($unlink_image);
        removeImage($unlink_image1);
        $ci->db->query("DELETE FROM wps_products_media WHERE id = '" . $pmRes['id'] . "'");
      }
    }
    $ci->db->query("DELETE FROM wps_products WHERE customers_id = '" . $memberId . "'");
  }
}
