<?php

class Home extends Public_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->model(array('home/home_model', 'products/product_model', 'users/users_model', 'members/members_model', 'category/category_model'));
    $this->load->model(array('sitepanel/setting_model'));
    $this->load->helper(array('products/product', 'category/category'));
    $this->lang->load('portuguese', 'portuguese');
    $this->load->library(array('safe_encrypt', 'securimage_library', 'Auth', 'Dmailer', 'cart'));
  }

  public function index() {

    $data['page_title'] = "";
    $data['page_keyword'] = "";
    $data['page_description'] = "";

    //banners
    //blog
    $data['blog'] = $this->db->query("SELECT * FROM wps_blog WHERE status = '1' order by article_id LIMIT 0,3")->result_array();

    //Category Listing
    $fullList = array();
    $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 = '0' AND status='1' AND home_menu = '1'", 'limit' => '6', 'offset' => '0', 'debug' => FALSE);
    $res_array = $this->category_model->getcategory($condtion_array);

    $cn = 0;
    if (is_array($res_array) && !empty($res_array)) {
      foreach ($res_array as $val) {
        $fullList[$cn] = $val;
        //subcat list
        $condtion_array_sub = 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 = '" . $val['category_id'] . "' AND status='1' ", 'debug' => FALSE);
        $res_array_sub = $this->category_model->getcategory($condtion_array_sub);
        $fullList[$cn]['subcat'] = $res_array_sub;
        $cn++;
      }
    }
    //trace($fullList);
    $data['catList'] = $fullList;

    //catList Full
    $data['catListFull'] = $this->db->query("SELECT category_name, friendly_url FROM wps_categories WHERE parent_id = '0' AND status = '1' ORDER BY sort_order ASC")->result_array();

    //catList Homepage
    $data['catListHome'] = $this->db->query("SELECT category_name, category_image, friendly_url FROM wps_categories WHERE status = '1' AND home_menu = '1' ORDER BY RAND() LIMIT 0, 8")->result_array();

    //homepage content
    $data['homePageContent'] = get_db_field_value("wps_cms_pages", "page_description", "WHERE page_id = '12'");

    //catList Full
    $data['cityList'] = $this->db->query("SELECT city, temp_title, image_name FROM wps_cities_list WHERE is_featured = '1' AND status = '1' ORDER BY sort_order ASC")->result_array();
    
    //catList Full
    $data['featured'] = $this->db->query("SELECT p.product_name, p.friendly_url, p.products_id, p.customers_id, p.unit_measurement, pi.media FROM wps_products as p LEFT JOIN wps_products_media as pi ON p.products_id = pi.products_id WHERE p.coming_product = '1' AND p.status = '1' GROUP BY p.products_id")->result_array();
    
    $data['featuredMem'] = $this->db->query("SELECT c.company_name, ws.website_logo, wu.website_url FROM wps_customers as c LEFT JOIN wps_website_settings as ws ON c.customers_id = ws.customers_id LEFT JOIN wps_company_website_urls as wu ON c.customers_id = wu.customers_id WHERE c.is_featured = '1' AND c.status = '1' GROUP BY c.customers_id")->result_array();


    $this->load->view('home', $data);
  }

  public function homenew() {

    $data['page_title'] = "";
    $data['page_keyword'] = "";
    $data['page_description'] = "";

    //banners
    //blog
    $data['blog'] = $this->db->query("SELECT * FROM wps_blog WHERE status = '1' order by article_id LIMIT 0,3")->result_array();

    $this->load->view('homenew', $data);
  }

  public function home_inner() {

    $data['page_title'] = "";
    $data['page_keyword'] = "";
    $data['page_description'] = "";
    $category_id = 1;

    //For paging & Sub-Category List 
    $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 = 1;
    $base_url = ( $parent_segment > 0 ) ? "category/category_listing/$parent_id/pg/" : "category/category_listing/pg/";

    //Sub-Category 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['catList'] = $res_array;
    //End of Sub-category and Paging Here
    //trace($res_array);


    $this->load->view('home_inner', $data);
  }

  public function get_seller_product_list() {
    $this->load->model('products/product_model');
    $condtion['status'] = '1';
    $condtion['where'] = "bestseller_product = '1'";
    //$condtion['orderby'] = 'products_id DESC';
    $product_list = $this->product_model->get_products('', '', $condtion);
    //echo_sql();
    return $product_list;
  }

  public function get_special_product_list() {
    $this->load->model('products/product_model');
    $condtion['status'] = '1';
    $condtion['where'] = "special_product = '1'";
    //$condtion['orderby'] = 'products_id DESC';
    $product_list = $this->product_model->get_products('', '', $condtion);
    //echo_sql();
    return $product_list;
  }

  public function get_coming_product_list() {
    $this->load->model('products/product_model');
    $condtion['status'] = '1';
    $condtion['where'] = "coming_product = '1'";
    //$condtion['orderby'] = 'products_id DESC';
    $product_list = $this->product_model->get_products('', '', $condtion);
    //echo_sql();
    return $product_list;
  }

  public function get_product_new_list() {
    $condtion['status'] = '1';
    $condtion['where'] = "newarrival_product = '1'";
    //$condtion['orderby'] = 'products_id DESC';
    $product_list = $this->product_model->get_products('10', '0', $condtion);
    return $product_list;
  }

  public function get_product_popular() {
    $condtion['status'] = '1';
    $condtion['where'] = "coming_product = '1'";
    //$condtion['orderby'] = 'products_id DESC';
    $product_list = $this->product_model->get_products('10', '0', $condtion);
    //echo_sql();
    return $product_list;
  }

  public function add_newsletter_member($email, $name = NULL) {

    $query = $this->db->query("SELECT * FROM wps_newsletters  WHERE subscriber_email='" . $email . "' ");
    if ($query->num_rows() > 0) {
      $row = $query->row_array();
      if ($row['status'] == 1) {
        $error_type = "error";
        $error_msg = $this->config->item('newsletter_already_subscribed');
      } else {
        $where = "subscriber_email = '" . $row['subscriber_email'] . "'";
        $this->safe_update('wps_newsletters', array('status' => '1'), $where, FALSE);

        $error_type = "success";
        $error_msg = $this->config->item('newsletter_subscribed');
      }
    } else {
      $data = array('status' => '1',
          'subscriber_name' => $name,
          'subscriber_email' => $email,
          'subscribe_date' => $this->config->item('config.date.time'),
      );
      $this->home_model->safe_insert('wps_newsletters', $data);
    }
  }

  public function set_currency() {
    $currId = (int) $this->uri->segment(3);
    $this->session->set_userdata('currency_id', $currId);
    redirect($_SERVER['HTTP_REFERER'], 'refresh');
  }

  public function set_location() {
    $locId = (int) $this->uri->segment(3);
    $this->session->set_userdata('location_id', $locId);
    redirect($_SERVER['HTTP_REFERER'], 'refresh');
  }

  public function set_language() {
    $locId = $this->uri->segment(3);
    $this->session->unset_userdata('lang', '0');
    $this->session->unset_userdata('field_type', '');
    $this->session->set_userdata('lang', $locId);
    if ($locId == 'p') {
      $this->session->set_userdata('field_type', '_p');
    }
    redirect($_SERVER['HTTP_REFERER'], 'refresh');
  }

  public function set_sessions() {
    $ref = $this->input->get_post('ref');
    $p1 = $this->input->get_post('p1');
    $p2 = $this->input->get_post('p2');
    $p3 = $this->input->get_post('p3');

    $this->session->set_userdata('ref', $ref);
    if ($ref == 'buckets') {
      $this->session->set_userdata('destination', $p1);
      $this->session->set_userdata('start', $p2);
    }
    if ($ref == 'tripSearch') {
      $this->session->set_userdata('theme', $p1);
      $this->session->set_userdata('start', $p2);
      $this->session->set_userdata('zone', $p3);
    }
    echo $this->session->userdata('ref');
  }

  public function search_products() {
    $keyword = $this->input->post('keyword');
    $where = "";
    $qry = "SELECT p.friendly_url, p.product_name, pm.media from wps_products p LEFT JOIN wps_products_media as pm ON p.products_id=pm.products_id where p.status='1' and (p.product_name LIKE '%" . $keyword . "%' OR p.product_code LIKE '%" . $keyword . "%') AND pm.is_default = 'Y' $where group by p.products_id";
    $products = $this->db->query($qry)->result_array();
    if (count($products) > 0) {
      ?>
      <ul class="searching_listing" style="margin-bottom: 0;border: 1px solid gray;padding: 10px; z-index: 999999 !important;">
        <?php foreach ($products as $prod) { ?>
          <li style=" float: none !important; margin-left: 0px !important; padding: 5px; cursor: pointer;" onclick="window.location.href = '<?php echo base_url($prod['friendly_url']); ?>'">
            <img src="<?php echo get_image('product_images', $prod['media'], '50', '50', 'R'); ?>" width="32" height="32"> &nbsp; <?php echo $prod['product_name']; ?>
          </li>
          <?php
        }
        echo "</ul>";
      } else {
        ?>
        <ul class="searching_listing" style="margin-bottom: 0; width: 100%; border: 1px solid gray;padding: 10px; z-index: 999999 !important;">
          <li style="width: 99%;">No Product Found</li>
        </ul>
        <?php
      }
    }

    public function search_services() {
      $keyword = $this->input->post('keyword');
      $where = "";
      $qry = "SELECT category_name, friendly_url, category_image from wps_categories where status='1' and (category_name LIKE '%" . $keyword . "%') $where group by category_id";
      $products = $this->db->query($qry)->result_array();

      if (count($products) > 0) {
        ?>
        <ul class="searching_listing" style="margin-bottom: 0; width: 100%; border: 1px solid gray;padding: 10px; z-index: 999999 !important;">
          <?php foreach ($products as $prod) { ?>
            <li style=" float: none !important; margin-left: 0px !important; padding: 5px; cursor: pointer;" onclick="window.location.href = '<?php echo base_url($prod['friendly_url']); ?>'">
              <img src="<?php echo get_image('category', $prod['category_image'], '50', '50', 'R'); ?>"> &nbsp; <?php echo $prod['category_name']; ?>
            </li>
            <?php
          }
          ?>
        </ul>
        <?php
      } else {
        ?>
        <ul class="searching_listing" style="margin-bottom: 0; width: 100%; border: 1px solid gray;padding: 10px; z-index: 999999 !important;">
          <li style="width: 99%;">No Service Found.</li>
        </ul>
        <?php
      }
    }

    public function post_newsletter() {
      $email = $this->input->get_post('email');


      $query = $this->db->query("SELECT subscriber_email,status FROM  wps_newsletters WHERE subscriber_email='$email'");
      $subscribe_me = 'Y';

      if ($query->num_rows() > 0) {
        $row = $query->row_array();
        if ($row['status'] == '0' && ($subscribe_me == 'Y')) {
          $where = "subscriber_email = '" . $row['subscriber_email'] . "'";
          $this->pages_model->safe_update('wps_newsletters', array('status' => '1'), $where, FALSE);
          $msg = $this->config->item('newsletter_subscribed');
          echo $msg;
        } else if ($row['status'] == '0' && ($subscribe_me == 'N')) {
          $msg = $this->config->item('newsletter_not_subscribe');
          echo $msg;
        } else if ($row['status'] == '1' && ($subscribe_me == 'Y')) {
          $msg = $this->config->item('newsletter_already_subscribed');
          echo $msg;
        } else if ($row['status'] == '1' && ($subscribe_me == 'N')) {
          $where = "subscriber_email = '" . $row['subscriber_email'] . "'";
          $this->pages_model->safe_update('wps_newsletters', array('status' => '0'), $where, FALSE);
          $msg = $this->config->item('newsletter_unsubscribed');
          echo $msg;
        }
      } else {
        if ($subscribe_me == 'N') {
          $msg = $this->config->item('newsletter_not_subscribe');
          echo $msg;
        } else {
          $data = array('status' => '1', 'subscriber_email' => $email);
          $this->home_model->safe_insert('wps_newsletters', $data);
          $msg = $this->config->item('newsletter_subscribed');
          echo $msg;
        }
      }
    }

    public function recoverPassword() {
      $email = $this->input->post('email');

      $condtion = array('field' => "user_name,password,first_name,last_name", 'condition' => "user_name ='" . $email . "' AND status ='1' ");
      $res = $this->users_model->find('wps_customers', $condtion);
      if (is_array($res) && !empty($res)) {
        $first_name = $res['first_name'];
        $last_name = $res['last_name'];
        $username = $res['user_name'];
        $password = $res['password'];
        $password = $this->safe_encrypt->decode($password);
        /* Send  mail to user */

        $content = get_content('wps_auto_respond_mails', '2');
        $subject = $content->email_subject;
        $body = $content->email_content;

        $verify_url = "<a href=" . base_url() . "users/register>Click here </a>";

        $name = $first_name . ' ' . $last_name;
        $body = str_replace('{mem_name}', $name, $body);
        $body = str_replace('{username}', $username, $body);
        $body = str_replace('{password}', $password, $body);
        $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
        $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
        $body = str_replace('{url}', base_url(), $body);
        $body = str_replace('{link}', $verify_url, $body);

        $mail_conf = array(
            'subject' => $subject,
            'to_email' => $username,
            'from_email' => $this->admin_info->admin_email,
            'from_name' => $this->config->item('site_name'),
            'body_part' => $body
        );
        //trace($mail_conf);
        @$this->dmailer->mail_notify($mail_conf);

        $data['message'] = $this->config->item('forgot_password_success');
        $data['success'] = true;
      } else {
        $data['error'] = $this->config->item('email_not_exist');
        $data['success'] = false;
      }

      echo json_encode($data);
    }

    //Old Way
    public function logIn() {
      $this->form_validation->set_rules('username', 'Email ID', 'trim|required|valid_email');
      if ($this->input->post('login_type') == 'normal' || $this->input->post('login_type') == '') {
        $this->form_validation->set_rules('password', 'Password', 'trim|required|');
      }
      //$this->form_validation->set_rules('user', 'User', 'trim');
      if ($this->form_validation->run() == TRUE) {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $this->auth->verify_user($username, $password);
        if ($this->auth->is_user_logged_in()) {
          $user_id = $this->session->userdata('user_id');
          $userData = get_db_single_row("wps_customers", "*", "customers_id = '" . $user_id . "'");

          if ($userData['is_blocked'] == 1) {
            //echo "ssss";
            $data['error'] = "Your login details have been Blocked, please contact Admin!";
            $data['success'] = false;
          } else {
            $name = $userData['first_name'] . ' ' . $userData['last_name'];
            $data = array(
                'user_id' => $userData['customers_id'],
                'username' => $userData['user_name'],
                'name' => $name,
                'login_type' => $userData['login_type'],
                'first_name' => $userData['first_name'],
                'phone' => $userData['phone_number'],
                'last_name' => $userData['last_name'],
                'logged_in' => TRUE
            );
            $this->session->set_userdata($data);
            //trace($this->session->userdata); exit;
            //Transaction
            $data['post_type'] = $this->session->userdata('post_type');
            $data['transactionId'] = $this->session->userdata('transactionId');

            $data['Userdata'] = $userData;
            $data['user_id'] = $user_id;
            //$data['txnId'] = $this->session->userdata('transactionId');
            $data['message'] = "Login Successful!!";
            $data['success'] = true;
          }
        } else {
          $data['error'] = $this->config->item('login_failed'); //"Something wrong, please try again!!!";
          $data['success'] = false;
        }
      } else {
        $data['error'] = "Parameter Missing!!!";
        $data['success'] = false;
      }
      echo json_encode($data);
    }

    //OLD Way
    public function registerMember() {
      $count = count_record("wps_customers", "user_name = '" . $this->input->post('email') . "'");
      if ($count > 0) {
        $data['error'] = "Email ID already Exists!";
        $data['success'] = false;
      } else {
        $postData = $this->input->post();
        $username = $postData['email'];
        $password = $postData['password'];

        $registerID = $this->register_member_mail($postData);
        //Make user Login after Successful registartion
        $this->auth->verify_user($username, $password);
        if ($this->auth->is_user_logged_in()) {
          $user_id = $this->session->userdata('user_id');
          $userData = get_db_single_row("wps_customers", "*", "customers_id = '" . $user_id . "'");

          if ($userData['is_blocked'] == 1) {
            //echo "ssss";
            $data['error'] = "Your login details have been Blocked, please contact Admin!";
            $data['success'] = false;
          } else {
            $name = $userData['first_name'] . ' ' . $userData['last_name'];
            $data = array(
                'user_id' => $userData['customers_id'],
                'username' => $userData['user_name'],
                'name' => $name,
                'login_type' => $userData['login_type'],
                'first_name' => $userData['first_name'],
                'phone' => $userData['phone_number'],
                'last_name' => $userData['last_name'],
                'logged_in' => TRUE
            );
            $this->session->set_userdata($data);
          }
        }
        //End

        $this->session->set_userdata('user_id', $registerID);
        $message = $this->config->item('register_thanks');
        $message = str_replace('<site_name>', $this->config->item('site_name'), $message);
        // $this->session->set_userdata(array('msg_type'=>'success'));
        $this->session->set_flashdata('success', $message);
        $data['message'] = $message;
        $data['success'] = true;
        $data['transactionId'] = $this->session->userdata('transactionId');
        $data['user_id'] = $registerID;
      }
      echo json_encode($data);
    }

    // New API on 1st June 2016
    public function register_member_mail($postData) {
      $registeredId = $this->users_model->create_user_json($postData);
      $username = $postData['email'];
      $password = $postData['password'];


      //Mail to user if user registered as a normal User
      if ($postData['login_type'] == 'normal' || $postData['login_type'] == '') {
        /* Send  mail to user */
        $content = get_content('wps_auto_respond_mails', '1');
        $subject = str_replace('{site_name}', $this->config->item('site_name'), $content->email_subject);
        $body = $content->email_content;
        $verify_url = "";
        $name = " User ";
        $body = str_replace('{mem_name}', $name, $body);
        $body = str_replace('{username}', $username, $body);
        $body = str_replace('{password}', $password, $body);
        $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
        $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
        $body = str_replace('{url}', base_url(), $body);
        $body = str_replace('{link}', $verify_url, $body);

        $mail_conf = array(
            'subject' => $subject,
            'to_email' => $username,
            'from_email' => $this->admin_info->admin_email,
            'from_name' => $this->config->item('site_name'),
            'body_part' => $body
        );
        //trace($mail_conf);
        @$this->dmailer->mail_notify($mail_conf);
      }

      /* Send  mail to admin */
      $subject = ($postData['login_type'] == 'normal' || $postData['login_type'] == '') ? 'New member is registered' : 'New member is registered with ' . $this->input->get_post('login_type');

      $body = '<table border="0" style="width:100%">
        <tbody>
          <tr><td colspan="2"><strong>Hi Admin,</strong></td></tr>
          <tr><td colspan="2">You have new member registered on {site_name} with the following details:</td></tr>
          <tr><td colspan="2">&nbsp;</td></tr>
          <tr><td><strong>Email ID:</strong></td><td>{username}</td></tr>
          <tr><td><strong>Password:</strong></td><td>{password}</td></tr>
          <tr><td colspan="2">&nbsp;</td></tr>
          <tr><td colspan="2">&nbsp;</td></tr>
          <tr>
            <td colspan="2">
              Thank you.<br />
              {site_name} Customer Service<br />
              Email: {admin_email}
            </td>
          </tr>
          <tr>
            <td colspan="2" style="text-align:center">
              &copy; ' . date('Y') . ' {site_name}. All rights reserved.
            </td>
          </tr>
        </tbody>
        </table>';
      $body = str_replace('{username}', $username, $body);
      $body = str_replace('{password}', $password, $body);
      $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
      $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
      $body = str_replace('{url}', base_url(), $body);
      $mail_conf = array(
          'subject' => $subject,
          'to_email' => $this->admin_info->admin_email,
          'from_email' => $username,
          'from_name' => $this->config->item('site_name'),
          'body_part' => $body
      );
      //trace($mail_conf);
      @$this->dmailer->mail_notify($mail_conf);
      /* End send  mail to admin */

      return $registeredId;
    }

    public function member_exists($email) {
      $count = count_record("wps_customers", "email = '" . $email . "'");
      if ($count > 0) {
        return 1;
      } else {
        return 0;
      }
      echo my_json_encode($data);
    }

    public function send_otp() {
      $mobile = $this->input->post('mobile');
      $otp = substr(str_shuffle('1234567890'), 0, 4);
      //Insert into table
      $count = count_record("wps_customers", "user_name = '" . $mobile . "'");
      if ($count == 0) {
        $this->db->query("INSERT INTO wps_otp SET mobile_number = '" . $mobile . "', otp = '" . $otp . "'");
        $message = $otp . ' is your one time password to Register with - Natural Therapy India';
        sendSms($mobile, $message);
        echo "T";
      } else {
        $userName = get_db_field_value('wps_customers', 'first_name', "WHERE user_name='" . $mobile . "'");
        $userName = ($userName) ? $userName : 'User';
        echo 'Dear ' . $userName . ', You are already Registered, Please enter Password and Login';
        //echo "This number is already Registered with US. Please try Login!";
      }
    }

    public function send_password() {
      $mobile = $this->input->post('mobile');
      $password = get_db_field_value("wps_customers", "password", "WHERE user_name = '" . $mobile . "'");
      if ($password) {
        $password = $this->safe_encrypt->decode($password);
        $message = $password . ' is your password to login with - Natural Therapy India Do not share your password with anyone.';
        if (is_numeric($mobile)) {
          sendSms($mobile, $message);
        } else {

          $mailContentHtmlSupport = "";
          $verify_url = site_url() . 'login';
          $mailContentHtmlSupport = file_get_contents(site_url() . 'mailer/recover-password.html');
          $body = $mailContentHtmlSupport;

          $body = str_replace('{message}', $message, $body);
          $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
          $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
          $body = str_replace('{link}', $verify_url, $body);
          $mail_conf = array(
              'subject' => 'Your Password @ Natural Therapy India',
              'to_email' => $mobile,
              'from_email' => 'support@webpulse.co',
              'from_name' => 'Natural Therapy India',
              'body_part' => $body
          );
          @$this->dmailer->mail_notify($mail_conf);
          //trace($mail_conf);
        }
        echo '1';
      } else {
        echo '0';
      }
    }

    public function verify_otp() {
      $mobile = $this->input->post('mobile');
      $otp = $this->input->post('otp');
      verifySms($mobile, $otp);
    }

    public function get_citylist() {
      $stateId = $this->input->get_post('stateId');
      $citylist = $this->db->query("select * from wps_cities_list where state_id='" . $stateId . "'")->result_array();
      if (is_array($citylist) && !empty($citylist)) {
        ?>
        <option value="" disabled selected>Select City*</option>
        <?php
        foreach ($citylist as $ck => $cval) {
          ?>
          <option value="<?php echo $cval['id']; ?>"><?php echo $cval['city']; ?></option>
          <?php
        }
      } else {
        ?>
        <option value="" disabled selected>Select City*</option>
        <?php
      }
    }

    public function getCompanyContactNo() {
      $customersId = $this->session->userdata('user_id'); //visitor
       $curdate = date('Y-m-d', strtotime(date('Y-m-d')));
      $countPerDayQuery = $this->db->query("SELECT * FROM wps_viewed_contacts WHERE customers_id='".$customersId."' and viewed_date = '".$curdate."' GROUP BY compId")->result_array();
      $countPerDay = count($countPerDayQuery);
      // echo $countPerDay;
      if($countPerDay>=10){
         echo "<b style='color:red;'>Oops !! Your limit has been exceeded.</b><br/>
You can view up to 10 company's contact number in a day.";
      }else{

        $compId = $this->input->post('compId'); //for which user is viewing phone no
        $this->session->unset_userdata('compIdVerification'); // unset userdata
        $contactNo = get_db_field_value('wps_customers', 'mobile_number', "WHERE customers_id = '" . $compId . "'");
        $compName = get_db_field_value('wps_customers', 'company_name', "WHERE customers_id = '" . $compId . "'");
       

        //if customer is not same
        $vdate = date('Y-m-d', strtotime(date('Y-m-d') . ' -2 days'));  
        $count = count_record("wps_viewed_contacts", "compId = '".$compId."' AND customers_id = '".$customersId."' AND viewed_date > '".$vdate."'");
        if ($customersId != $compId and $count == 0) {
          
          //insert into table
          $this->db->query("DELETE FROM wps_viewed_contacts WHERE compId = '".$compId."' AND customers_id = '".$customersId."'");
          $this->db->query("INSERT INTO wps_viewed_contacts SET compId = '".$compId."', customers_id = '".$customersId."', viewed_date = '".date('Y-m-d')."'");
          
          //send SMS to customer
          $viewerNo = get_db_field_value('wps_customers', 'mobile_number', "WHERE customers_id = '" . $customersId . "'");
          $sessionUserDets = get_db_single_row('wps_customers', "first_name,last_name", "customers_id = '" . $customersId . "'");
          //if at least firstname is not blank.
          if ($sessionUserDets['first_name'] != '') {
            $message = "Dear Customer, " . $sessionUserDets['first_name'] . ' ' . $sessionUserDets['last_name'] . ' has viewed your contact details. You can reach this customer at ' . $viewerNo . ' Thanks Natural Therapy India';
            //sendSms($contactNo, $message);
            //End Here
          }
        }
        echo 'Contact Number of <b style="color:red;">' . $compName . '</b> is : ' . $contactNo;
      }
    }

  }
  