<?php

class Members extends Admin_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->model(array('members/members_model', 'products/product_model'));
    $this->load->library(array('safe_encrypt'));
    $this->config->set_item('menu_highlight', 'members management');
  }

  public function index() {

    $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'));
    $status = $this->input->get_post('status', TRUE);
    if ($status != '') {
      $condtion['status'] = $status;
    }
    $condtion['customer_type'] ='other';
    $res_array = $this->members_model->get_members($config['limit'], $offset, $condtion);
    //echo_sql();
    $total_record = get_found_rows();
    $data['page_links'] = admin_pagination($base_url, $total_record, $config['limit'], $offset);
    $data['heading_title'] = 'Manage Members';
    $data['pagelist'] = $res_array;
    $data['total_rec'] = $total_record;
    if ($this->input->post('status_action') != '') {
      $this->update_status('wps_customers', 'customers_id');
    }
    if ($this->input->post('set_as') != '') {
      $set_as = $this->input->post('set_as', TRUE);
      $this->set_as('wps_customers', 'customers_id', array($set_as => '1'));
    }
    if ($this->input->post('unset_as') != '') {
      $unset_as = $this->input->post('unset_as', TRUE);
      $this->set_as('wps_customers', 'customers_id', array($unset_as => '0'));
    }
    if ($this->input->post('action') == 'submit_excel') {
      $this->form_validation->set_rules('excel_file', 'Upload Excel File', 'required|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->members_model->add_bulk_upload_member($worksheet);

        if ($process_add === TRUE) {
          $this->session->set_userdata(array('msg_type' => 'success'));
          $this->session->set_flashdata('success', 'Excel file inserted successfully!!!');
          redirect('sitepanel/members', '');
        } else {
          $this->form_validation->_error_array['image'] = 'Uploading Failed. Please Try Again';
        }
      }
    }

    //trace($this->input->post());
    //print_r("hello");exit;

    $this->load->view('member/member_list_view', $data);
  }

  public function migrateData() {
    $this->db2 = $this->load->database('nti', TRUE);
    $business_nature_array = array("1" => "Buyer", "2" => "Supplier", "3" => "Buyer/Supplier");

    $categories = $this->db2->query("SELECT * FROM `category_tbl` WHERE catName LIKE '%Products' AND parentID = '0' AND catID NOT IN ('1244', '52', '3') Limit 0,1")->result_array();
    //trace($categories);
    //die;
    foreach ($categories as $cat) {
      $members = $this->db2->query("SELECt DISTINCT(memberID) FROM product_tbl WHERE allCategories LIKE '%^" . $cat['catID'] . "^%'")->result_array();
      foreach ($members as $mem) {

        $mem = $this->db2->query("SELECT * FROM member_tbl WHERE memberID = '" . $mem['memberID'] . "'")->row_array();
        $mobile = @$mem['mobileNo'];
        if ($mobile) {
          $ntimemId = $mem['memberID'];
          $count = count_record("wps_customers", "mobile_number = '" . $mobile . "'");
          if ($count == 0) {
            //Insert to New Database
            $city = get_db_field_value("wps_cities_list", "id", "WHERE city = '" . $mem['city'] . "'");
            $state = get_db_field_value("wps_states_list", "id", "WHERE LOWER(name) = '" . strtolower($mem['state']) . "'");
            $name = explode(' ', $mem['memberName']);
            $posted_data_customers = array(
                'title' => @$mem['nameTitle'],
                'user_name' => @$mem['email'],
                'password' => $this->safe_encrypt->encode(@$mem['pwd']),
                'mobile_number' => @$mem['mobileNo'],
                'first_name' => @$name[0],
                'last_name' => @$name[1],
                'company_name' => @$mem['companyName'],
                'profile_picture' => '',
                'designation' => '',
                'address' => @$mem['address'],
                'state' => $state,
                'city' => $city,
                'country' => @$mem['country'],
                'landmark' => '',
                'locality' => '',
                'zipcode' => @$mem['zipcode'],
                'alt_mobile' => @$mem['mobileNo2'],
                'user_email' => @$mem['email'],
                'alt_email' => @$mem['alternateEmail'],
                'website' => @$mem['website'],
                'status' => '1',
                'actkey' => md5($this->input->post('email')),
                'account_created_date' => @$mem['recvDate'],
                'current_login' => $this->config->item('config.date.time'),
                'ip_address' => $this->input->ip_address()
            );
            //trace($posted_data_customers);
            $wpsmemId = $this->members_model->safe_insert('wps_customers', $posted_data_customers, FALSE);
            $posted_customer_factsheet = array(
                'customers_id' => $wpsmemId,
                'business_nature' => ($mem['businessNature'] > 0) ? $business_nature_array[$mem['businessNature']] : '1',
                'business_nature_alt' => '',
                'ceo_name' => $mem['ownerName'],
                'registered_address' => $mem['address'],
                'about_company' => $mem['aboutUs'],
                'youtube_id' => '',
                'employee_count' => '1',
                'establishment_year' => $mem['yoe'],
                'legal_firm_status' => '1',
                'promoter_name' => '',
                'turnover' => $this->input->post('turnover'),
                'building_infrastructure' => '',
                "infra_img" => '',
                "infra_img2" => '',
                "infra_img3" => '',
                "infra_img4" => '',
                'premises_size' => '',
                'premises_unit' => '',
                'competitive_advantage' => '',
                'contract_manufacturing' => '',
                'testing_facilities' => '',
                'ie_code' => '',
                'banker' => '',
                'gst_no' => '',
                'customized_packaging' => '',
                'payment_mode' => '',
                'shipment_mode' => '',
            );
            //trace($posted_customer_factsheet);
            $this->members_model->safe_insert('wps_customers_factsheet', $posted_customer_factsheet, FALSE);
          } else {
            $mem = get_db_single_row('wps_customers', 'customers_id', "mobile_number = '" . $mobile . "' OR alt_mobile = '" . $mobile . "' OR user_name = '" . $mem['email'] . "'");
            $wpsmemId = $mem['customers_id'];
          }
          //Get Products
          $products = $this->db2->query("SELECT * FROM product_tbl WHERE memberID = '" . $ntimemId . "'")->result_array();
          foreach ($products as $pageVal) {
            $countpro = count_record("wps_products", "customers_id = '" . @$wpsmemId . "' AND product_name = '" . $pageVal['productName'] . "'");
            if ($countpro == 0) {
              $posted_data = array(
                  'customers_id' => @$wpsmemId,
                  'category_id' => '33',
                  'category_links' => '33',
                  'product_name' => $pageVal['productName'],
                  'product_code' => $pageVal['productCode'],
                  'moq' => $pageVal['minimumOrder'],
                  'product_price' => $pageVal['productPrice'],
                  'unit_value' => '',
                  'unit_measurement' => '',
                  'product_alt' => $pageVal['productName'],
                  'attribute_name' => '',
                  'attribute_value' => '',
                  'dispatch_port' => '',
                  'delivery_time' => '',
                  'packaging_details' => '',
                  'dashkeyword' => '',
                  'products_description' => $pageVal['completeDescription'],
                  'youtube_id' => '',
                  'product_added_date' => $this->config->item('config.date.time')
              );
              trace($posted_data);
              $productId = $this->product_model->safe_insert('wps_products', $posted_data, TRUE);
              if ($productId > 0) {
                $this->cbk_friendly_url = seo_url_title($pageVal['productName'] . '-' . $productId);
                $this->db->query("UPDATE wps_products SET friendly_url = '" . $this->cbk_friendly_url . "' WHERE products_id = '" . $productId . "'");

                //Create Meta
                $redirect_url = "products/detail";
                $meta_array = array(
                    'entity_type' => $redirect_url,
                    'entity_id' => $productId,
                    'page_url' => $this->cbk_friendly_url,
                    'meta_title' => get_text($pageVal['productName'], 80),
                    'meta_description' => get_text($pageVal['completeDescription']),
                    'meta_keyword' => get_keywords($pageVal['completeDescription'])
                );
                create_meta($meta_array);

                //Add media
                $this->db->query("INSERT INTO wps_products_media SET media = '" . $pageVal['image1'] . "', products_id = '" . $productId . "', media_date_added = '" . $this->config->item('config.date.time') . "', is_default = 'Y'");
              }
            }
          }
        }
      }

      $strCatQuery = "Update category_tbl SET migrateData = '1' WHERE catID = '" . $cat['catID'] . "'";
      trace($strCatQuery);
      $this->db2->query($strCatQuery);
    }
  }


  public function add() {
    $mobile_number = $this->input->post('mobile_number');
    $email = $this->input->post('email');
    $this->form_validation->set_rules('title', 'Title', 'trim|required');
    $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('last_name', 'Last Name.', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('mobile_number', 'Mobile No.', 'trim|required|max_length[15]|unique[wps_customers.mobile_number ="' . $mobile_number . '"]');
    $this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email|unique[wps_customers.user_email ="' . $email . '"]');
    $this->form_validation->set_rules('password', 'Password', 'trim|required');

    $this->form_validation->set_rules('company_name', 'Company Name', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('image1', 'Profile Picture', 'file_allowed_type[image]');
    $this->form_validation->set_rules('designation', 'Designation', 'trim');
    $this->form_validation->set_rules('address', 'Address', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('country', 'Country', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('state', 'State', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('city', 'City', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('locality', 'Locality', 'trim|max_length[220]');
    $this->form_validation->set_rules('landmark', 'Landmark', 'trim|max_length[220]');
    $this->form_validation->set_rules('zipcode', 'Pincode', 'trim|required|max_length[20]');
    $this->form_validation->set_rules('alt_mobile', 'Alternate Mobile No.', 'trim|max_length[15]');
    $this->form_validation->set_rules('alt_email', 'Alt. Email Address', 'trim|valid_email');
    $this->form_validation->set_rules('website', 'Website', 'trim|max_length[220]');
    $this->form_validation->set_rules('business_nature', 'Nature of business', 'required');
    $this->form_validation->set_rules('business_nature_alt', 'Alt. Nature of Business', '');
    $this->form_validation->set_rules('ceo_name', 'CEO Name.', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('registered_address', 'Registered Address', 'trim|required');
    $this->form_validation->set_rules('about_company', 'About Company', 'trim');
    $this->form_validation->set_rules('youtube_id', 'Youtube Video Link', 'trim');

    $this->form_validation->set_rules('employee_count', 'No. of Employees', 'trim');
    $this->form_validation->set_rules('establishment_year', 'Establishment Year', 'trim|');
    $this->form_validation->set_rules('legal_firm_status', 'Legal Status of Firm', 'trim|');
    $this->form_validation->set_rules('promoter_name', 'Promoter Name', 'trim|max_length[220]');
    $this->form_validation->set_rules('turnover', 'Company Turnover', 'trim');
    $this->form_validation->set_rules('building_infrastructure', 'Building Infrastructure', 'trim|max_length[220]');
    $this->form_validation->set_rules('premises_size', 'Company Premises Size', 'trim|max_length[160]');
    $this->form_validation->set_rules('competitive_advantage', 'Company USP', 'trim');
    $this->form_validation->set_rules('contract_manufacturing', 'Contract Manufaturing', 'trim||max_length[220]');
    $this->form_validation->set_rules('testing_facilities', 'Quality/Testing Facility', 'trim');
    $this->form_validation->set_rules('ie_code', 'IE CODE', 'trim|max_length[160]');

    $this->form_validation->set_rules('banker', 'Banker', 'trim|max_length[220]');
    $this->form_validation->set_rules('gst_no', 'GST No.', 'trim|max_length[15]');
    $this->form_validation->set_rules('customized_packaging', 'Customized Packaging', 'trim|');
    $this->form_validation->set_rules('payment_mode', 'Payment Mode', '');
    $this->form_validation->set_rules('shipment_mode', 'Shipment Mode', 'trim|max_length[220]');

    if ($this->form_validation->run() == TRUE) {
      $uploaded_file = "";
      if (!empty($_FILES) && $_FILES['image1']['name'] != '') {
        $config['max_size'] = '2048';
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('image1', 'user');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $uploaded_file = $uploaded_data['upload_data']['file_name'];
        }
      }

      $infra_uploaded_file1 = "";
      if (!empty($_FILES) && $_FILES['infra_img1']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('infra_img1', 'infra');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $infra_uploaded_file1 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $infra_uploaded_file2 = "";
      if (!empty($_FILES) && $_FILES['infra_img2']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('infra_img2', 'infra');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $infra_uploaded_file2 = $uploaded_data['upload_data']['file_name'];
        }
      }
      $infra_uploaded_file3 = "";
      if (!empty($_FILES) && $_FILES['infra_img3']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('infra_img3', 'infra');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $infra_uploaded_file3 = $uploaded_data['upload_data']['file_name'];
        }
      }
      $infra_uploaded_file4 = "";
      if (!empty($_FILES) && $_FILES['infra_img4']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('infra_img4', 'infra');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $infra_uploaded_file4 = $uploaded_data['upload_data']['file_name'];
        }
      }

      $password = $this->input->post('password');

      $posted_data_customers = array(
          'title' => $this->input->post('title'),
          'user_name' => $this->input->post('mobile_number'),
          'password' => $this->safe_encrypt->encode($password),
          'mobile_number' => $this->input->post('mobile_number'),
          'first_name' => $this->input->post('first_name'),
          'last_name' => $this->input->post('last_name'),
          'company_name' => $this->input->post('company_name'),
          'profile_picture' => $uploaded_file,
          'designation' => $this->input->post('designation'),
          'address' => $this->input->post('address'),
          'state' => $this->input->post('state'),
          'city' => $this->input->post('city'),
          'country' => $this->input->post('country'),
          'landmark' => $this->input->post('landmark'),
          'locality' => $this->input->post('locality'),
          'zipcode' => $this->input->post('zipcode'),
          'alt_mobile' => $this->input->post('alt_mobile'),
          'user_email' => $this->input->post('email'),
          'alt_email' => $this->input->post('alt_email'),
          'website' => $this->input->post('website'),
          'status' => '1',
          'actkey' => md5($this->input->post('email')),
          'account_created_date' => $this->config->item('config.date.time'),
          'current_login' => $this->config->item('config.date.time'),
          'ip_address' => $this->input->ip_address()
      );
      //trace($posted_data_customers);
      $customerID = $this->members_model->safe_insert('wps_customers', $posted_data_customers, FALSE);
      $posted_customer_factsheet = array(
          'customers_id' => $customerID,
          'business_nature' => $this->input->post('business_nature'),
          'business_nature_alt' => implode(',', $this->input->post('business_nature_alt')),
          'ceo_name' => $this->input->post('ceo_name'),
          'registered_address' => $this->input->post('registered_address'),
          'about_company' => $this->input->post('about_company'),
          'youtube_id' => $this->input->post('youtube_id'),
          'employee_count' => $this->input->post('employee_count'),
          'establishment_year' => $this->input->post('establishment_year'),
          'legal_firm_status' => $this->input->post('legal_firm_status'),
          'promoter_name' => $this->input->post('promoter_name'),
          'turnover' => $this->input->post('turnover'),
          'building_infrastructure' => $this->input->post('building_infrastructure'),
          "infra_img" => $infra_uploaded_file1,
          "infra_img2" => $infra_uploaded_file2,
          "infra_img3" => $infra_uploaded_file3,
          "infra_img4" => $infra_uploaded_file4,
          'premises_size' => $this->input->post('premises_size'),
          'premises_unit' => $this->input->post('premises_unit'),
          'competitive_advantage' => $this->input->post('competitive_advantage'),
          'contract_manufacturing' => $this->input->post('contract_manufacturing'),
          'testing_facilities' => $this->input->post('testing_facilities'),
          'ie_code' => $this->input->post('ie_code'),
          'banker' => $this->input->post('banker'),
          'gst_no' => $this->input->post('gst_no'),
          'customized_packaging' => $this->input->post('customized_packaging'),
          'payment_mode' => @implode(',', $this->input->post('payment_mode')),
          'shipment_mode' => $this->input->post('shipment_mode'),
      );
      //trace($posted_customer_factsheet);
      $this->members_model->safe_insert('wps_customers_factsheet', $posted_customer_factsheet, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', lang('success'));
      redirect('sitepanel/members', '');
    }


    $data['businessNatureAll'] = $this->config->item('businessNatureAll');
    $data['businessNature'] = $this->config->item('businessNature');
    $data['employeeCount'] = $this->config->item('employeeCount');
    $data['firmStatus'] = $this->config->item('firmStatus');
    $data['turnover'] = $this->config->item('turnover');
    $data['premises_unit'] = $this->config->item('premises_unit');
    $data['testingFacilities'] = $this->config->item('testingFacilities');
    $data['customizedPackaging'] = $this->config->item('customizedPackaging');
    $data['paymentMode'] = $this->config->item('paymentMode');
    $data['state'] = $this->db->query("select * from wps_states_list")->result_array();
    $data['city'] = $this->db->query("SELECT * FROM `wps_cities_list` WHERE status='1' and temp_title IN (SELECT page_url from wps_meta_tags where is_fixed = 'L') order by id asc")->result_array();
    $data['heading_title'] = 'Add Members';
    $this->load->view('member/view_member_add', $data);
  }

  public function edit() {
    $custId = (int) $this->uri->segment(4);
    if ($custId == '') {
      redirect('sitepanel/', '');
    }
    $mres = $this->members_model->get_member_row($custId);
    $factRes = $this->members_model->get_member_factsheet($custId);

    $mobile_number = $this->input->post('mobile_number');
    $email = $this->input->post('email');
    $this->form_validation->set_rules('title', 'Title', 'trim|required');
    $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('last_name', 'Last Name.', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('mobile_number', 'Mobile No.', 'trim|required|max_length[15]|unique[wps_customers.mobile_number ="' . $mobile_number . '" and wps_customers.customers_id!="' . $mres['customers_id'] . '"]');
    $this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email|unique[wps_customers.user_email ="' . $email . '" and wps_customers.customers_id!="' . $mres['customers_id'] . '"]');
    $this->form_validation->set_rules('password', 'Password', 'trim|required');

    $this->form_validation->set_rules('company_name', 'Company Name', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('image1', 'Profile Picture', 'file_allowed_type[image]');
    $this->form_validation->set_rules('designation', 'Designation', 'trim');
    $this->form_validation->set_rules('address', 'Address', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('country', 'Country', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('state', 'State', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('city', 'City', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('locality', 'Locality', 'trim|max_length[220]');
    $this->form_validation->set_rules('landmark', 'Landmark', 'trim|max_length[220]');
    $this->form_validation->set_rules('zipcode', 'Pincode', 'trim|required|max_length[20]');
    $this->form_validation->set_rules('alt_mobile', 'Alternate Mobile No.', 'trim|max_length[15]');
    $this->form_validation->set_rules('alt_email', 'Alt. Email Address', 'trim|valid_email');
    $this->form_validation->set_rules('website', 'Website', 'trim|max_length[220]');
    $this->form_validation->set_rules('business_nature', 'Nature of business', 'required');
    $this->form_validation->set_rules('business_nature_alt', 'Alt. Nature of Business', '');
    $this->form_validation->set_rules('ceo_name', 'CEO Name.', 'trim|required|max_length[220]');
    $this->form_validation->set_rules('registered_address', 'Registered Address', 'trim|required');
    $this->form_validation->set_rules('about_company', 'About Company', 'trim');
    $this->form_validation->set_rules('youtube_id', 'Youtube Video Link', 'trim');

    $this->form_validation->set_rules('employee_count', 'No. of Employees', 'trim');
    $this->form_validation->set_rules('establishment_year', 'Establishment Year', 'trim|');
    $this->form_validation->set_rules('legal_firm_status', 'Legal Status of Firm', 'trim|');
    $this->form_validation->set_rules('promoter_name', 'Promoter Name', 'trim|max_length[220]');
    $this->form_validation->set_rules('turnover', 'Company Turnover', 'trim');
    $this->form_validation->set_rules('building_infrastructure', 'Building Infrastructure', 'trim|max_length[220]');
    $this->form_validation->set_rules('premises_size', 'Company Premises Size', 'trim|max_length[160]');
    $this->form_validation->set_rules('competitive_advantage', 'Company USP', 'trim');
    $this->form_validation->set_rules('contract_manufacturing', 'Contract Manufaturing', 'trim||max_length[220]');
    $this->form_validation->set_rules('testing_facilities', 'Quality/Testing Facility', 'trim');
    $this->form_validation->set_rules('ie_code', 'IE CODE', 'trim|max_length[160]');

    $this->form_validation->set_rules('banker', 'Banker', 'trim|max_length[220]');
    $this->form_validation->set_rules('gst_no', 'GST No.', 'trim|max_length[15]');
    $this->form_validation->set_rules('customized_packaging', 'Customized Packaging', 'trim|');
    $this->form_validation->set_rules('payment_mode', 'Payment Mode', '');
    $this->form_validation->set_rules('shipment_mode', 'Shipment Mode', 'trim|max_length[220]');

    if ($this->form_validation->run() == TRUE) {
      $uploaded_file = $mres['profile_picture'];
      $unlink_image = array('source_dir' => "user", 'source_file' => $mres['profile_picture']);
      if (!empty($_FILES) && $_FILES['image1']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('image1', 'user');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $uploaded_file = $uploaded_data['upload_data']['file_name'];
          removeImage($unlink_image);
        }
      }

      $infra_uploaded_file1 = "";
      $unlink_image1 = array();
      if (isset($factRes['infra_img'])) {
        $infra_uploaded_file1 = $factRes['infra_img'];
        $unlink_image1 = array('source_dir' => "infra", 'source_file' => $factRes['infra_img']);
      }
      if (!empty($_FILES) && $_FILES['infra_img']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('infra_img', 'infra');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $infra_uploaded_file1 = $uploaded_data['upload_data']['file_name'];
          @removeImage($unlink_image1);
        }
      }

      $infra_uploaded_file2 = "";
      $unlink_image2 = array();
      if (isset($factRes['infra_img2'])) {
        $infra_uploaded_file2 = $factRes['infra_img2'];
        $unlink_image2 = array('source_dir' => "infra", 'source_file' => $factRes['infra_img2']);
      }
      if (!empty($_FILES) && $_FILES['infra_img2']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('infra_img2', 'infra');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $infra_uploaded_file2 = $uploaded_data['upload_data']['file_name'];
          @removeImage($unlink_image2);
        }
      }

      $infra_uploaded_file3 = "";
      $unlink_image3 = array();
      if (isset($factRes['infra_img3'])) {
        $infra_uploaded_file3 = $factRes['infra_img3'];
        $unlink_image3 = array('source_dir' => "infra", 'source_file' => $factRes['infra_img3']);
      }
      if (!empty($_FILES) && $_FILES['infra_img3']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('infra_img3', 'infra');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $infra_uploaded_file3 = $uploaded_data['upload_data']['file_name'];
          @removeImage($unlink_image3);
        }
      }

      $infra_uploaded_file4 = "";
      $unlink_image4 = array();
      if (isset($factRes['infra_img4'])) {
        $infra_uploaded_file4 = $factRes['infra_img4'];
        $unlink_image4 = array('source_dir' => "infra", 'source_file' => $factRes['infra_img4']);
      }
      if (!empty($_FILES) && $_FILES['infra_img4']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('infra_img4', 'infra');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $infra_uploaded_file4 = $uploaded_data['upload_data']['file_name'];
          @removeImage($unlink_image4);
        }
      }


      $password = $this->input->post('password');

      $posted_data_customers = array(
          'title' => $this->input->post('title'),
          'user_name' => $this->input->post('mobile_number'),
          'password' => $this->safe_encrypt->encode($password),
          'mobile_number' => $this->input->post('mobile_number'),
          'first_name' => $this->input->post('first_name'),
          'last_name' => $this->input->post('last_name'),
          'company_name' => $this->input->post('company_name'),
          'profile_picture' => $uploaded_file,
          'designation' => $this->input->post('designation'),
          'address' => $this->input->post('address'),
          'state' => $this->input->post('state'),
          'city' => $this->input->post('city'),
          'country' => $this->input->post('country'),
          'landmark' => $this->input->post('landmark'),
          'locality' => $this->input->post('locality'),
          'zipcode' => $this->input->post('zipcode'),
          'alt_mobile' => $this->input->post('alt_mobile'),
          'user_email' => $this->input->post('email'),
          'alt_email' => $this->input->post('alt_email'),
          'website' => $this->input->post('website'),
          'status' => '1',
          'actkey' => md5($this->input->post('email')),
          'account_created_date' => $this->config->item('config.date.time'),
          'current_login' => $this->config->item('config.date.time'),
          'ip_address' => $this->input->ip_address()
      );
      //trace($posted_data_customers);
      $where_ship = "customers_id = '" . $mres['customers_id'] . "'";
      $this->members_model->safe_update('wps_customers', $posted_data_customers, $where_ship, FALSE);

      $posted_customer_factsheet = array(
          'business_nature' => $this->input->post('business_nature'),
          'business_nature_alt' => implode(',', $this->input->post('business_nature_alt')),
          'ceo_name' => $this->input->post('ceo_name'),
          'registered_address' => $this->input->post('registered_address'),
          'about_company' => $this->input->post('about_company'),
          'youtube_id' => $this->input->post('youtube_id'),
          'employee_count' => $this->input->post('employee_count'),
          'establishment_year' => $this->input->post('establishment_year'),
          'legal_firm_status' => $this->input->post('legal_firm_status'),
          'promoter_name' => $this->input->post('promoter_name'),
          'turnover' => $this->input->post('turnover'),
          'building_infrastructure' => $this->input->post('building_infrastructure'),
          "infra_img" => $infra_uploaded_file1,
          "infra_img2" => $infra_uploaded_file2,
          "infra_img3" => $infra_uploaded_file3,
          "infra_img4" => $infra_uploaded_file4,
          'premises_size' => $this->input->post('premises_size'),
          'premises_unit' => $this->input->post('premises_unit'),
          'competitive_advantage' => $this->input->post('competitive_advantage'),
          'contract_manufacturing' => $this->input->post('contract_manufacturing'),
          'testing_facilities' => $this->input->post('testing_facilities'),
          'ie_code' => $this->input->post('ie_code'),
          'banker' => $this->input->post('banker'),
          'gst_no' => $this->input->post('gst_no'),
          'customized_packaging' => $this->input->post('customized_packaging'),
          'payment_mode' => @implode(',', $this->input->post('payment_mode')),
          'shipment_mode' => $this->input->post('shipment_mode'),
      );
      //trace($posted_customer_factsheet);
      $where_ship2 = "customers_id = '" . $mres['customers_id'] . "'";
      $this->members_model->safe_update('wps_customers_factsheet', $posted_customer_factsheet, $where_ship2, FALSE);
      // echo_sql();

      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', lang('success'));
      redirect('sitepanel/members', '');
    }


    $data['businessNatureAll'] = $this->config->item('businessNatureAll');
    $data['businessNature'] = $this->config->item('businessNature');
    $data['employeeCount'] = $this->config->item('employeeCount');
    $data['firmStatus'] = $this->config->item('firmStatus');
    $data['turnover'] = $this->config->item('turnover');
    $data['premises_unit'] = $this->config->item('premises_unit');
    $data['testingFacilities'] = $this->config->item('testingFacilities');
    $data['customizedPackaging'] = $this->config->item('customizedPackaging');
    $data['paymentMode'] = $this->config->item('paymentMode');
    $data['state'] = $this->db->query("select * from wps_states_list")->result_array();
    $data['city'] = $this->db->query("SELECT * FROM `wps_cities_list` WHERE status='1' and temp_title IN (SELECT page_url from wps_meta_tags where is_fixed = 'L') order by id asc")->result_array();
    $data['heading_title'] = 'Edit Members';
    $data['mres'] = $mres;
    $data['factRes'] = $factRes;
    $this->load->view('member/view_member_edit', $data);
  }

  public function details() {



    $customers_id = (int) $this->uri->segment(4);

    $mres = $this->members_model->get_member_row($customers_id);



    $data['heading_title'] = 'Member Details';

    $data['mres'] = $mres;

    $this->load->view('member/view_member_detail', $data);
  }

  public function ip_details() {

    $customers_id = (int) $this->uri->segment(4);

    $mres = $this->db->query("select * from wps_ip_details where member_id = '" . $customers_id . "' ")->result_array();

    $data['heading_title'] = 'Members Login Details';

    $data['mres'] = $mres;

    $this->load->view('member/view_member_ip_detail', $data);
  }

  public function support_ticket($page = NULL) {



    $post_per_page = $this->input->post('per_page');



    if ($post_per_page != '') {

      $post_per_page = applyFilter('NUMERIC_GT_ZERO', $post_per_page);

      if ($post_per_page > 0) {

        $config['per_page'] = $post_per_page;
      } else {

        $config['per_page'] = $this->config->item('per_page');
      }
    } else {

      $config['per_page'] = $this->config->item('per_page');
    }



    $offset = $this->uri->segment(4, 0);

    $res_array = $this->members_model->get_support_ticket($offset, $config['per_page']);

    $total_record = get_found_rows();



    if ($this->input->post('delete_ticket') != '' && $this->input->post('delete_ticket') == 'Delete') {

      $arr_ids = $this->input->post('arr_ids');

      $str_ids = implode(',', $arr_ids);

      $where = "id IN( $str_ids)";

      $this->members_model->delete_in('wps_ticket_support', $where, FALSE);
    }





    $data['page_links'] = admin_pagination("members/support_ticket/pages/", $total_record, $config['per_page']);

    $data['heading_title'] = 'Manage Support Ticket';

    $data['pagelist'] = $res_array;

    $data['total_rec'] = $total_record;

    $this->load->view('member/support_ticket_view', $data);
  }

  public function ticket_reply() {

    $rid = $this->uri->segment(4);

    $res_data = $this->db->get_where('wps_ticket_support', array('id' => $rid))->row();



    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() == FALSE) {

        $data['heading_title'] = "Send Reply";

        $data['res'] = $res_data;

        $this->load->view('member/support_ticket_reply_view', $data);
      } else {

        /* Reply  mail to user */



        $admin_email = get_site_email();

        $mail_to = $res_data->email;

        $mail_subject = $this->input->post('subject');

        $from_email = $admin_email->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 ";



        $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->db->where('id', $res_data->id);

        $this->db->update('wps_ticket_support', array('replyed' => 'Y'));



        $this->session->set_userdata(array('msg_type' => 'success'));

        $this->session->set_flashdata('success', lang('admin_mail_msg'));





        redirect('sitepanel/members/ticket_reply/' . $res_data->id, '');



        /* End reply mail to user */
      }
    }
  }

}

// End of controller