<?php

class Enquiry extends Admin_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->model(array('sitepanel/enquiry_model', 'members/members_model'));
    $this->config->set_item('menu_highlight', 'manage enquiry');
  }

  public function index() {
    $type = (int) $this->uri->segment(4);
    $keyword = trim($this->input->post('keyword', TRUE));
    $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'));
    $condition = "type = '" . $type . "'";
    $keyword = $this->db->escape_str($keyword);
    if ($keyword != '') {
      $condition .= " AND  ( email like '%$keyword%' OR  company_name like '%$keyword%' OR CONCAT_WS(' ',first_name,last_name) LIKE '%" . $keyword . "%' ) ";
    }

    $res_array = $this->enquiry_model->get_enquiry($offset, $config['limit'], $condition);
    //echo_sql();
    $config['total_rows'] = $this->enquiry_model->total_rec_found;
    $data['page_links'] = admin_pagination($base_url, $config['total_rows'], $config['limit'], $offset);

    if ($this->input->post('status_action') != '') {
      $this->update_status('wps_enquiry', 'id');
    }
    if ($type == 1) {
      $data['heading_title'] = 'Manage Enquiry';
    }
    if ($type == 2) {
      $data['heading_title'] = 'Manage Suggestioin';
    }
    if ($type == 3) {
      $data['heading_title'] = 'Manage Feedback';
    }
    if ($type == 4) {
      $data['heading_title'] = 'Manage Product Enquiry';
    }
    if ($type == 5) {
      $data['heading_title'] = 'Manage Complaint';
    }


    /* Product set as a */
    if ($this->input->post('status_action') != '') {
      $this->update_status('wps_products', 'products_id');
    }
    /* End product set as a */

    $data['inq_type'] = 'General';
    $data['res'] = $res_array;
    $data['type'] = $type;
    //print_r($res_array);exit;
    $this->load->view('enquiry/view_enquiry_list', $data);
  }

  public function edit() {
    $id = (int) $this->uri->segment(4);
    $condition = "id = '" . $id . "'";
    $res = $this->enquiry_model->get_enquiry(0, 1, $condition);
    $res = $res[0];

    $this->form_validation->set_rules('first_name', '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('quantity', 'Quantity', 'trim|required|max_length[10]');
    $this->form_validation->set_rules('enquiryMessage', 'Message', 'trim|required');
    if ($this->form_validation->run() == TRUE) {
      $posted_data = array(
          'email' => $this->input->post('emailAddress'),
          'first_name' => $this->input->post('first_name'),
          'mobile_number' => $this->input->post('mobileNumber'),
          'message' => $this->input->post('enquiryMessage'),
          'quantity' => $this->input->post('quantity'),
          'update_date' => $this->config->item('config.date'),
          'updated_by' => $this->session->userdata('admin_id')
      );
      //trace($posted_data); die;
      $where = "id = '" . $res['id'] . "'";
      $this->enquiry_model->safe_update('wps_enquiry', $posted_data, $where, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', lang('successupdate'));
      redirect('sitepanel/enquiry/index/4', '');
    }
    $data['heading_title'] = "Edit Enquiry";
    $data['res'] = $res;
    $this->load->view('enquiry/view_edit_enquiry', $data);
  }

  public function forward() {
    $id = (int) $this->uri->segment(4);
    $condition = "id = '" . $id . "'";
    $res = $this->enquiry_model->get_enquiry(0, 1, $condition);
    $res = $res[0];


    $data['heading_title'] = "Forward Enquiry";
    $data['res'] = $res;
    $data['state'] = $this->db->query("select * from wps_states_list where country_id='105'")->result_array();
    $this->load->view('enquiry/view_forward_enquiry', $data);
  }

  public function send_reply() {
    $rid = (int) $this->uri->segment(4);
    $this->db->select("*,CONCAT_WS(' ',first_name,last_name) AS name", FALSE);
    $res_data = $this->db->get_where('wps_enquiry', array('id' => $rid))->row();
    $this->load->library('email');

    if (is_object($res_data)) {
      $this->form_validation->set_rules('subject', 'Subject', 'required|xss_clean');
      $this->form_validation->set_rules('message', 'Message', 'required|xss_clean');

      if ($this->form_validation->run() == TRUE) {
        /* Reply  mail to user */


        $mail_to = $res_data->email;
        $mail_subject = $this->input->post('subject');
        $from_email = $this->admin_info->admin_email;
        $from_name = $this->config->item('site_name');
        $body = "Dear " . $res_data->name . ",<br /><br />	";
        $body .= $this->input->post('message');
        $body .= "<br /> <br />						   
									Thanks and Regards,<br />						   
									" . $this->config->item('site_name') . " Team ";
        //print_r($body);exit;		
        $this->email->from($from_email, $from_name);
        $this->email->to($mail_to);
        $this->email->subject($mail_subject);
        $this->email->message($body);
        $this->email->set_mailtype('html');
        //$this->email->send();
        $this->enquiry_model->update_reply_status($rid);
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', lang('admin_mail_msg'));

        //redirect('sitepanel/enquiry', '');
        redirect('sitepanel/enquiry/send_reply/'.$res_data->id, '');

        /* End reply mail to user */
      }

      $data['heading_title'] = "Send Reply";
      $this->load->view('enquiry/view_send_enq_reply', $data);
    } else {
      redirect('sitepanel/enquiry/', '');
    }
  }

  public function getmembers(){
    $keyword = $this->input->get_post('keyword');
    $enqId = $this->input->get_post('enqId');
    $state = $this->input->get_post('state');
    $city = $this->input->get_post('city');
    $membership = $this->input->get_post('membership');
    $condtion = array();
    if ($keyword != '') {
      $condtion['keyword'] = $keyword;
    }
    if ($state != '') {
      $condtion['state'] = $state;
    }
    if ($city != '') {
      $condtion['city'] = $city;
    }
    if ($membership != '') {
      $condtion['membership'] = $membership;
    }

    $per_page = 100; //(int) $this->input->get_post('per_page');
    $offset = (int) $this->input->get_post('OffSet');

    $condtion['status'] = '1';
    $res_array = $this->members_model->get_members($per_page , $offset, $condtion);
    //trace($res_array);
    $data['total_list_rows'] = get_found_rows();
    $data['res_array'] = $res_array;

    //$res_array = $this->members_model->get_members('Unlimited', '', $condtion);
    //echo_sql();
    //trace($res_array);
    if (is_array($res_array) && !empty($res_array)) {
          foreach ($res_array as $pageVal) {
            $userId = $pageVal['customers_id'];
            $count = count_record('wps_enquiry', "FIND_IN_SET($userId,customers_id) AND id = '" . $enqId . "'");
            ?>
            <div class="row listpager" >
              <div class="col-md-3">
                <?php
                if ($count == 0) {
                  ?>
                  <input type="checkbox" class="enqCheck" name="cids[]" value="<?php echo $pageVal['customers_id']; ?>" />
                  <?php
                } else {
                  echo "<span class='btn btn-warning'>Enquiry Already Forwarded</span>";
                }
                ?>
              </div>
              <div class="col-md-3"><?php echo $pageVal['company_name']; ?></div>
              <div class="col-md-3"><?php echo $pageVal['user_email']; ?></div>
              <div class="col-md-3"><?php echo $pageVal['mobile_number']; ?></div>
            </div>
            <?php
          }
    } else {
      echo '<div class="row"><div class="col-md-12">No Result Found!</div></div>';
    }
  }

  public function ajax_load_forword_member_listing() {
    $data['title'] = 'Ajax Load Member';
    //For Paging
    $config['per_page'] = 10;
    $offset = $this->input->get_post('stOffSet');
    $page_segment = find_paging_segment();

    $keyword = $this->input->get_post('keyword');
    $enqId = $this->input->get_post('enqId');
    $state = $this->input->get_post('state');
    $city = $this->input->get_post('city');
    $membership = $this->input->get_post('membership');
    $condtion = array();
    if ($keyword != '') {
      $condtion['keyword'] = $keyword;
    }
    if ($state != '') {
      $condtion['state'] = $state;
    }
    if ($city != '') {
      $condtion['city'] = $city;
    }
    if ($membership != '') {
      $condtion['membership'] = $membership;
    }
    $condtion['status'] = '1';

    $res_array = $this->members_model->get_members($config['per_page'], $offset, $condtion);
    //trace($res_array);
    //$config['total_rows'] = get_found_rows();
    $config['total_rows'] = $this->members_model->total_rec_found;
    $data['res_array'] = $res_array;
    $this->load->view('sitepanel/enquiry/ajax_load_forword_member_listing', $data);
  }

  public function assignEnquiry() {
    $ids = $this->input->post('ids');
    $custIds = ',' . $ids;
    $custArry = explode(',', $ids);
    $enqID = $this->input->post('enqID');

    if ($ids) {
      $assignList = get_db_field_value('wps_enquiry', 'customers_id', "WHERE id = '" . $enqID . "'");
      $this->db->query("UPDATE wps_enquiry SET customers_id = '" . $assignList . $custIds . "' WHERE id = '" . $enqID . "'");

      foreach ($custArry as $k => $v) {
        $details = array();
        //$productID = get_db_field_value('wps_enquiry', 'products_id', "WHERE id = '" . $enqID . "'");
        $custEmail = get_db_field_value('wps_customers', 'user_email', "WHERE customers_id = '" . $v . "'");
        //$product = $this->db->query("SELECT u.user_email FROM wps_customers as u LEFT JOIN wps_products as p ON u.customers_id = p.customers_id WHERE p.products_id = '" . $productID . "'")->row_array();
        $dets = get_db_single_row('wps_enquiry', '*', "id = '" . $enqID . "'");

        $details['emailAddress'] = $dets['email'];
        $details['fullName'] = $dets['first_name'];
        $details['mobileNumber'] = $dets['mobile_number'];
        $details['enquiryMessage'] = $dets['message'];
        $details['productQuantity'] = $dets['quantity'];
        $details['post_url'] = $dets['post_url'];
        $details['productID'] = $dets['products_id'];


        //Insert into vendor table
        $this->db->query("INSERT INTO wps_vendor_enquiry SET id = '" . $enqID . "', customers_id = '" . $v . "'");

        sendCompEnquiryEmail('New Enquiry Received from Natural Therapy India', $emailIds = array("0" => $custEmail), $details);
      }
      echo 'Enquiry Forwarded to selected Companies successfully!';
    } else {
      echo 'Something went wrong, please try again!';
    }
  }

}

// End of controller