<?php

class Products extends Public_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->model(array('category/category_model', 'products/product_model', 'color/color_model', 'size/size_model', 'testimonials/testimonial_model'));
    $this->load->helper(array('products/product', 'category/category', 'query_string'));
    $this->lang->load('portuguese', 'portuguese');
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");
    $this->page_section_ct = 'product';
  }

  public function index() {
    $this->page_section_ct = 'product';
    //get product List
    $condtion = array();
    $per_page = $this->config->item('per_page');
    $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 = "";
    if ($this->input->get_post('category_id') > 0) {
      $category_id = $this->input->get_post('category_id');
      $condtion['category_id'] = $category_id;
    }
    $data['categoryId'] = $category_id;
    $condtion['groupby'] = "wlp.customers_id";
    $condtion['status'] = "1";
    if ($this->input->get_post('keyword')) {
      $page_title = "Search Result - " . ucwords($this->input->get_post('keyword'));
        $condtion['keyword']=$this->input->get_post('keyword');
    } else {
      $page_title = "Product Lists";
    }
    $res_array = $this->product_model->get_products($per_page, $offset, $condtion);
    //echo_sql();
    $data['total_list_rows'] = $total_rows = get_found_rows();
    //die;
    $data['page_list_links'] = front_pagination($base_url, $total_rows, $per_page, $offset);
    //trace($res_array);
    $data['listRes'] = $res_array;

    /* Global array */
    $data['heading_title'] = $page_title;
    $data['unit_measurement'] = $this->config->item('unit_measurement');
    $this->load->view('products/view_product_listing', $data);
  }

  public function ajax_load_product_view() {

    $data['title'] = 'Ajax Load Products';
    $page_title = "Product Lists";
    $config['per_page'] = $this->config->item('per_page');
    $offset = $this->input->get_post('stOffSet');

    $locationId = $this->input->get_post('locationId');
    //echo $locationId;

    if ($this->input->get_post('category_id')) {
      $parent_segment = (int) $this->input->get_post('category_id');
    } else {
      $parent_segment = (int) $this->input->get_post('category_id');
    }
    $page_segment = find_paging_segment();
    $parent_id = ( $parent_segment > 0 ) ? $parent_segment : '0';
    $category_id = $this->input->get_post('category_id');
    if ($category_id > 0) {
      $condtion['category_id'] = $category_id;
    }
    $condtion['groupby'] = "wlp.customers_id";
    $condtion['status'] = '1';
    $condtion['city'] = $locationId;

    $res_array = $this->product_model->get_products($config['per_page'], $offset, $condtion);
    //echo_sql();
    //exit;
    $data['categoryId'] = $category_id;
    $data['unit_measurement'] = $this->config->item('unit_measurement');
    $data['listRes'] = $res_array;
    $this->load->view('products/ajax_load_products', $data);
  }

  public function details() {
    $data = array();
    $this->load->view('products/view_product_details', $data);
  }

  public function detail() {
    $this->page_section_ct = 'product';
    $data['unq_section'] = "Product";
    $productId = (int) $this->meta_info['entity_id'];
    $where = "wlp.products_id = '" . $productId . "' AND wlp.status = '1'";
    $option = array(
        'fields' => "SQL_CALC_FOUND_ROWS wlp.*,wlc.first_name,wlc.user_name,wlc.mobile_number,wlcat.category_id",
        'where' => $where
    );
    $res = $this->product_model->get_products('1', '', $option);
    if (is_array($res) && !empty($res)) {
      $res = $res[0];

      $data['title'] = "Product";
      $data['res'] = $res;
      $this->product_model->update_viewed($res['products_id'], $res['products_viewed']);

      //Media
      $media_res = $this->product_model->get_product_media(4, 0, array('productid' => $res['products_id']));
      $data['media_res'] = $media_res;

      //Conpany Details & Factsheet
      $data['company'] = get_db_single_row('wps_customers', 'first_name, last_name, website, profile_picture, company_name, address, state, city,  country, locality, landmark, website', "customers_id = '" . $res['customers_id'] . "'");
      $data['factsheet'] = get_db_single_row('wps_customers_factsheet', '*', "customers_id = '" . $res['customers_id'] . "'");

      //Related Products
      $condtion_rel['categoryIds'] = $res['category_id'];
      $condtion_rel['leave_product_id'] = $res['products_id'];
      $condtion_rel['orderby'] = 'RAND()';
      $rel_array = $this->product_model->get_products(4, 0, $condtion_rel);
      $data['related'] = $rel_array;

      $this->load->view('products/view_product_details', $data);
    } else {
      redirect('directory', '');
    }
  }

  public function detail_comp() {
    $this->page_section_ct = 'product';
    $data['unq_section'] = "Product";

    //get company details
    $uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $uri_segments = explode('/', $uri_path);
    $st = $uri_segments[1];
    $companyID = 0;
    $prevCompanyURL = $this->db->query("SELECT customers_id, website_url FROM wps_company_website_urls WHERE website_url='" . $st . "'")->row_array();
    if (is_array($prevCompanyURL) && !empty($prevCompanyURL)) {
      $companyID = $prevCompanyURL['customers_id'];
    }
    //end here

    $productId = (int) $this->meta_info['entity_id'];
    $where = "wlp.products_id = '" . $productId . "'";
    $option = array(
        'fields' => "SQL_CALC_FOUND_ROWS wlp.*,wlc.first_name,wlc.user_name,wlc.mobile_number,wlcat.category_id",
        'where' => $where
    );
    $res = $this->product_model->get_products('1', '', $option);
    if (is_array($res) && !empty($res)) {
      $res = $res[0];

      $data['title'] = "Product";
      $data['res'] = $res;
      $this->product_model->update_viewed($res['products_id'], $res['products_viewed']);

      //Media
      $media_res = $this->product_model->get_product_media(4, 0, array('productid' => $res['products_id']));
      $data['media_res'] = $media_res;

      //Conpany Details & Factsheet
      $data['company'] = get_db_single_row('wps_customers', 'first_name, last_name, website, profile_picture, company_name, address, state, city,  country, locality, landmark, website', "customers_id = '" . $res['customers_id'] . "'");
      $data['factsheet'] = get_db_single_row('wps_customers_factsheet', '*', "customers_id = '" . $res['customers_id'] . "'");

      //Related Products
      //$condtion_rel['categoryIds'] = $res['category_id'];
      $condtion_rel['leave_product_id'] = $res['products_id'];
      $condtion_rel['customers_id'] = $companyID;
      $condtion_rel['orderby'] = 'RAND()';
      $rel_array = $this->product_model->get_products(4, 0, $condtion_rel);
      $data['related'] = $rel_array;

      $this->load->view('wpstemplate/product-details2', $data);
    } else {
      redirect('directory', '');
    }
  }

  public function get_product_price() {
    $sid = (int) $this->input->post('sid');
    $cid = (int) $this->input->post('cid');
    $pid = (int) $this->input->post('pid');

    if ($cid > 0 && $sid > 0) {
      $res = $this->db->select('quantity,product_price,product_discounted_price')->get_where('wps_product_attributes', array('color_id' => $cid, 'size_id' => $sid, 'product_id' => $pid))->row();
      if (is_object($res)) {
        echo $res->quantity . '-' . $res->product_price . '-' . $res->product_discounted_price;
      }
    }
  }

  public function post_review() {

    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");

    $this->form_validation->set_rules('name', 'Name', 'trim|required|max_length[70]');
    $this->form_validation->set_rules('email', 'Email', 'trim|required|max_length[80]|valid_email');
    $this->form_validation->set_rules('rating', 'Rating', 'trim|required|max_length[1]');
    $this->form_validation->set_rules('reviews', 'Review', 'trim|required|max_length[450]');
    if ($this->form_validation->run() === TRUE) {
      $mem_id = $this->session->userdata('user_id');
      $posted_data = array(
          'entity_id' => $this->input->get_post('products_id'),
          'entity_type' => 'product',
          'customer_id' => $mem_id,
          'ads_rating' => $this->input->post('rating'),
          'author' => $this->input->post('name'),
          'author_email' => $this->input->post('email'),
          'text' => $this->input->post('reviews'),
          'status' => '1',
          'review_date' => $this->config->item('config.date.time')
      );
      $this->product_model->safe_insert('wps_review', $posted_data, FALSE);

      $data['success'] = true;
      $data['message'] = 'Thank you. Your review has been submitted successfully';
      echo json_encode($data);
    } else {
      $data['success'] = false;
      $data['error'] = validation_errors();
      echo json_encode($data);
    }
  }

  public function check_product_exits_into_cart($pres) {
    $cart_array = $this->cart->contents();
    $insert_flag = 0;
    if (is_array($cart_array) && !empty($cart_array)) {
      foreach ($this->cart->contents() as $item) {
        if (array_key_exists('pid', $item)) {
          if ($item['pid'] == $pres['products_id']) {
            $insert_flag = 1;
          }
        }
      }
    }
    return $insert_flag;
  }

  public function postEnquiry() {
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");

    $this->form_validation->set_rules('fullName', 'Your Name', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('mobileNumber', 'Mobile Number', 'trim|required|max_length[30]');
    $this->form_validation->set_rules('emailAddress', 'Email', 'trim|required|max_length[80]|valid_email');
    //$this->form_validation->set_rules('productQuantity', 'Quantity', 'trim|required|max_length[10]');
    $this->form_validation->set_rules('enquiryMessage', 'Message', 'trim|required');


    if ($this->form_validation->run() === TRUE) {
      $mem_id = $this->input->post('companyID');
      $pro_id = $this->input->post('productID');
      $post_url = $this->input->post('post_url');
      if($post_url=='NULL'){$post_url=NULL;}

      $posted_data = array( 
          'products_id' => $pro_id,
          'customers_id' => $mem_id,
          'type' => $this->input->post('type'),
          'email' => $this->input->post('emailAddress'),
          'first_name' => $this->input->post('fullName'),
          'mobile_number' => $this->input->post('mobileNumber'),
          'message' => $this->input->post('enquiryMessage'),
          'quantity' => $this->input->post('productQuantity'),
          'post_url' => $post_url,
          'location' => $this->input->post('location'),
          'status' => '0',
          'receive_date' => $this->config->item('config.date.time')
      );
      $this->product_model->safe_insert('wps_enquiry', $posted_data, FALSE);
      //Send Email to Admin
      sendAdminEnquiryEmail('New Enquiry Received from Natural Therapy India', $emailIds = array("0" => "support@webpulseindia.com"), $this->input->post());
      //Send Email to User
      sendUserEnquiryEmail('Enquiry Received with Thanks @ Natural Therapy India', $this->input->post('emailAddress'), $this->input->post());


      $data['success'] = 'true';
      $data['message'] = 'Thank you. Your enquiry has been submitted successfully!';
      echo json_encode($data);
    } else {
      $data['success'] = 'false';
      $data['error'] = validation_errors();
      echo json_encode($data);
    }
  }

  public function postEnquiryCompany() { 
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");

    $this->form_validation->set_rules('fullName', 'Your Name', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('mobileNumber', 'Mobile Number', 'trim|required|max_length[30]');
    $this->form_validation->set_rules('emailAddress', 'Email', 'trim|required|max_length[80]|valid_email');
    $this->form_validation->set_rules('productQuantity', 'Quantity', 'trim|required|max_length[10]');
    $this->form_validation->set_rules('enquiryMessage', 'Message', 'trim|required');


    if ($this->form_validation->run() === TRUE) {
      $mem_id = $this->input->post('companyID');
      $pro_id = $this->input->post('productID');
      $post_url = $this->input->post('post_url');

      $product = get_db_single_row('wps_products', 'product_name, unit_measurement', "products_id = '" . $pro_id . "'");
      if ($this->input->post('type') == 'category') {
        $product = get_db_single_row('wps_company_categories', 'category_name as product_name', "category_id = '" . $pro_id . "'");
      }

      $posted_data = array(
          'products_id' => $pro_id,
          'enquiry_for' => $product['product_name'],
          'customers_id' => $mem_id,
          'email' => $this->input->post('emailAddress'),
          'first_name' => $this->input->post('fullName'),
          'mobile_number' => $this->input->post('mobileNumber'),
          'message' => $this->input->post('enquiryMessage'),
          'quantity' => $this->input->post('productQuantity'),
          'post_url' => $this->input->post('post_url'),
          'location' => $this->input->post('location'),
          'status' => '0',
          'receive_date' => $this->config->item('config.date.time')
      );
      $this->product_model->safe_insert('wps_company_enquiry', $posted_data, FALSE);
      //Send Email to Admin
      sendAdminEnquiryEmail('New Enquiry Received from Natural Therapy India', $emailIds = array("0" => "support@webpulseindia.com"), $this->input->post(), $this->input->post('type'));
      //Send Email to User
      sendUserEnquiryEmail('Enquiry Received with Thanks @ Natural Therapy India', $this->input->post('emailAddress'), $this->input->post(), $this->input->post('type'));


      $data['success'] = 'true';
      $data['message'] = 'Thank you. Your enquiry has been submitted successfully!';
      echo json_encode($data);
    } else {
      $data['success'] = 'false';
      $data['error'] = validation_errors();
      echo json_encode($data);
    }
  }

  public function postEnquiryCompanyLeft() {
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");

    $this->form_validation->set_rules('fullName', 'Your Name', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('mobileNumber', 'Mobile Number', 'trim|required|max_length[30]');
    $this->form_validation->set_rules('emailAddress', 'Email', 'trim|required|max_length[80]|valid_email');
    $this->form_validation->set_rules('location', 'Location', 'trim|required|max_length[160]');
    $this->form_validation->set_rules('enquiryMessage', 'Message', 'trim|required');


    if ($this->form_validation->run() === TRUE) {
      $mem_id = $this->input->post('companyID');
      $pro_id = $this->input->post('productID');
      $post_url = $this->input->post('post_url');

      $product = get_db_single_row('wps_products', 'product_name, unit_measurement', "products_id = '" . $pro_id . "'");
      if ($this->input->post('type') == 'category') {
        $product = get_db_single_row('wps_company_categories', 'category_name as product_name', "category_id = '" . $pro_id . "'");
      }

      $posted_data = array(
          'products_id' => $pro_id,
          'enquiry_for' => $product['product_name'],
          'customers_id' => $mem_id,
          'email' => $this->input->post('emailAddress'),
          'first_name' => $this->input->post('fullName'),
          'mobile_number' => $this->input->post('mobileNumber'),
          'message' => $this->input->post('enquiryMessage'),
          'quantity' => $this->input->post('productQuantity'),
          'post_url' => $this->input->post('post_url'),
          'location' => $this->input->post('location'),
          'status' => '0',
          'receive_date' => $this->config->item('config.date.time')
      );
      $this->product_model->safe_insert('wps_company_enquiry', $posted_data, FALSE);
      //Send Email to Admin
      sendAdminEnquiryEmail('New Enquiry Received from Natural Therapy India', $emailIds = array("0" => "support@webpulseindia.com"), $this->input->post());
      //Send Email to User
      sendUserEnquiryEmail('Enquiry Received with Thanks @ Natural Therapy India', $this->input->post('emailAddress'), $this->input->post());


      $data['success'] = 'true';
      $data['message'] = 'Thank you. Your enquiry has been submitted successfully!';
      echo json_encode($data);
    } else {
      $data['success'] = 'false';
      $data['error'] = validation_errors();
      echo json_encode($data);
    }
  }

  public function midEnquiry() {
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");

    $this->form_validation->set_rules('fullName', 'Your Name', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('mobileNumber', 'Mobile Number', 'trim|required|max_length[30]');
    $this->form_validation->set_rules('emailAddress', 'Email', 'trim|required|max_length[80]|valid_email');
    $this->form_validation->set_rules('location', 'Location', 'trim|required|max_length[160]');
    $this->form_validation->set_rules('enquiryMessage', 'Message', 'trim|required');


    if ($this->form_validation->run() === TRUE) {
      $mem_id = 0; //$this->input->post('companyID');
      $pro_id = $this->input->post('productID');
      $post_url = $this->input->post('post_url');

      $product = get_db_single_row('wps_products', 'product_name, unit_measurement', "products_id = '" . $pro_id . "'");
      if ($this->input->post('type') == 'category') {
        $product = get_db_single_row('wps_company_categories', 'category_name as product_name', "category_id = '" . $pro_id . "'");
      }

      $posted_data = array(
          'products_id' => $pro_id,
          'enquiry_for' => $product['product_name'],
          'customers_id' => $mem_id,
          'type'=>'3',
          'email' => $this->input->post('emailAddress'),
          'first_name' => $this->input->post('fullName'),
          'mobile_number' => $this->input->post('mobileNumber'),
          'message' => $this->input->post('enquiryMessage'),
          'quantity' => $this->input->post('productQuantity'),
          'post_url' => $this->input->post('post_url'),
          'location' => $this->input->post('location'),
          'status' => '0',
          'receive_date' => $this->config->item('config.date.time')
      );
      $this->product_model->safe_insert('wps_company_enquiry', $posted_data, FALSE);
      //Send Email to Admin
      sendAdminEnquiryEmail('New Enquiry Received from Natural Therapy India', $emailIds = array("0" => "support@webpulseindia.com"), $this->input->post());
      //Send Email to User
      sendUserEnquiryEmail('Enquiry Received with Thanks @ Natural Therapy India', $this->input->post('emailAddress'), $this->input->post());


      $data['success'] = 'true';
      $data['message'] = 'Thank you. Your enquiry has been submitted successfully!';
      echo json_encode($data);
    } else {
      $data['success'] = 'false';
      $data['error'] = validation_errors();
      echo json_encode($data);
    }
  }
  

}

?>