<?php

class Category extends Public_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->helper(array('category/category', 'products/product'));
    $this->load->model(array('category/category_model', 'products/product_model', 'styles/style_model', 'brands/brand_model', 'admin/color_model', 'admin/size_model'));
  }

  public function index() {
    $category_id = (int) $this->meta_info['entity_id'];
    $have_sub_cat = get_db_field_value('wps_categories', 'parent_id', "WHERE parent_id = '$category_id' ");
    if ($category_id > 0) {
      if ($have_sub_cat > 0) {
        $this->category_listing($category_id);
      } else {
        $this->products_listing($category_id);
      }
    } else {
      $this->products_listing($category_id);
    }
 
  }

  public function products_listing($category_id) {
    $this->page_section_ct = 'product';
    $condtion = array();
    $cat_res = '';
    $record_per_page = (int) $this->input->post('pagesize');
    $category_id = (int) $category_id;
    $page_segment = find_paging_segment();
    $config['per_page'] = ( $record_per_page > 0 ) ? $record_per_page : $this->config->item('pagesize');
    $offset = (int) $this->uri->segment($page_segment, 0);
    $base_url = ( $category_id != '' ) ? "category/products_listing/$category_id/pg/" : "category/products_listing/pg/";

    $page_title = "Products List";

    //Sorting
    $sort = $this->input->get_post('sort');
    if ($sort > 0) {
      if ($sort == 1) {//Popular Products
        $condtion['orderby'] = 'wlp.products_viewed DESC';
      }
      if ($sort == 2) {//New Arrival
        $condtion['orderby'] = 'wlp.products_id DESC';
      }
      if ($sort == 4) {//Price Low to High
        $condtion['orderby'] = '(CASE WHEN wlp.product_discounted_price > 0 THEN wlp.product_discounted_price ELSE wlp.product_price END) ASC';
        //$condtion['orderby'] = 'wlp.product_price ASC';
      }
      if ($sort == 3) {//Price High to Low
        $condtion['orderby'] = '(CASE WHEN wlp.product_discounted_price > 0 THEN wlp.product_discounted_price ELSE wlp.product_price END) DESC';
        //$condtion['orderby'] = 'wlp.product_price DESC';
      }
    } else {
      $condtion['orderby'] = 'wlp.product_code asc';
    }


    $condtion['status'] = '1';
    $color = $this->input->post('color');
    $size = $this->input->post('size');
    $price = $this->input->post('price');
    $category_ids = $this->input->post('category_id');

    if (!empty($color)) {
      $colors = implode(',', $color);
      $condtion['color'] = $colors;
    }
    if (!empty($size)) {
      $sizes = implode(',', $size);
      $condtion['size'] = $sizes;
    }
    if (!empty($price)) {
      $condtion['price'] = $price;
    }
    if ($category_ids > 0) {
      $condtion['category_ids'] = $category_ids;
    }



    $srtQry = "AND parent_id = '1'";
    $data['catid'] = "";
    $category_description = "";
    if ($category_id > 0) {
      $condtion['category_id'] = $category_id;
      $cat_res = get_db_single_row('wps_categories', '*', " category_id='$category_id'");
      // $page_title = (isset($cat_res['category_heading']) && $cat_res['category_heading']!='')?$cat_res['category_heading']:$cat_res['category_name'];
      $page_title = $cat_res['category_name_p'];
      $category_description = $cat_res['category_description'];
      $srtQry = "AND parent_id = '" . $cat_res['parent_id'] . "'";
      $data['catid'] = $category_id;

      //Check if it is subdomain
      $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
      $uri_segments = explode('/', $uri_path);
      $st = $uri_segments[1];
      if (strstr($st, '.html')) {
        $st = substr($st, 0, -5);
      }
      $stArray = $this->db->query("SELECT page_url FROM wps_meta_tags WHERE is_fixed='L' AND page_url='" . $st . "'")->row_array();
      if (is_array($stArray) & !empty($stArray)) {
        $resprosub = $this->db->query("SELECT * FROM wps_subcontent WHERE status = '1' AND FIND_IN_SET($category_id,category_id)")->row();
        if (is_object($resprosub) && !empty($resprosub)) {

          //With location and category
          $locId = get_db_field_value("wps_meta_tags", "meta_id", "WHERE page_url = '" . $st . "'");
          $resprosubloc = $this->db->query("SELECT * FROM wps_subcontent WHERE status = '1' AND FIND_IN_SET($category_id,category_id) AND FIND_IN_SET($locId,location_id)")->row();
          if (is_object($resprosubloc) && !empty($resprosubloc)) {//With location and category
            $key1 = $resprosubloc->meta_key1;
            $key2 = $resprosubloc->meta_key2;
            $key3 = $resprosubloc->meta_key3;
            $cat_res['category_description'] = str_replace('{catname}', $page_title, str_replace('{location}', ucwords(locationName($st)), str_replace('{key3}', $key3, str_replace('{key2}', $key2, str_replace('{key1}', $key1, $resprosubloc->description)))));
            if ($resprosubloc->page_heading != '') {
              $page_title = str_replace('{catname}', $page_title, str_replace('{location}', ucwords(locationName($st)), str_replace('{key3}', $key3, str_replace('{key2}', $key2, str_replace('{key1}', $key1, $resprosubloc->page_heading)))));
            } else {
              $page_title .= ' In ' . ucwords(locationName($st));
            }
          } else {//With category only
            $key1 = $resprosub->meta_key1;
            $key2 = $resprosub->meta_key2;
            $key3 = $resprosub->meta_key3;
            $cat_res['category_description'] = str_replace('{catname}', $page_title, str_replace('{location}', ucwords($st), str_replace('{key3}', $key3, str_replace('{key2}', $key2, str_replace('{key1}', $key1, $resprosub->description)))));
            if ($resprosub->page_heading != '') {
              $page_title = str_replace('{catname}', $page_title, str_replace('{location}', ucwords(locationName($st)), str_replace('{key3}', $key3, str_replace('{key2}', $key2, str_replace('{key1}', $key1, $resprosub->page_heading)))));
            } else {
              $page_title .= ' In ' . ucwords(locationName($st));
            }
          }
        }
      }
    }
    
    $res_array = $this->product_model->get_products($config['per_page'], $offset, $condtion);
    //echo_sql();
    $data['total_rows'] = $data['total_list_rows'] = $config['total_rows'] = get_found_rows();
    $data['heading_title'] = $page_title;
    $data['category_description'] = $category_description;
    $data['products'] = $res_array;
    $data['cat_res'] = $cat_res;
    
    /* Available Color Records */
    $color_cond_config = array(
        'condition' => " AND status='1' ",
        'order' => 'color_name '
    );
    $colors = $this->db->select('*')->from('wps_colors')->where('status', '1')->order_by('color_type', 'desc')->get()->result_array();
    $data['colors'] = $colors;
    /* Available Size Records */
    $size_cond_config = array(
        'condition' => " AND status='1' ",
        'order' => 'size_name '
    );
    $sizes = $this->size_model->getsizes($size_cond_config);
    $data['sizes'] = $sizes;
    $data['themes'] = $this->db->query("SELECT * FROM wps_categories WHERE status = '1' AND parent_id != '0'")->result_array();
    $this->load->view('products/view_product_listing', $data);
  }

  public function category_listing() {

    $data['unq_section'] = isset($parentdata) && is_object($parentdata) ? "Subcategory" : "Category";
    $data['title'] = "Category";
    $data['heading_title'] = 'Our Range';
    $page_title = 'Category';

    //For paging
    $record_per_page = (int) $this->input->post('per_page');
    if (array_key_exists('entity_id', $this->meta_info) && $this->meta_info['entity_id'] > 0) {
      $parent_segment = (int) $this->meta_info['entity_id'];
    } else {
      $parent_segment = (int) $this->uri->segment(3);
    }
    $page_segment = find_paging_segment();
    $config['per_page'] = ( $record_per_page > 0 ) ? $record_per_page : $this->config->item('per_page');
    $offset = (int) $this->uri->segment($page_segment, 0);
    $parent_id = ( $parent_segment > 0 ) ? $parent_segment : '0';
    $base_url = ( $parent_segment > 0 ) ? "category/category_listing/$parent_id/pg/" : "category/category_listing/pg/";

    //Cat List    
    $condtion_array = array('field' => "*,( SELECT COUNT(category_id) FROM wps_categories AS b WHERE b.parent_id=a.category_id ) AS total_subcategories", 'condition' => "AND parent_id = '$parent_id' AND status='1' ", 'limit' => $config['per_page'], 'offset' => $offset, 'debug' => FALSE);
    $res_array = $this->category_model->getcategory($condtion_array);
    $data['total_rows'] = $config['total_rows'] = $this->category_model->total_rec_found;
    //$data['page_links'] = front_pagination("$base_url", $config['total_rows'], $config['per_page'], $page_segment);
    $data['res'] = $res_array;

    //Products
    $proRes = $this->product_model->get_products(5, 0, array("categoryIds" => $parent_id));
    $data['proRes'] = $proRes;

    //Parent Data
    $parentdata = $this->category_model->get_category_by_id($parent_id);
    $page_title = @$parentdata['category_name_p'];
    //Check if it is subdomain
    $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $uri_segments = explode('/', $uri_path);
    $st = $uri_segments[1];
    if (strstr($st, '.html')) {
      $st = substr($st, 0, -5);
    }
    $stArray = $this->db->query("SELECT page_url FROM wps_meta_tags WHERE is_fixed='L' AND page_url='" . $st . "'")->row_array();
    if (is_array($stArray) & !empty($stArray)) {
      $resprosub = $this->db->query("SELECT * FROM wps_subcontent WHERE status = '1' AND FIND_IN_SET($parent_id,category_id)")->row();
      if (is_object($resprosub) && !empty($resprosub)) {

        //With location and category
        $locId = get_db_field_value("wps_meta_tags", "meta_id", "WHERE page_url = '" . $st . "'");
        $resprosubloc = $this->db->query("SELECT * FROM wps_subcontent WHERE status = '1' AND FIND_IN_SET($parent_id,category_id) AND FIND_IN_SET($locId,location_id)")->row();
        if (is_object($resprosubloc) && !empty($resprosubloc)) {//With location and category
          $key1 = $resprosubloc->meta_key1;
          $key2 = $resprosubloc->meta_key2;
          $key3 = $resprosubloc->meta_key3;
          $parentdata['category_description'] = str_replace('{catname}', $page_title, str_replace('{location}', ucwords(locationName($st)), str_replace('{key3}', $key3, str_replace('{key2}', $key2, str_replace('{key1}', $key1, $resprosubloc->description)))));
          if ($resprosubloc->page_heading != '') {
            $page_title = str_replace('{catname}', $page_title, str_replace('{location}', ucwords(locationName($st)), str_replace('{key3}', $key3, str_replace('{key2}', $key2, str_replace('{key1}', $key1, $resprosubloc->page_heading)))));
          } else {
            $page_title .= ' In ' . ucwords(locationName($st));
          }
        } else {//With category only
          $key1 = $resprosub->meta_key1;
          $key2 = $resprosub->meta_key2;
          $key3 = $resprosub->meta_key3;
          $parentdata['category_description'] = str_replace('{catname}', $page_title, str_replace('{location}', ucwords($st), str_replace('{key3}', $key3, str_replace('{key2}', $key2, str_replace('{key1}', $key1, $resprosub->description)))));
          if ($resprosub->page_heading != '') {
            $page_title = str_replace('{catname}', $page_title, str_replace('{location}', ucwords(locationName($st)), str_replace('{key3}', $key3, str_replace('{key2}', $key2, str_replace('{key1}', $key1, $resprosub->page_heading)))));
          } else {
            $page_title .= ' In ' . ucwords(locationName($st));
          }
        }
      }
    }
    $data['parentres'] = isset($parentdata) && is_array($parentdata) ? $parentdata : "";


    if ($parent_id > 0) {
      $data['catid'] = $parent_id;
      $conArray = array('field' => "*,( SELECT COUNT(category_id) FROM wps_categories AS b WHERE b.parent_id=a.category_id ) AS total_subcategories", 'condition' => "AND parent_id = '$parent_id' AND status='1' ", //'limit'=>10,//'offset'=>$offset,'debug' => FALSE
      );
      $data['heading_title'] = $parentdata['category_name'];
      $resArray = $this->category_model->getcategory($conArray);
      $data['totalRecord'] = $this->category_model->total_rec_found;
      $data['resleft'] = $resArray;
      $data['page_title'] = $page_title;
      $this->load->view('category/view_category', $data);
    } else {
      $data['page_title'] = 'Category List';
      $this->load->view('category/view_category', $data);
    }
  }

  public function ajax_load_category_view() {
    $data['title'] = 'Ajax Load Category';
    //For Paging
    $config['per_page'] = $this->config->item('per_page');
    $offset = $this->input->get_post('stOffSet');
    if (array_key_exists('entity_id', $this->meta_info) && $this->meta_info['entity_id'] > 0) {
      $parent_segment = (int) $this->meta_info['entity_id'];
    } else {
      $parent_segment = (int) $this->input->get_post('category_id');
    }
    $page_segment = find_paging_segment();
    $parent_id = ( $parent_segment > 0 ) ? $parent_segment : '0';

    //cat result
    $condtion_array = array('field' => "*,( SELECT COUNT(category_id) FROM wps_categories AS b WHERE b.parent_id=a.category_id ) AS total_subcategories", 'condition' => "AND parent_id = '$parent_id' AND status='1' ", 'limit' => $config['per_page'], 'offset' => $offset, 'debug' => FALSE);
    $res_array = $this->category_model->getcategory($condtion_array);
    $config['total_rows'] = $this->category_model->total_rec_found;
    $data['res'] = $res_array;
    $this->load->view('category/ajax_load_category', $data);
  }

  //Datamigration
  public function getOldCategories() {
    $this->db2 = $this->load->database('wp', TRUE);
    $res = $this->db2->query("SELECT * FROM wp_terms WHERE 1")->result_array();
    $resp = array();
    $sl = 0;
    foreach ($res as $cat) {
      $txonomy = $this->db2->query("SELECT * FROM wp_term_taxonomy WHERE term_id = '" . $cat['term_id'] . "' AND taxonomy = 'product_cat'")->result_array();
      if (is_array($txonomy) && !empty($txonomy)) {
        $resp[$sl] = $cat;
        $resp[$sl]['taxonomy'] = $txonomy;

        $sl++;
      }
    }

    //insert data in table
    if (is_array($resp) && !empty($resp)) {
      $redirect_url = "category/index";
      foreach ($resp as $category) {
        //trace($category);
        $posted_data = array(
            'category_id_old' => $category['term_id'],
            'category_name' => $category['name'],
            'category_name_p' => $category['name'],
            'category_alt' => $category['name'],
            'category_description' => '',
            'parent_id' => '0',
            'friendly_url' => seo_url_title($category['name']),
            'date_added' => $this->config->item('config.date.time'),
            'category_image' => '',
            'category_icon' => '',
            'bg_image' => '',
        );
        trace($posted_data);
        //exit;
        //$this->db->insert('wps_categories', $posted_data);
        $insertId = 0; //$this->db->insert_id();
        if ($insertId > 0) {

          $title = '';
          $description = '';
          $keywords = '';

          $meta_array = array(
              'entity_type' => $redirect_url,
              'entity_id' => $insertId,
              'page_url' => seo_url_title($category['name']),
              'meta_title' => $title,
              'meta_description' => $description,
              'meta_keyword' => $keywords
          );
          trace($meta_array);
          //$this->db->insert('wps_meta_tags', $meta_array);
        }
      }
    }
  }

  public function getOldProducts() {
    $this->db2 = $this->load->database('wp', TRUE);
    $res = $this->db2->query("SELECT * FROM wp_posts WHERE post_type = 'product' AND ID != '182' GROUP BY ID ORDER BY ID ASC LIMIT 500, 100")->result_array();
    $resp = array();
    $sl = 0;
    foreach ($res as $cat) {
      $txonomy = $this->db2->query("SELECT * FROM wp_postmeta WHERE post_id = '" . $cat['ID'] . "' AND (meta_key LIKE '%_price')")->result_array();

      $txonomyMeta = $this->db2->query("SELECT * FROM wp_posts WHERE post_parent = '" . $cat['ID'] . "' AND (post_type = 'attachment')")->result_array();

      $resp[$sl] = $cat;
      $resp[$sl]['taxonomy'] = $txonomy;
      $resp[$sl]['taxonomyMeta'] = $txonomyMeta;
      $sl++;
    }


    if (is_array($resp) && !empty($resp)) {
      foreach ($resp as $product) {

        $proCount = count_record("wps_products", "products_id_old = '" . $product['ID'] . "'");
        if ($proCount == 0) {
          //trace($product);
          $price = $dprice = 0;
          foreach ($product['taxonomy'] as $pp) {
            if ($pp['meta_key'] == '_regular_price') {
              $price = $pp['meta_value'];
            }
            if ($pp['meta_key'] == '_price') {
              $dprice = $pp['meta_value'];
            }
          }
          if ($dprice > 0 && $dprice < $price) {
            $price = $price;
            $dprice = $dprice;
          } else {
            $price = $price;
            $dprice = 0;
          }
          //Price Ends Here

          $this->cbk_friendly_url = seo_url_title($product['post_title']);
          $posted_data = array(
              'products_id_old' => $product['ID'],
              'category_id' => '1',
              'category_links' => '1',
              'friendly_url' => $this->cbk_friendly_url,
              'product_name' => $product['post_title'],
              'product_code' => '',
              'hsn_code' => '',
              'product_price' => $price,
              'product_discounted_price' => $dprice,
              'product_qty' => '100',
              'specification' => '',
              'short_desc' => '',
              'product_alt' => $product['post_title'],
              'product_gst' => 0,
              'products_description' => $product['post_content'],
              'product_added_date' => $this->config->item('config.date.time')
          );
          trace($posted_data);
          //exit;
          $productId = 0; //$this->product_model->safe_insert('wps_products', $posted_data, FALSE);
          if ($productId > 0) {
            //product images
            $is_default = 'Y';
            foreach ($product['taxonomyMeta'] as $img) {
              $fl = explode('/', $img['guid']);
              $fl = array_reverse($fl);
              $filename = $fl[0];
              //get File content and save to destination path
              $blob = file_get_contents($img['guid']);
              $image = base64_encode($blob);
              $dataImg = base64_decode($image);
              //echo '<img src="data:image/jpg;base64,'.$image.'">';
              $success = file_put_contents(UPLOAD_DIR . '/products/' . $filename, $dataImg);
              if ($success) {
                $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';
              }
            }

            //Create Meta
            $redirect_url = "products/detail";
            $title = $product['post_title'];
            $description = '';
            $keywords = '';
            $meta_array = array(
                'entity_type' => $redirect_url,
                'entity_id' => $productId,
                'page_url' => $this->cbk_friendly_url,
                'meta_title' => $title,
                'meta_description' => $description,
                'meta_keyword' => $keywords
            );
            //create_meta($meta_array);
          }
          //exit;
        }
      }
    }
  }

  public function migrateUsers() {
    $this->db2 = $this->load->database('wp', TRUE);
    $res = $this->db2->query("SELECT * FROM wp_users WHERE is_migrate = '0' ORDER BY ID DESC LIMIT 0, 100")->result_array();
    $resp = array();
    $sl = 0;
    foreach ($res as $user) {
      $txonomy = $this->db2->query("SELECT * FROM wp_usermeta WHERE user_id = '" . $user['ID'] . "'")->result_array();
      if (is_array($txonomy) && !empty($txonomy)) {
        $resp[$sl] = $user;
        $resp[$sl]['taxonomy'] = $txonomy;

        $sl++;
      }
    }

    //trace($resp);
    //exit;
    if (is_array($resp) && !empty($resp)) {
      foreach ($resp as $user) {

        $firstName = $lastName = $phone = $bilFirstName = $bilLastName = $bilMobile = $bilAddress = $bilCity = $bilState = $bilCode = $bilCountry = $shipFirstName = $shipLastName = $shipMobile = $shipAddress = $shipCity = $shipState = $shipCode = $shipCountry = "";
        foreach ($user['taxonomy'] as $um) {
          if ($um['meta_key'] == '_first_name') {
            $shipFirstName = $um['meta_value'];
          }
          if ($um['meta_key'] == '_last_name') {
            $shipLastName = $um['meta_value'];
          }
          if ($um['meta_key'] == '_country') {
            $shipCountry = $um['meta_value'];
          }
          if ($um['meta_key'] == '_address_1') {
            $shipAddress = $um['meta_value'];
          }
          if ($um['meta_key'] == '_city') {
            $shipCity = $um['meta_value'];
          }
          if ($um['meta_key'] == '_state') {
            $shipState = $um['meta_value'];
          }
          if ($um['meta_key'] == '_postcode') {
            $shipCode = $um['meta_value'];
          }
          if ($um['meta_key'] == 'first_name') {
            $firstName = $um['meta_value'];
          }
          if ($um['meta_key'] == 'last_name') {
            $lastName = $um['meta_value'];
          }
          if ($um['meta_key'] == 'billing_phone') {
            $bilMobile = $phone = $um['meta_value'];
          }
          if ($um['meta_key'] == 'billing_first_name') {
            $bilFirstName = $um['meta_value'];
          }
          if ($um['meta_key'] == 'billing_last_name') {
            $bilLastName = $um['meta_value'];
          }
          if ($um['meta_key'] == 'billing_address_1') {
            $bilAddress = $um['meta_value'];
          }
          if ($um['meta_key'] == 'billing_city') {
            $bilCity = $um['meta_value'];
          }
          if ($um['meta_key'] == 'billing_state') {
            $bilState = $um['meta_value'];
          }
          if ($um['meta_key'] == 'billing_postcode') {
            $bilCode = $um['meta_value'];
          }
          if ($um['meta_key'] == 'billing_country') {
            $bilCountry = $um['meta_value'];
          }
        }

        //insert data in table
        $password = md5('user@Beziddi21');
        $register_array = array(
            'customers_id_old' => $user['ID'],
            'user_name' => $user['user_login'],
            'password' => $password,
            'first_name' => $firstName,
            'last_name' => $lastName,
            'mobile_number' => $phone,
            'email' => $user['user_email'],
            'actkey' => md5($this->input->post('user_login', TRUE)),
            'account_created_date' => $user['user_registered'],
            'current_login' => $user['user_registered'],
            'status' => '1',
            'is_verified' => '1',
            'ip_address' => $this->input->ip_address()
        );
        trace($register_array);
        $insId = $this->product_model->safe_insert('wps_customers', $register_array, FALSE);
        if ($insId > 0) {
          $add_array_bill = array(
              'customer_id' => $insId,
              'first_name' => $bilFirstName,
              'last_name' => $bilLastName,
              'mobile' => $bilMobile,
              'address' => $bilAddress,
              'city' => $bilCity,
              'state' => $bilState,
              'country' => $bilCountry,
              'zipcode' => $bilCode,
              'reciv_date' => $user['user_registered'],
              'address_type' => 'Bill',
              'default_status' => 'N'
          );
          $add_array_ship = array(
              'customer_id' => $insId,
              'first_name' => $shipFirstName,
              'last_name' => $shipLastName,
              'mobile' => $shipMobile,
              'address' => $shipAddress,
              'city' => $shipCity,
              'state' => $shipState,
              'country' => $shipCountry,
              'zipcode' => $shipCode,
              'reciv_date' => $user['user_registered'],
              'address_type' => 'Ship',
              'default_status' => 'N'
          );
          $this->product_model->safe_insert('wps_customers_address_book', $add_array_bill, FALSE);
          $this->product_model->safe_insert('wps_customers_address_book', $add_array_ship, FALSE);

          trace($add_array_bill);
          trace($add_array_ship);
          
          $this->db2->query("UPDATE wp_users SET is_migrate = '1' WHERE ID = '".$user['ID']."'");
        }
      }
    }
  }

}

/* End of file member.php */
/* Location: .application/modules/products/controllers/products.php */