<?php

if (!defined('BASEPATH'))
  exit('No direct script access allowed');

class Product_model extends MY_Model {

  public function get_products($limit = '10', $offset = '0', $param = array()) {
    $productType = @$param['productType'];
    $category_id = @$param['category_id'];
    $customers_id = @$param['customers_id'];
    $categoryIds = @$param['categoryIds'];
    $status = @$param['status'];
    $productid = @$param['productid'];
    $orderby = @$param['orderby'];
    $groupby = @$param['groupby'];
    $where = @$param['where'];
    $catIds = @$param['catIds'];
    $price = @$param['price'];
    $newarrival = @$param['newarrival'];
    $bestseller = @$param['bestseller'];
    $brand = @$param['brand'];
    $new = @$param['new_arrival'];
    $popular = @$param['popular'];
    $best_seller = @$param['best_seller'];
    $city = @$param['city'];
    $leave_product_id = @$param['leave_product_id'];
    $businessNaturePosted = @$param['businessNaturePosted'];
    $is_template = (int) @$param['is_template'];

    $keyword = trim($this->input->get_post('keyword', TRUE));
    $keyword = $this->db->escape_str($keyword);

    $search_keyword = trim($this->input->get_post('keywordSearch', TRUE));
    $search_keyword = $this->db->escape_str($search_keyword);

    if ($productType!="") {
      $this->db->where("wlp.productType = '" . $productType . "'");
    }
    if (!empty($catIds)) {
      $this->db->where("wlp.category_id IN ($catIds)");
    }
    if (!empty($newarrival)) {
      $this->db->where("wlp.newarrival_product = '" . $newarrival . "'");
    }
    if (!empty($brand)) {
      $this->db->where("wlp.brand_id = '" . $brand . "'");
    }
    if (!empty($bestseller)) {
      $this->db->where("wlp.special_product = '" . $bestseller . "'");
    }
    if (!empty($price)) {
      $price = explode('-', $price);
      $this->db->where("wlp.product_price between '$price[0]' AND '$price[1]'");
    }
    if (!empty($new)) {
      $this->db->where("wlp.newarrival_product = '" . $new . "'");
    }

    if (!empty($best_seller)) {
      $this->db->where("wlp.special_product = '" . $best_seller . "'");
    }
    if ($is_template > 0) {
      if ($category_id != '') {
        $this->db->where("website_category_id = '" . $category_id . "'");
      }  
    } else {
      if ($category_id != '') {
        //$this->db->where("FIND_IN_SET('" . $category_id . "',wlp.category_links) AND category_id!=''");
        $this->db->where("FIND_IN_SET('" . $category_id . "',wlp.category_links) AND category_id!=''");
      }
    }
    if ($customers_id > 0) {
      $this->db->where("wlp.customers_id = '" . $customers_id . "'");
    }
    if ($categoryIds != '') {
      $catIdsArr = explode(',', $categoryIds);
      $cstStr = "(";
      foreach ($catIdsArr as $cId) {
        $cstStr .= "FIND_IN_SET('" . $cId . "', wlp.category_links) OR ";
      }
      $cstStr = substr($cstStr, 0, -3);
      $cstStr .= ")";
      $this->db->where($cstStr);
    }

    if (is_array($businessNaturePosted) && !empty($businessNaturePosted)) {
      $cstStr = "(";
      foreach ($businessNaturePosted as $cId) {
        //$cstStr .= "FIND_IN_SET('" . $cId . "', cf.business_nature_alt) OR ";
        $cstStr .= "FIND_IN_SET('" . $cId . "', cf.business_nature) OR ";
      }
      $cstStr = substr($cstStr, 0, -3);
      $cstStr .= ")";
      $this->db->where($cstStr);
    }


    if ($productid != '') {
      $this->db->where("wlp.products_id  ", "$productid");
    }
    if ($status != '') {
      $this->db->where("wlp.status", "$status");
    }
    if ($where != '') {
      $this->db->where($where);
    }
    if ($keyword != '') {
      $this->db->where("(LOWER(wlp.product_name) LIKE '%" . strtolower($keyword) . "%' OR LOWER(wlp.product_code) LIKE '%" . strtolower($keyword) . "%')");
    }
    if ($search_keyword != '') {
      $this->db->where("(LOWER(wlp.product_name) LIKE '%" . strtolower($search_keyword) . "%' OR LOWER(wlp.product_code) LIKE '%" . strtolower($search_keyword) . "%')");
    }
    if (!empty($leave_product_id)) {
      $this->db->where("wlp.products_id != '" . $leave_product_id . "'");
    }
    if ($city > 0) {
      //$this->db->where("(c.city = '" . $city . "')");
      if($city=='25'){
        $this->db->where("(c.city = '" . $city . "' OR c.state = '" . $city . "')");
      }else{
        $this->db->where("(c.city = '" . $city . "')");
      }
      
    }


    if ($orderby != '') {
      $this->db->order_by($orderby);
    } else {
      $this->db->order_by('wlpm.products_id', 'desc');
    }
    if ($limit > 0) {
      if (applyFilter('NUMERIC_WT_ZERO', $offset) == -1) {
        $offset = 0;
      }
      $this->db->limit($limit, $offset);
    }

    if ($groupby) {
      $this->db->group_by($groupby);
    } else {
      $this->db->group_by("wlp.products_id");
    }
    $this->db->select('SQL_CALC_FOUND_ROWS wlp.*,wlpm.media,wlpm.media_type,wlpm.is_default, c.city, c.state', FALSE);
    $this->db->from('wps_products as wlp');
    if ($this->uri->segment(1) != 'sitepanel') {
      $this->db->where('wlp.status !=', '2');
    }
    $this->db->join('wps_products_media AS wlpm', 'wlp.products_id=wlpm.products_id', 'left');
    $this->db->join('wps_customers AS c', 'wlp.customers_id=c.customers_id', 'left');
    $this->db->join('wps_customers_factsheet AS cf', 'wlp.customers_id=cf.customers_id', 'left');

    $q = $this->db->get();
    //echo_sql(); 
    //die;
    $result = $q->result_array();
    return $result;
  }

  public function get_company_products($limit = '10', $offset = '0', $param = array()) {
    $category_id = @$param['category_id'];
    $customers_id = @$param['customers_id'];
    $categoryIds = @$param['categoryIds'];
    $status = @$param['status'];
    $productid = @$param['productid'];
    $orderby = @$param['orderby'];
    $groupby = @$param['groupby'];
    $where = @$param['where'];
    $catIds = @$param['catIds'];
    $price = @$param['price'];
    $newarrival = @$param['newarrival'];
    $bestseller = @$param['bestseller'];
    $brand = @$param['brand'];
    $new = @$param['new_arrival'];
    $popular = @$param['popular'];
    $best_seller = @$param['best_seller'];
    $city = @$param['city'];
    $leave_product_id = @$param['leave_product_id'];
    $businessNaturePosted = @$param['businessNaturePosted'];

    $keyword = trim($this->input->get_post('keyword', TRUE));
    $keyword = $this->db->escape_str($keyword);

    $search_keyword = trim($this->input->get_post('keyword_search', TRUE));
    $search_keyword = $this->db->escape_str($search_keyword);

    if (!empty($catIds)) {
      $this->db->where("wlp.category_id IN ($catIds)");
    }
    if (!empty($newarrival)) {
      $this->db->where("wlp.newarrival_product = '" . $newarrival . "'");
    }

    if (!empty($bestseller)) {
      $this->db->where("wlp.special_product = '" . $bestseller . "'");
    }
    if (!empty($price)) {
      $price = explode('-', $price);
      $this->db->where("wlp.product_price between '$price[0]' AND '$price[1]'");
    }
    if (!empty($new)) {
      $this->db->where("wlp.newarrival_product = '" . $new . "'");
    }
    if (!empty($popular)) {
      $this->db->where("wlp.coming_product = '" . $popular . "'");
    }
    if (!empty($best_seller)) {
      $this->db->where("wlp.special_product = '" . $best_seller . "'");
    }
    if ($category_id != '') {
      $this->db->where("FIND_IN_SET('" . $category_id . "',wlp.category_links) AND category_id!=''");
    }
    if ($customers_id > 0) {
      $this->db->where("wlp.customers_id = '" . $customers_id . "'");
    }
    if ($categoryIds != '') {
      $catIdsArr = explode(',', $categoryIds);
      $cstStr = "(";
      foreach ($catIdsArr as $cId) {
        $cstStr .= "FIND_IN_SET('" . $cId . "', wlp.category_links) OR ";
      }
      $cstStr = substr($cstStr, 0, -3);
      $cstStr .= ")";
      $this->db->where($cstStr);
    }

    if (is_array($businessNaturePosted) && !empty($businessNaturePosted)) {
      $cstStr = "(";
      foreach ($businessNaturePosted as $cId) {
        $cstStr .= "FIND_IN_SET('" . $cId . "', cf.business_nature_alt) OR ";
      }
      $cstStr = substr($cstStr, 0, -3);
      $cstStr .= ")";
      $this->db->where($cstStr);
    }


    if ($productid != '') {
      $this->db->where("wlp.products_id  ", "$productid");
    }
    if ($status != '') {
      $this->db->where("wlp.status", "$status");
    }
    if ($where != '') {
      $this->db->where($where);
    }
    if ($keyword != '') {
      $this->db->where("(LOWER(wlp.product_name) LIKE '%" . strtolower($keyword) . "%' OR LOWER(wlp.product_code) LIKE '%" . strtolower($keyword) . "%')");
    }
    if ($search_keyword != '') {
      $this->db->where("(LOWER(wlp.product_name) LIKE '%" . strtolower($search_keyword) . "%' OR LOWER(wlp.product_code) LIKE '%" . strtolower($search_keyword) . "%')");
    }
    if (!empty($leave_product_id)) {
      $this->db->where("wlp.products_id != '" . $leave_product_id . "'");
    }
    if ($city > 0) {
      $this->db->where("(c.city = '" . $city . "' OR c.state = '" . $city . "')");
    }


    if ($orderby != '') {
      $this->db->order_by($orderby);
    } else {
      $this->db->order_by('wlpm.products_id', 'desc');
    }
    if ($limit > 0) {
      if (applyFilter('NUMERIC_WT_ZERO', $offset) == -1) {
        $offset = 0;
      }
      $this->db->limit($limit, $offset);
    }

    if ($groupby) {
      $this->db->group_by($groupby);
    } else {
      $this->db->group_by("wlp.products_id");
    }
    $this->db->select('SQL_CALC_FOUND_ROWS wlp.*,wlpm.media,wlpm.media_type,wlpm.is_default', FALSE);
    $this->db->from('wps_company_products as wlp');
    if ($this->uri->segment(1) != 'sitepanel') {
      $this->db->where('wlp.status !=', '2');
    }
    $this->db->join('wps_company_products_media AS wlpm', 'wlp.products_id=wlpm.products_id', 'left');
    //$this->db->join('wps_customers AS c', 'wlp.customers_id=c.customers_id', 'left');
    //$this->db->join('wps_customers_factsheet AS cf', 'wlp.customers_id=cf.customers_id', 'left');


    $q = $this->db->get();
    //echo_sql(); 
    //die;
    $result = $q->result_array();
    return $result;
  }

  public function get_product_media($limit = '5', $offset = '0', $param = array()) {
    $default = @$param['default'];
    $productid = @$param['productid'];
    $media_type = @$param['media_type'];

    if (is_array($param) && !empty($param)) {
      $this->db->select('SQL_CALC_FOUND_ROWS *', FALSE);
      $this->db->limit($limit, $offset);
      $this->db->from('wps_products_media');
      $this->db->where('products_id', $productid);

      if ($default != '') {
        $this->db->where('is_default', $default);
      }
      if ($media_type != '') {
        $this->db->where('media_type', $media_type);
      }

      $q = $this->db->get();
      $result = $q->result_array();
      $result = ($limit == '1') ? $result[0] : $result;
      return $result;
    }
  }

  public function update_viewed($id, $counter = 0) {
    $id = (int) $id;
    if ($id > 0) {
      $posted_data = array(
          'products_viewed' => ($counter + 1)
      );
      $where = "products_id = '" . $id . "'";
      $this->category_model->safe_update('wps_products', $posted_data, $where, FALSE);
    }
  }

  public function get_related_products($condition) {
    $condtion = (!empty($condition)) ? "status !='2'  $condition" : "status !='2'";
    $fetch_config = array(
        'condition' => $condtion,
        'order' => "products_id DESC",
        'limit' => 'NULL',
        'start' => 'NULL',
        'debug' => FALSE,
        'return_type' => "array"
    );
    $result = $this->findAll('wps_products', $fetch_config);
    return $result;
  }

  public function related_products($res, $limit = 'NULL', $start = 'NULL') {
    $condtion = array();
    $condtion['where'] = "wlp.status ='1' AND wlp.products_id IN(SELECT wpr.related_id FROM wps_products_related as wpr WHERE wpr.product_id ='" . $res['products_id'] . "') ";
    $res_data = $this->get_products($limit, $start, $condtion);
    return $res_data;
  }

   public function add_bulk_upload_product($worksheet) {
    for ($i = 2; $i <= count($worksheet); $i++) {

      $imageLink = $filename = '';
      $imageLink2 = $filename2 = '';
      $imageLink3 = $filename3 = '';
      $imageLink4 = $filename4 = '';

      $user_mobile = (!isset($worksheet[$i][1])) ? '' : addslashes(trim($worksheet[$i][1]));
      $category_name = (!isset($worksheet[$i][2])) ? '' : addslashes(trim($worksheet[$i][2]));
      $product_name = (!isset($worksheet[$i][3])) ? '' : addslashes(trim($worksheet[$i][3]));
      $product_code = (!isset($worksheet[$i][4])) ? '' : addslashes(trim($worksheet[$i][4]));
      $price = (!isset($worksheet[$i][5])) ? '' : addslashes(trim($worksheet[$i][5]));
      $unit_value = (!isset($worksheet[$i][6])) ? '' : addslashes(trim($worksheet[$i][6]));
      $unit = (!isset($worksheet[$i][7])) ? '' : addslashes(trim($worksheet[$i][7]));
      $youtube_video_id = (!isset($worksheet[$i][8])) ? '' : addslashes(trim($worksheet[$i][8]));
      $product_attribute = (!isset($worksheet[$i][9])) ? '' : addslashes(trim($worksheet[$i][9]));
      $attribute_value = (!isset($worksheet[$i][10])) ? '' : addslashes(trim($worksheet[$i][10]));
      $description = (!isset($worksheet[$i][11])) ? '' : addslashes(trim($worksheet[$i][11]));
     
      $imageLink = (!isset($worksheet[$i][12])) ? '' : addslashes(trim($worksheet[$i][12]));
      $imageLink2 = (!isset($worksheet[$i][13])) ? '' : addslashes(trim($worksheet[$i][13]));
      $imageLink3 = (!isset($worksheet[$i][14])) ? '' : addslashes(trim($worksheet[$i][14]));

      $imageLink4 = (!isset($worksheet[$i][15])) ? '' : addslashes(trim($worksheet[$i][15]));
     
     
      $category_id = get_db_field_value("wps_categories", "category_id", "WHERE category_name like '%" . trim($category_name) . "%'");
      $category_links = get_parent_categories($category_id, "AND status='1'", "category_id,parent_id");
      $category_links = array_keys($category_links);
      $category_links = implode(",", $category_links);

      $cust_id = get_db_field_value("wps_customers", "customers_id", "WHERE user_name like '%" . trim($user_mobile) . "%'");

      if ($imageLink != '') {
        $imageLink = str_replace('?dl=0', '?dl=1', $imageLink);
        $url = $imageLink;
        $image_ext = explode('.', $imageLink);
        $image_ext = array_reverse($image_ext);
        $filename = seo_url_title($product_name).rand().'.'.str_replace('?dl=1', '', $image_ext[0]);
        //get File content and save to destination path
        $blob = file_get_contents($url);
        $image = base64_encode($blob);
        $dataImg = base64_decode($image);
        //echo '<img src="data:image/jpg;base64,'.$image.'">';
        $success = file_put_contents(UPLOAD_DIR . '/product_images/' . $filename, $dataImg);
        //print $success ? $file : 'Unable to save the file.';
        //die;
      }
      if ($imageLink2 != '') {
        $imageLink2 = str_replace('?dl=0', '?dl=1', $imageLink2);
        $url = $imageLink2;
        $image_ext = explode('.', $imageLink2);
        $image_ext = array_reverse($image_ext);
        $filename2 = seo_url_title($product_name).rand() . '.' . str_replace('?dl=1', '', $image_ext[0]);
        //get File content and save to destination path
        $blob = file_get_contents($url);
        $image = base64_encode($blob);
        $dataImg = base64_decode($image);
        //echo '<img src="data:image/jpg;base64,'.$image.'">';
        $success = file_put_contents(UPLOAD_DIR . '/product_images/' . $filename2, $dataImg);
        //print $success ? $file : 'Unable to save the file.';
        //die;
      }
      if ($imageLink3 != '') {
        $imageLink3 = str_replace('?dl=0', '?dl=1', $imageLink3);
        $url = $imageLink3;
        $image_ext = explode('.', $imageLink3);
        $image_ext = array_reverse($image_ext);
        $filename3 = seo_url_title($product_name).rand() . '.' . str_replace('?dl=1', '', $image_ext[0]);
        //get File content and save to destination path
        $blob = file_get_contents($url);
        $image = base64_encode($blob);
        $dataImg = base64_decode($image);
        //echo '<img src="data:image/jpg;base64,'.$image.'">';
        $success = file_put_contents(UPLOAD_DIR . '/product_images/' . $filename3, $dataImg);
        //print $success ? $file : 'Unable to save the file.';
        //die;
      }
      if ($imageLink4 != '') {
        $imageLink4 = str_replace('?dl=0', '?dl=1', $imageLink4);
        $url = $imageLink4;
        $image_ext = explode('.', $imageLink4);
        $image_ext = array_reverse($image_ext);
        $filename4 = seo_url_title($product_name).rand() . '.' . str_replace('?dl=1', '', $image_ext[0]);
        //get File content and save to destination path
        $blob = file_get_contents($url);
        $image = base64_encode($blob);
        $dataImg = base64_decode($image);
        //echo '<img src="data:image/jpg;base64,'.$image.'">';
        $success = file_put_contents(UPLOAD_DIR . '/product_images/' . $filename4, $dataImg);
        //print $success ? $file : 'Unable to save the file.';
        //die;
      }

      if ($product_code == "") {
        $product_code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $product_code = 'NTI' . $product_code . date('Ym');
      }
      $unit_measurements = $this->config->item('unit_measurement');
      $unit_measurement = array_search ($unit, $unit_measurements);

       $posted_data = array(
          'customers_id' => $cust_id,
          'category_id' => $category_id,
          'category_links' => $category_links,
          'product_name' => $product_name,
          'product_code' => $product_code,
          'moq' => $moq,
          'product_price' => $price,
          'unit_value' => $unit_value,
          'unit_measurement' => $unit_measurement,
          'product_alt' => $product_name,
          'attribute_name' => $product_attribute,
          'attribute_value' => $attribute_value,
          'dispatch_port' => $port_of_dispatch,
          'delivery_time' => $delivery_time,
          'packaging_details' => $packaging_details,
          'dashkeyword' => '',
          'products_description' => $description,
          'youtube_id' => $youtube_video_id,
          'product_added_date' => $this->config->item('config.date.time')
      );
    
      $product_id = $this->safe_insert('wps_products', $posted_data, FALSE);

      //Update Media
      if ($product_id > 0) {
        $this->cbk_friendly_url = seo_url_title($product_name.'-'.$product_id);
        $this->db->query("UPDATE wps_products SET friendly_url = '" . $this->cbk_friendly_url . "' WHERE products_id = '" . $product_id . "'");

        $productId = $product_id;
        
        $is_default = 'Y';
        if ($filename!='') {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $filename . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
       
        if ($filename2 != '') {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $filename2 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($filename3 != '') {
         $this->db->query("INSERT INTO wps_products_media SET media = '" . $filename3 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($filename4 != '') {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $filename4 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        
        //Create Meta
        $redirect_url = "products/detail";
        $meta_array = array(
            'entity_type' => $redirect_url,
            'entity_id' => $productId,
            'page_url' => $this->cbk_friendly_url,
            'meta_title' => get_text($product_name, 80),
            'meta_description' => get_text($description),
            'meta_keyword' => get_keywords($description)
        );
        create_meta($meta_array);
      }
    }
    //exit;
    return true;
  }


  public function add_bulk_upload_product_services($worksheet) {
    for ($i = 2; $i <= count($worksheet); $i++) {

      $imageLink = $filename = '';
      $imageLink2 = $filename2 = '';
      $imageLink3 = $filename3 = '';
      $imageLink4 = $filename4 = '';

      $user_mobile = (!isset($worksheet[$i][1])) ? '' : addslashes(trim($worksheet[$i][1]));
      $category_name = (!isset($worksheet[$i][2])) ? '' : addslashes(trim($worksheet[$i][2]));
      $product_name = (!isset($worksheet[$i][3])) ? '' : addslashes(trim($worksheet[$i][3]));
      $product_code = (!isset($worksheet[$i][4])) ? '' : addslashes(trim($worksheet[$i][4]));
      $price = (!isset($worksheet[$i][5])) ? '' : addslashes(trim($worksheet[$i][5]));
      $unit_value = (!isset($worksheet[$i][6])) ? '' : addslashes(trim($worksheet[$i][6]));
      $unit = (!isset($worksheet[$i][7])) ? '' : addslashes(trim($worksheet[$i][7]));
      $youtube_video_id = (!isset($worksheet[$i][8])) ? '' : addslashes(trim($worksheet[$i][8]));
      $product_attribute = (!isset($worksheet[$i][9])) ? '' : addslashes(trim($worksheet[$i][9]));
      $attribute_value = (!isset($worksheet[$i][10])) ? '' : addslashes(trim($worksheet[$i][10]));
      $description = (!isset($worksheet[$i][11])) ? '' : addslashes(trim($worksheet[$i][11]));
     
      $imageLink = (!isset($worksheet[$i][12])) ? '' : addslashes(trim($worksheet[$i][12]));
      $imageLink2 = (!isset($worksheet[$i][13])) ? '' : addslashes(trim($worksheet[$i][13]));
      $imageLink3 = (!isset($worksheet[$i][14])) ? '' : addslashes(trim($worksheet[$i][14]));

      $imageLink4 = (!isset($worksheet[$i][15])) ? '' : addslashes(trim($worksheet[$i][15]));
     
     
      $category_id = get_db_field_value("wps_categories", "category_id", "WHERE category_name like '%" . trim($category_name) . "%'");
      $category_links = get_parent_categories($category_id, "AND status='1'", "category_id,parent_id");
      $category_links = array_keys($category_links);
      $category_links = implode(",", $category_links);

      $cust_id = get_db_field_value("wps_customers", "customers_id", "WHERE user_name like '%" . trim($user_mobile) . "%'");

      if ($imageLink != '') {
        $imageLink = str_replace('?dl=0', '?dl=1', $imageLink);
        $url = $imageLink;
        $image_ext = explode('.', $imageLink);
        $image_ext = array_reverse($image_ext);
        $filename = seo_url_title($product_name).rand().'.'.str_replace('?dl=1', '', $image_ext[0]);
        //get File content and save to destination path
        $blob = file_get_contents($url);
        $image = base64_encode($blob);
        $dataImg = base64_decode($image);
        //echo '<img src="data:image/jpg;base64,'.$image.'">';
        $success = file_put_contents(UPLOAD_DIR . '/product_images/' . $filename, $dataImg);
        //print $success ? $file : 'Unable to save the file.';
        //die;
      }
      if ($imageLink2 != '') {
        $imageLink2 = str_replace('?dl=0', '?dl=1', $imageLink2);
        $url = $imageLink2;
        $image_ext = explode('.', $imageLink2);
        $image_ext = array_reverse($image_ext);
        $filename2 = seo_url_title($product_name).rand() . '.' . str_replace('?dl=1', '', $image_ext[0]);
        //get File content and save to destination path
        $blob = file_get_contents($url);
        $image = base64_encode($blob);
        $dataImg = base64_decode($image);
        //echo '<img src="data:image/jpg;base64,'.$image.'">';
        $success = file_put_contents(UPLOAD_DIR . '/product_images/' . $filename2, $dataImg);
        //print $success ? $file : 'Unable to save the file.';
        //die;
      }
      if ($imageLink3 != '') {
        $imageLink3 = str_replace('?dl=0', '?dl=1', $imageLink3);
        $url = $imageLink3;
        $image_ext = explode('.', $imageLink3);
        $image_ext = array_reverse($image_ext);
        $filename3 = seo_url_title($product_name).rand() . '.' . str_replace('?dl=1', '', $image_ext[0]);
        //get File content and save to destination path
        $blob = file_get_contents($url);
        $image = base64_encode($blob);
        $dataImg = base64_decode($image);
        //echo '<img src="data:image/jpg;base64,'.$image.'">';
        $success = file_put_contents(UPLOAD_DIR . '/product_images/' . $filename3, $dataImg);
        //print $success ? $file : 'Unable to save the file.';
        //die;
      }
      if ($imageLink4 != '') {
        $imageLink4 = str_replace('?dl=0', '?dl=1', $imageLink4);
        $url = $imageLink4;
        $image_ext = explode('.', $imageLink4);
        $image_ext = array_reverse($image_ext);
        $filename4 = seo_url_title($product_name).rand() . '.' . str_replace('?dl=1', '', $image_ext[0]);
        //get File content and save to destination path
        $blob = file_get_contents($url);
        $image = base64_encode($blob);
        $dataImg = base64_decode($image);
        //echo '<img src="data:image/jpg;base64,'.$image.'">';
        $success = file_put_contents(UPLOAD_DIR . '/product_images/' . $filename4, $dataImg);
        //print $success ? $file : 'Unable to save the file.';
        //die;
      }

      if ($product_code == "") {
        $product_code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $product_code = 'NTI' . $product_code . date('Ym');
      }
      $unit_measurements = $this->config->item('unit_measurement');
      $unit_measurement = array_search ($unit, $unit_measurements);

       $posted_data = array(
          'customers_id' => $cust_id,
          'category_id' => $category_id,
          'category_links' => $category_links,
          'product_name' => $product_name,
          'product_code' => $product_code,
          'moq' => $moq,
          'product_price' => $price,
          'unit_value' => $unit_value,
          'unit_measurement' => $unit_measurement,
          'product_alt' => $product_name,
          'attribute_name' => $product_attribute,
          'attribute_value' => $attribute_value,
          'dispatch_port' => $port_of_dispatch,
          'delivery_time' => $delivery_time,
          'packaging_details' => $packaging_details,
          'dashkeyword' => '',
          'products_description' => $description,
          'youtube_id' => $youtube_video_id,
          'productType' => '1',
          'product_added_date' => $this->config->item('config.date.time')
      );
    
      $product_id = $this->safe_insert('wps_products', $posted_data, FALSE);

      //Update Media
      if ($product_id > 0) {
        $this->cbk_friendly_url = seo_url_title($product_name.'-'.$product_id);
        $this->db->query("UPDATE wps_products SET friendly_url = '" . $this->cbk_friendly_url . "' WHERE products_id = '" . $product_id . "'");

        $productId = $product_id;
        
        $is_default = 'Y';
        if ($filename!='') {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $filename . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
       
        if ($filename2 != '') {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $filename2 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($filename3 != '') {
         $this->db->query("INSERT INTO wps_products_media SET media = '" . $filename3 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($filename4 != '') {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $filename4 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        
        //Create Meta
        $redirect_url = "products/detail";
        $meta_array = array(
            'entity_type' => $redirect_url,
            'entity_id' => $productId,
            'page_url' => $this->cbk_friendly_url,
            'meta_title' => get_text($product_name, 80),
            'meta_description' => get_text($description),
            'meta_keyword' => get_keywords($description)
        );
        create_meta($meta_array);
      }
    }
    //exit;
    return true;
  }




}
