<?php

class Products extends Admin_Controller {

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

  public function index($page = NULL) {
    $this->load->helper(array('products/product'));
    $condtion = array();
    $pagesize = (int) $this->input->get_post('pagesize');
    $config['limit'] = ( $pagesize > 0 ) ? $pagesize : $this->config->item('pagesize');
    $offset = ( $this->input->get_post('per_page') > 0 ) ? $this->input->get_post('per_page') : 0;
    $base_url = current_url_query_string(array('filter' => 'result'), array('per_page'));
    $category_id = (int) $this->uri->segment(4, 0);
    $status = $this->input->get_post('status', TRUE);

    if ($this->input->post('update_order') != '') {
      $this->update_displayOrder('wps_products', 'product_qty', 'products_id');
      $this->session->set_flashdata('success', 'Quantity has been updated');
    }

    if ($this->input->post('update_price') != '') {
      $this->update_displayPrice('wps_products', 'product_price', 'products_id');
      $this->update_displayDiscountPrice('wps_products', 'product_discounted_price', 'products_id');
      $this->session->set_flashdata('success', 'Price has been updated');
    }

    $cat_name = '';
    if ($category_id > 0) {
      $condtion['category_id'] = $category_id;
      $cat_name = 'in ';
      $cat_name .= get_db_field_value('wps_categories', 'category_name', "WHERE category_id='$category_id'");
    }
    if ($status != '') {
      $condtion['status'] = $status;
    }
    $condtion['orderby'] = 'wlp.products_id desc';
    //----------------start searching and sorting----------------- 
    //Sorting
    $sort = $this->input->get('sort');
    if ($sort > 0) {
      if ($sort == 8) {//Min Sold Products
        $condtion['orderby'] = 'wlp.products_sold ASC';
      }
      if ($sort == 7) {//Max sold Products
        $condtion['orderby'] = 'wlp.products_sold DESC';
      }
      if ($sort == 6) {//Min Popular Products
        $condtion['orderby'] = 'wlp.products_viewed ASC';
      }
      if ($sort == 5) {//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';
    }

    //Filter
    //$type = $this->uri->segment(1);
    $type = $this->input->get('type');

    if ($type != "") {
      if ($type == 'latest') {
        $condtion['newarrival_product'] = '1';
        $page_title = "Latest Products";
      }
      if ($type == 'best-seller') {
        $condtion['bestseller'] = '1';
        $page_title = "Best Seller Products";
      }
      if ($type == 'popular') {
        $condtion['popular_product'] = '1';
        $page_title = "Popular Products";
      }
      if ($type == 'new-arrival') {
        $condtion['newarrival'] = '1';
        $page_title = "New Arrival Products";
      }
    }

    $color = $this->input->get('color');
    $size = $this->input->get('size');
    $price = $this->input->get('price');
    $category_ids = $this->input->get('category_id');
    $brand = $this->input->get('brand');
    $style = $this->input->get('style');
    $room = $this->input->get('room');

    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 (!empty($brand)) {
      $brand = implode(',', $brand);
      $condtion['brand'] = $brand;
    }
    if (!empty($style)) {
      $style = implode(',', $style);
      $condtion['style'] = $style;
    }
    if (!empty($room)) {
      $room = implode(',', $room);
      $condtion['room'] = $room;
    }
    if ($category_ids > 0) {
      $condtion['category_ids'] = $category_ids;
    }

    if ($category_id > 0) {
      $condtion['category_id'] = $category_id;
      $cat_res = get_db_single_row('wps_categories', '*', " category_id='$category_id'");
      $page_title = $cat_res['category_name'];
    }
    $data['catid'] = '';
    $res_array22 = $this->product_model->get_products($config['limit'], $offset, $condtion);
    //echo_sql();
    /* Available Color Records */
    $color_cond_config = array(
        'condition' => " AND status='1' ",
        'order' => 'color_name '
    );
    $colors = $this->color_model->getcolors($color_cond_config);
    $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;
    /* Available Category Records */
    $size_categorycond_config = array(
        'condition' => " AND status='1' ",
        'order' => 'category_name '
    );
    $categories = $this->category_model->getcategory($size_categorycond_config);
    $data['categories'] = $categories;
    /* Available Brand Records */
    $size_brandcond_config = array(
        'condition' => " AND status='1' ",
        'order' => 'brand_name '
    );
    $brands = $this->brand_model->getbrands($size_brandcond_config);
    $data['brands'] = $brands;

    /* Available Style Records */
    $size_stylecond_config = array(
        'condition' => " AND status='1' ",
        'order' => 'style_name '
    );
    $styles = $this->style_model->getstyles($size_stylecond_config);
    $data['styles'] = $styles;

    /* Available Room Records */
    $data['total_rows'] = $data['total_list_rows'] = $config['total_rows'] = get_found_rows();
    if (!empty($page_title)) {
      $data['headingTitle'] = $page_title;
    } else {
      $data['headingTitle'] = 'Products List';
    }
    $data['products'] = $res_array22;
    //--------end searching and sorting--------------
    $res_array = $this->product_model->get_products($config['limit'], $offset, $condtion);
    $config['total_rows'] = get_found_rows();
    $data['paging'] = dashboard_pagination($base_url, $config['total_rows'], $config['limit'], $offset);
    $data['res'] = $res_array;
    if ($this->input->post('action') != '') {
      if ($this->input->post('action') == 'Delete') {
        $prod_id = $this->input->post('arr_ids');
        foreach ($prod_id as $v) {
          $where = array('entity_type' => 'products/detail', 'entity_id' => $v);
          $this->product_model->safe_delete('wps_meta_tags', $where, TRUE);
        }
      }
      /* Product set as a */
      if ($this->input->post('set_as') != '') {

        $set_as = $this->input->post('set_as', TRUE);
        $this->set_as('wps_products', 'products_id', array($set_as => '1'));
      }
      if ($this->input->post('unset_as') != '') {
        $unset_as = $this->input->post('unset_as', TRUE);
        $this->set_as('wps_products', 'products_id', array($unset_as => '0'));
      }
      /* End product set as a */
      $this->session->set_flashdata('success', lang('deleted'));
      $this->update_status('wps_products', 'products_id');
    }

    /* upload Bulk Excel */
    if ($this->input->post('action1') == 'submit_excel') {
      $this->form_validation->set_rules('excel_file', 'Upload Excel File', 'trim|file_allowed_type[document]|callback_check_upload_excel');
      if ($this->form_validation->run() == TRUE) {

        require_once FCPATH . 'apps/third_party/Excel/reader.php';
        $data = new Spreadsheet_Excel_Reader();
        $data->setOutputEncoding('CP1251');

        //$data->setUTFEncoder('');
        chmod($_FILES["excel_file"]["tmp_name"], 0777);
        $data->read($_FILES["excel_file"]["tmp_name"]);
        $worksheet = $data->sheets[0]['cells'];

        $process_add = $this->product_model->add_bulk_upload_product($worksheet);
        // echo "sss";
        // exit; 
        if ($process_add === TRUE) {
          $this->session->set_userdata(array('msg_type' => 'success'));
          $this->session->set_flashdata('success', 'Excel file inserted successfully!!!');
          redirect('sitepanel/products', '');
        } else {
          $this->form_validation->_error_array['image'] = 'Uploading Failed. Please Try Again';
        }
      } else {
        echo "error";
        validation_message();
        exit;
      }
    }


    $data['category_result_found'] = "Total " . $config['total_rows'] . " result(s) found " . strtolower($cat_name) . " ";

    //Call of View
    $this->load->view('products/view_product_list', $data);
  }

  public function add() {
    $data['headingTitle'] = 'Add Product';
    $categoryposted = $this->input->post('catid');
    $data['categoryposted'] = $categoryposted;
    $data['ckeditor1'] = set_ck_config(array('textarea_id' => 'description')); //'type' => 'basic'
    $data['ckeditor2'] = set_ck_config(array('textarea_id' => 'specification'));

    $this->form_validation->set_rules('product_name', 'Product Name', "required|unique[wps_products.product_name='" . $this->db->escape_str($this->input->post('product_name')) . "' AND status!='2']");
    $this->form_validation->set_rules('product_code', 'Product Code', "trim|max_length[65]|unique[wps_products.product_code='" . $this->db->escape_str($this->input->post('product_code')) . "' AND status!='2']");
    $this->form_validation->set_rules('product_price', 'Price', 'trim|required|is_valid_amount|numeric|greater_than[0]');
    $this->form_validation->set_rules('description', 'Product Description', 'required|trim');
    $this->form_validation->set_rules('category_id[]', 'Product Category', 'trim|required');
    $this->form_validation->set_rules('color_id[]', 'Color', "trim");
    $this->form_validation->set_rules('size_id[]', 'Size', "trim");
    $this->form_validation->set_rules('product_qty', 'Quantity', "trim|required|numeric");
    $this->form_validation->set_rules('product_gst', 'Product GST', "");
    if (empty($_FILES['img1']['name'])) {
      $this->form_validation->set_rules('img1', 'Product Main Image', 'required|file_allowed_type[image]');
    }
    $this->form_validation->set_rules('img2', 'Product Additional Image', 'file_allowed_type[image]');
    $this->form_validation->set_rules('img3', 'Product Additional Image', 'file_allowed_type[image]');
    $this->form_validation->set_rules('img4', 'Product Additional Image', 'file_allowed_type[image]');
    $this->form_validation->set_rules('img5', 'Product Additional Image', 'file_allowed_type[image]');
    $this->form_validation->set_rules('img6', 'Product Additional Image', 'file_allowed_type[image]');
    $this->form_validation->set_rules('img7', 'Product Additional Image', 'file_allowed_type[image]');
    $this->form_validation->set_rules('img8', 'Product Additional Image', 'file_allowed_type[image]');
    $this->check_price();
    //echo "<pre>";print_r($_POST);die;
    if ($this->form_validation->run() === TRUE) {

      $pic1 = '';
      if (!empty($_FILES) && $_FILES['img1']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/products/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img1');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic1 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $pic2 = '';
      if (!empty($_FILES) && $_FILES['img2']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/products/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img2');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic2 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $pic3 = '';
      if (!empty($_FILES) && $_FILES['img3']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/products/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img3');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic3 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $pic4 = '';
      if (!empty($_FILES) && $_FILES['img4']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/products/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img4');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic4 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $pic5 = '';
      if (!empty($_FILES) && $_FILES['img5']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/products/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img5');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic5 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $pic6 = '';
      if (!empty($_FILES) && $_FILES['img6']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/products/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img6');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic6 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $pic7 = '';
      if (!empty($_FILES) && $_FILES['img7']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/products/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img7');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic7 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $pic8 = '';
      if (!empty($_FILES) && $_FILES['img8']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/products/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img8');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic8 = $uploaded_data['upload_data']['file_name'];
        }
      }
      //cat links
      $postCategory = $this->input->post('category_id');
      $category_links = "";
      $catlink = $ctl = "";
      foreach ($postCategory as $ctv) {
        $catlink = get_parent_categories($ctv, "AND status='1'", "category_id,parent_id");
        $ctl = array_keys($catlink);
        $category_links .= implode(",", $ctl) . ',';
      }
      $category_links = substr($category_links, 0, -1);

      //size
      $posted_size_id = $this->input->post('size_id');
      $posted_size_id = !is_array($posted_size_id) ? array() : $posted_size_id;
      $size_ids = implode(",", $posted_size_id);
      //color
      $posted_color_id = $this->input->post('color_id');
      $posted_color_id = !is_array($posted_color_id) ? array() : $posted_color_id;
      $color_ids = implode(",", $posted_color_id);
      //brand
      $posted_brand_id = $this->input->post('brand_id');
      $posted_brand_id = !is_array($posted_brand_id) ? array() : $posted_brand_id;
      $brand_ids = implode(",", $posted_brand_id);
      //$brand_ids = $this->input->post('brand_id');
      //MAJOR color
      $posted_majorcolor_id = $this->input->post('majorcolor_id');
      $posted_majorcolor_id = !is_array($posted_majorcolor_id) ? array() : $posted_majorcolor_id;
      $majorcolor_ids = implode(",", $posted_majorcolor_id);
      //Styles
      $posted_style_id = $this->input->post('style_id');
      $posted_style_id = !is_array($posted_style_id) ? array() : $posted_style_id;
      $style_ids = implode(",", $posted_style_id);
      //Rooms    
      $posted_room_id = $this->input->post('room_id');
      $posted_room_id = !is_array($posted_room_id) ? array() : $posted_room_id;
      $room_ids = implode(",", $posted_room_id);

      $this->cbk_friendly_url = seo_url_title($this->input->post('product_name'));

      $posted_data = array(
          'category_id' => implode(',', $this->input->post('category_id')),
          'category_links' => $category_links,
          'friendly_url' => $this->cbk_friendly_url,
          'product_name' => $this->input->post('product_name', TRUE),
          'product_code' => $this->input->post('product_code', TRUE),
          'hsn_code' => $this->input->post('hsn_code', TRUE),
          'product_price' => $this->input->post('product_price', TRUE),
          'product_qty' => $this->input->post('product_qty', TRUE),
          'color_ids' => $color_ids,
          'majorcolor_ids' => $majorcolor_ids,
          'size_ids' => $size_ids,
          'brand_id' => $brand_ids,
          'style_id' => $style_ids,
          'room_id' => $room_ids,
          'specification' => $this->input->post('specification', TRUE),
          'short_desc' => $this->input->post('short_desc', TRUE),
          'product_alt' => $this->input->post('product_name'),
          'product_gst' => $this->input->post('product_gst'),
          'products_description' => $this->input->post('description'),
          //'youtube_id' => $this->input->post('youtube_id', TRUE),
          'product_added_date' => $this->config->item('config.date.time')
      );
      //trace($posted_data); exit;
      $productId = $this->product_model->safe_insert('wps_products', $posted_data, FALSE);
      if ($productId > 0) {
        $this->cbk_friendly_url = seo_url_title($this->input->post('product_name'));

        //update friendly_url
        $this->db->query("UPDATE wps_products SET friendly_url = '" . $this->cbk_friendly_url . "' WHERE products_id = '" . $productId . "'");

        //add images to table
        $is_default = 'Y';
        if ($pic1) {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic1 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($pic2) {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic2 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($pic3) {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic3 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($pic4) {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic4 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($pic5) {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic5 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($pic6) {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic6 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($pic7) {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic7 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        if ($pic8) {
          $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic8 . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = '" . $is_default . "'");
          $is_default = 'N';
        }
        //End
        //Create Meta
        $redirect_url = "products/detail";
        if ($this->input->get_post('metaTitle') != '') {
          $title = $this->input->get_post('metaTitle');
          $description = $this->input->get_post('metaDescription');
          $keywords = $this->input->get_post('metaKeyword');
        } else {
          $title = $this->input->post('product_name');
          $description = $this->input->post('product_name');
          $keywords = $this->input->post('product_name');
        }
        $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);
      }
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', lang('success'));
      redirect('wps-admin/products/index/' . $this->input->post('category_id'), '');
    }

    /* Available Color Records */
    $color_cond_config = array(
        'condition' => " AND status='1' ",
        'order' => 'color_name '
    );
    $colors = $this->color_model->getcolors($color_cond_config);
    $data['colors'] = $colors;
    //* Available Major Color */
    $mjrcolor_cond_config = array(
        'condition' => " AND status='1' ",
        'order' => 'color_name ',
        'color_type' => 'majorcolor'
    );
    //$this->load->model('MY_Model');
    //$this->load->model('model_name', 'foobar');
    $majorcolors = $this->db->query("select * from wps_colors where color_type='majorcolor'")->result_array();
    $data['majorcolors'] = $majorcolors;
    /* Available Size Records */
    $size_cond_config = array(
        'condition' => " AND status='1' ",
    );
    $sizes = $this->size_model->getsizes($size_cond_config);
    $data['sizes'] = $sizes;
    /* Available Brand Records */
    $brand_cond_config = array(
        'condition' => " AND status='1' ",
    );
    $brands = $this->brand_model->getbrands($brand_cond_config);
    $data['brands'] = $brands;
    /* Available Styles Records */
    $style_cond_config = array(
        'condition' => " AND status='1' ",
    );
    $styles = $this->style_model->getstyles($style_cond_config);
    $data['styles'] = $styles;

    //echo "<pre>";print_r($data);die;
    $this->load->view('products/view_product_add', $data);
  }

  public function edit($productId) {
    $data['headingTitle'] = 'Edit Product';
    $productId = (int) $this->uri->segment(4);
    $option = array('productid' => $productId);
    $res = $this->product_model->get_products(1, 0, $option);
    //echo_sql();
    $data['ckeditor1'] = set_ck_config(array('textarea_id' => 'description'));
    $data['ckeditor2'] = set_ck_config(array('textarea_id' => 'specification'));
    //image validation
    $img_allow_size = $this->config->item('allow.file.size');
    $img_allow_dim = $this->config->item('allow.imgage.dimension');

    $this->cbk_friendly_url = seo_url_title($this->input->post('friendly_url'));

    $media = array();

    if (is_array($res) && !empty($res)) {
      $res = $res[0];
      $media = $this->product_model->get_product_media(8, 0, array('productid' => $res['products_id']));

      $this->form_validation->set_rules('product_name', 'Product Name', "required");
      //$this->form_validation->set_rules('product_name', 'Product Name', "required");

      $this->form_validation->set_rules('friendly_url', 'Product URL', "trim|max_length[120]|unique[wps_products.friendly_url='" . $this->db->escape_str($this->input->post('friendly_url')) . "' AND status!='2' AND products_id != '" . $res['products_id'] . "']");

      $this->form_validation->set_rules('product_code', 'Product Code', "trim|max_length[65]|unique[wps_products.product_code='" . $this->db->escape_str($this->input->post('product_code')) . "' AND status!='2' AND products_id != '" . $res['products_id'] . "']");

      $this->form_validation->set_rules('product_price', 'Price', 'trim|required|is_valid_amount|numeric|greater_than[0]');
      $this->form_validation->set_rules('description', 'Product Description', 'trim');
      $this->form_validation->set_rules('category_id[]', 'Product Category', 'trim|required');
      $this->form_validation->set_rules('color_id[]', 'Color', "trim");
      $this->form_validation->set_rules('size_id[]', 'Size', "trim");
      $this->form_validation->set_rules('product_qty', 'Quantity', "trim|required|numeric");
      $this->form_validation->set_rules('product_gst', 'Product Gst', "");
      // $this->form_validation->set_rules('browsed_image', 'Browsed Image', "trim");
      $this->form_validation->set_rules('img1', 'Product Main Image', 'file_allowed_type[image]');
      $this->form_validation->set_rules('img2', 'Product Additional Image', 'file_allowed_type[image]');
      $this->form_validation->set_rules('img3', 'Product Additional Image', 'file_allowed_type[image]');
      $this->form_validation->set_rules('img4', 'Product Additional Image', 'file_allowed_type[image]');
      $this->form_validation->set_rules('img5', 'Product Additional Image', 'file_allowed_type[image]');
      $this->form_validation->set_rules('img6', 'Product Additional Image', 'file_allowed_type[image]');
      $this->form_validation->set_rules('img7', 'Product Additional Image', 'file_allowed_type[image]');
      $this->form_validation->set_rules('img8', 'Product Additional Image', 'file_allowed_type[image]');

      if ($this->form_validation->run() == TRUE) {

        $media1 = (isset($media[0]['media'])) ? $media[0]['id'] : '';
        $media2 = (isset($media[1]['media'])) ? $media[1]['id'] : '';
        $media3 = (isset($media[2]['media'])) ? $media[2]['id'] : '';
        $media4 = (isset($media[3]['media'])) ? $media[3]['id'] : '';
        $media5 = (isset($media[4]['media'])) ? $media[4]['id'] : '';
        $media6 = (isset($media[5]['media'])) ? $media[5]['id'] : '';
        $media7 = (isset($media[6]['media'])) ? $media[6]['id'] : '';
        $media8 = (isset($media[7]['media'])) ? $media[7]['id'] : '';

        $mediaFile1 = (isset($media[0]['media'])) ? $media[0]['media'] : '';
        $mediaFile2 = (isset($media[1]['media'])) ? $media[1]['media'] : '';
        $mediaFile3 = (isset($media[2]['media'])) ? $media[2]['media'] : '';
        $mediaFile4 = (isset($media[3]['media'])) ? $media[3]['media'] : '';
        $mediaFile5 = (isset($media[4]['media'])) ? $media[4]['media'] : '';
        $mediaFile6 = (isset($media[5]['media'])) ? $media[5]['media'] : '';
        $mediaFile7 = (isset($media[6]['media'])) ? $media[6]['media'] : '';
        $mediaFile8 = (isset($media[7]['media'])) ? $media[7]['media'] : '';

        $pic1 = $mediaFile1;
        $unlink_image1 = array('source_dir' => "products", 'source_file' => $mediaFile1);
        if (!empty($_FILES) && $_FILES['img1']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/products/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('img1');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $pic1 = $uploaded_data['upload_data']['file_name'];
            removeImage($unlink_image1);
            if ($mediaFile1) {
              $this->db->query("UPDATE wps_products_media SET media = '" . $pic1 . "' WHERE products_id = '" . $productId . "' AND id = '" . $media1 . "'");
            } else {
              $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic1 . "', products_id = '" . $productId . "'");
            }
          }
        }


        $pic2 = $mediaFile2;
        $unlink_image2 = array('source_dir' => "products", 'source_file' => $mediaFile2);
        if (!empty($_FILES) && $_FILES['img2']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/products/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('img2');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $pic2 = $uploaded_data['upload_data']['file_name'];
            removeImage($unlink_image2);
            if ($mediaFile2) {
              $this->db->query("UPDATE wps_products_media SET media = '" . $pic2 . "' WHERE products_id = '" . $productId . "' AND id = '" . $media2 . "'");
            } else {
              $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic2 . "', products_id = '" . $productId . "'");
            }
          }
        }

        $pic3 = $mediaFile3;
        $unlink_image3 = array('source_dir' => "products", 'source_file' => $mediaFile3);
        if (!empty($_FILES) && $_FILES['img3']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/products/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('img3');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $pic3 = $uploaded_data['upload_data']['file_name'];
            removeImage($unlink_image3);
            if ($mediaFile3) {
              $this->db->query("UPDATE wps_products_media SET media = '" . $pic3 . "' WHERE products_id = '" . $productId . "' AND id = '" . $media3 . "'");
            } else {
              $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic3 . "', products_id = '" . $productId . "'");
            }
          }
        }

        $pic4 = $mediaFile4;
        $unlink_image4 = array('source_dir' => "products", 'source_file' => $mediaFile4);
        if (!empty($_FILES) && $_FILES['img4']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/products/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('img4');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $pic4 = $uploaded_data['upload_data']['file_name'];
            removeImage($unlink_image4);
            if ($mediaFile4) {
              $this->db->query("UPDATE wps_products_media SET media = '" . $pic4 . "' WHERE products_id = '" . $productId . "' AND id = '" . $media4 . "'");
            } else {
              $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic4 . "', products_id = '" . $productId . "'");
            }
          }
        }

        $pic5 = $mediaFile5;
        $unlink_image5 = array('source_dir' => "products", 'source_file' => $mediaFile5);
        if (!empty($_FILES) && $_FILES['img5']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/products/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('img5');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $pic5 = $uploaded_data['upload_data']['file_name'];
            removeImage($unlink_image5);
            if ($mediaFile5) {
              $this->db->query("UPDATE wps_products_media SET media = '" . $pic5 . "' WHERE products_id = '" . $productId . "' AND id = '" . $media5 . "'");
            } else {
              $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic5 . "', products_id = '" . $productId . "'");
            }
          }
        }

        $pic6 = $mediaFile6;
        $unlink_image6 = array('source_dir' => "products", 'source_file' => $mediaFile6);
        if (!empty($_FILES) && $_FILES['img6']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/products/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('img6');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $pic6 = $uploaded_data['upload_data']['file_name'];
            removeImage($unlink_image6);
            if ($mediaFile6) {
              $this->db->query("UPDATE wps_products_media SET media = '" . $pic6 . "' WHERE products_id = '" . $productId . "' AND id = '" . $media6 . "'");
            } else {
              $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic6 . "', products_id = '" . $productId . "'");
            }
          }
        }

        $pic7 = $mediaFile7;
        $unlink_image7 = array('source_dir' => "products", 'source_file' => $mediaFile7);
        if (!empty($_FILES) && $_FILES['img7']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/products/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('img7');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $pic7 = $uploaded_data['upload_data']['file_name'];
            removeImage($unlink_image7);
            if ($mediaFile7) {
              $this->db->query("UPDATE wps_products_media SET media = '" . $pic7 . "' WHERE products_id = '" . $productId . "' AND id = '" . $media7 . "'");
            } else {
              $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic7 . "', products_id = '" . $productId . "'");
            }
          }
        }

        $pic8 = $mediaFile8;
        $unlink_image8 = array('source_dir' => "products", 'source_file' => $mediaFile8);
        if (!empty($_FILES) && $_FILES['img8']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/products/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('img8');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $pic8 = $uploaded_data['upload_data']['file_name'];
            removeImage($unlink_image8);
            if ($mediaFile8) {
              $this->db->query("UPDATE wps_products_media SET media = '" . $pic8 . "' WHERE products_id = '" . $productId . "' AND id = '" . $media8 . "'");
            } else {
              $this->db->query("INSERT INTO wps_products_media SET media = '" . $pic8 . "', products_id = '" . $productId . "'");
            }
          }
        }


        //cat links
        $postCategory = $this->input->post('category_id');
        $category_links = "";
        $catlink = $ctl = "";
        foreach ($postCategory as $ctv) {
          $catlink = get_parent_categories($ctv, "AND status='1'", "category_id,parent_id");
          $ctl = array_keys($catlink);
          $category_links .= implode(",", $ctl) . ',';
        }
        $category_links = substr($category_links, 0, -1);

        //size
        $posted_size_id = $this->input->post('size_id');
        $posted_size_id = !is_array($posted_size_id) ? array() : $posted_size_id;
        $size_ids = implode(",", $posted_size_id);
        //color
        $posted_color_id = $this->input->post('color_id');
        $posted_color_id = !is_array($posted_color_id) ? array() : $posted_color_id;
        $color_ids = implode(",", $posted_color_id);
        //brand
        // $posted_brand_id = $this->input->post('brand_id');
        // $posted_brand_id = !is_array($posted_brand_id) ? array() : $posted_brand_id;
        // $brand_ids = implode(",", $posted_brand_id);
        $brand_ids = $this->input->post('brand_id');

        //majr color
        $posted_majorcolor_id = $this->input->post('majorcolor_ids');
        $posted_majorcolor_id = !is_array($posted_majorcolor_id) ? array() : $posted_majorcolor_id;
        $majorcolor_ids = implode(",", $posted_majorcolor_id);
        //Styles
        $posted_style_id = $this->input->post('style_id');
        $posted_style_id = !is_array($posted_style_id) ? array() : $posted_style_id;
        $style_ids = implode(",", $posted_style_id);
        //Rooms
        $posted_room_id = $this->input->post('room_id');
        $posted_style_id = !is_array($posted_room_id) ? array() : $posted_room_id;
        $room_ids = implode(",", $posted_room_id);
        $posted_data = array(
            'category_id' => implode(',', $this->input->post('category_id')),
            'category_links' => $category_links,
            'friendly_url' => $this->cbk_friendly_url,
            'product_name' => $this->input->post('product_name', TRUE),
            'product_code' => $this->input->post('product_code', TRUE),
            'hsn_code' => $this->input->post('hsn_code', TRUE),
            'product_price' => $this->input->post('product_price', TRUE),
            'product_qty' => $this->input->post('product_qty', TRUE),
            'color_ids' => $color_ids,
            'majorcolor_ids' => $majorcolor_ids,
            'size_ids' => $size_ids,
            'brand_id' => $brand_ids,
            'style_id' => $style_ids,
            'room_id' => $room_ids,
            'short_desc' => $this->input->post('short_desc', TRUE),
            'specification' => $this->input->post('specification', TRUE),
            'product_alt' => $this->input->post('product_name'),
            'products_description' => $this->input->post('description'),
            'product_gst' => $this->input->post('product_gst'),
            //'youtube_id' => $this->input->post('youtube_id', TRUE),
            'product_updated_date' => $this->config->item('config.date.time')
        );
        //trace($posted_data); exit;
        $where = "products_id = '" . $res['products_id'] . "'";
        $this->product_model->safe_update('wps_products', $posted_data, $where, FALSE);

        if ($this->input->get_post('metaTitle') != '') {
          $title = $this->input->get_post('metaTitle');
          $description = $this->input->get_post('metaDescription');
          $keywords = $this->input->get_post('metaKeyword');
        } else {
          $title = $this->input->post('product_name');
          $description = $this->input->post('product_name');
          $keywords = $this->input->post('product_name');
        }
        $posted_data_meta = array(
            'meta_title' => $title,
            'meta_description' => $description,
            'meta_keyword' => $keywords,
            'page_url' => $this->cbk_friendly_url,
        );
        $this->db->where('entity_id', $res['products_id']);
        $this->db->where('entity_type', 'products/detail');
        $this->db->update('wps_meta_tags', $posted_data_meta);

        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', lang('successupdate'));
        if ($this->input->post('category_id') > 0) {
          redirect('wps-admin/products/index/' . $this->input->post('category_id'), '');
        } else {
          redirect('wps-admin/products/' . query_string(), '');
        }
      }

      /* Available Color Records */
      $color_cond_config = array(
          'condition' => " AND status='1' ",
          'order' => 'color_name '
      );
      $colors = $this->color_model->getcolors($color_cond_config);
      $data['colors'] = $colors;
      //Available Major Color Records
      $majorcolors = $this->db->query("select * from wps_colors where color_type='majorcolor'")->result_array();
      $data['majorcolors'] = $majorcolors;
      /* 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;
      /* Available Brand Records */
      $brand_cond_config = array(
          'condition' => " AND status='1' ",
          'order' => 'brand_name '
      );
      $brands = $this->brand_model->getbrands($brand_cond_config);
      $data['brands'] = $brands;
      /* Available Styles Records */
      $style_cond_config = array(
          'condition' => " AND status='1' ",
          'order' => 'style_name'
      );
      $styles = $this->style_model->getstyles($style_cond_config);
      $data['styles'] = $styles;

      $metaDets = get_db_single_row("wps_meta_tags", "meta_title, meta_description, meta_keyword", "entity_type = 'products/detail' AND entity_id = '" . $res['products_id'] . "'");
      $data['metaDets'] = $metaDets;
      $data['media_res'] = $media;
      $data['res'] = $res;
      $media_option = array('productid' => $res['products_id']);
      $res_photo_media = $this->product_model->get_product_media(5, 0, $media_option);
      $data['res_photo_media'] = $res_photo_media;
      //echo '<pre>';print_r($data);die;
      $this->load->view('products/view_product_edit', $data);
    } else {
      redirect('wps-admin/products', '');
    }
  }

  public function check_price() {
    $disc_price = $this->input->post('product_discounted_price');
    $price = $this->input->post('product_price');
    if ($disc_price != '' && $price != '') {
      $disc_price = floatval($disc_price);
      $price = floatval($price);
      if ($disc_price >= $price && $disc_price > 0 && $price > 0) {
        $this->form_validation->set_message('check_price', 'Discount price must be less than actual price.');
        return FALSE;
      } else {
        return TRUE;
      }
    } else {
      return TRUE;
    }
  }

  public function check_upload_excel() {
    $filearrext = array('xls');
    if ($_FILES['excel_file']['name'] == '') {
      $this->form_validation->set_message('check_upload_excel', 'Please upload excel file.');
      return FALSE;
    }
    if ($_FILES['excel_file']['name'] != '') {
      $extension = substr(strrchr($_FILES['excel_file']['name'], '.'), 1);
      if (!in_array($extension, $filearrext)) {
        $this->form_validation->set_message('check_upload_excel', 'Please upload (xls) file only.');
        return FALSE;
      } else {
        return TRUE;
      }
    }
  }

  public function view_stocks() {
    $productId = (int) $this->uri->segment(4);
    $option = array('productid' => $productId);
    $res = $this->db->select('products_id,size_ids')->from('wps_products')->where(['products_id' => $productId])->get()->row_array();
    //echo '<pre>'; print_r($res); exit();
    if (is_array($res)) {

      if ($this->input->post('sub') != '') {


        $this->db->query("DELETE FROM wps_product_attributes WHERE product_id='" . $this->input->post('product') . "'");


        $sizeid = $this->input->post('size');
        $product_id = $this->input->post('product_id');
        $product_price = $this->input->post('product_price');
        $product_discounted_price = $this->input->post('product_discounted_price');
        $quantity = $this->input->post('quantity');
        for ($i = 0; $i < sizeof($sizeid); $i++) {
          $data_insert = array(
              'product_id' => $product_id[$i],
              'size_id' => $sizeid[$i],
              'color_id' => 0,
              'product_price' => $product_price[$i],
              'product_discounted_price' => $product_discounted_price[$i],
              'quantity' => $quantity[$i],
          );
          //echo '<pre>'; print_r($data_insert);
          $this->db->insert('wps_product_attributes', $data_insert);
        }

        //exit();


        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', lang('successupdate'));
        redirect('wps-admin/products/view_stocks/' . $res['products_id'], '');
      }

      $sizelist = explode(',', $res['size_ids']);

      foreach ($sizelist as $sizes) {
        $ress = $this->db->select('s.size_id, s.size_name,pa.quantity, pa.product_price, pa.product_discounted_price')
                ->from('wps_sizes as s')
                ->join("wps_product_attributes as pa", "pa.product_id = '" . $res['products_id'] . "' AND pa.size_id = '" . $sizes . "'", 'left')
                ->where(['s.size_id' => $sizes])
                ->get()
                ->row_array();

        $size_data[] = $ress;
      }
      $data['size_data'] = $size_data;
      $data['headingTitle'] = "Manage Stocks";
      //echo "<pre>";print_r($data);die;
      $this->load->view('products/view_stock_products', $data);
    }
  }

  public function deleteImage() {
    $mid = $this->input->post('id');
    $this->db->query("DELETE FROM wps_products_media WHERE id = '" . $mid . "'");
    echo 'Image Deleted Successfully.';
  }

}

// End of controller