<?php

class Kisans extends Admin_Controller {

  public function __construct() { //
    parent::__construct();
    $this->load->model(array('kisans/kisans_model', 'kisan_sahayak_model', 'products/product_model'));
    $this->load->helper('category/category');
    $this->load->library(array('safe_encrypt'));
    $this->config->set_item('menu_highlight', 'kisans management');
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");
  }

  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'] ='kisan';

    if($this->session->userdata('admin_type')=='2'){  //when district head login
      $condtion['district_head_id'] = $this->session->userdata('admin_id');
    }
    if($this->session->userdata('admin_type')=='3'){  //when kisaan mitra login
      $condtion['district_head_id'] = $this->session->userdata('district_head_id');
      $condtion['kisan_mitra_id'] = $this->session->userdata('admin_id');
    }
    if($this->session->userdata('admin_type')=='4'){  //when KM sahyogi login / kisan sahayak
      $condtion['district_head_id'] = $this->session->userdata('district_head_id');
      $condtion['kisan_mitra_id'] = $this->session->userdata('kisan_mitra_id');
      $condtion['kisan_sahayak_id'] = $this->session->userdata('admin_id');
    }
    
      $res_array = $this->kisans_model->get_kisans($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 Kisaans';
    $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->kisans_model->add_bulk_upload_kisan($worksheet);

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

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

    $this->load->view('kisan/kisan_list_view', $data);
  }



  public function add() {

    $mobile_number = $this->input->post('mobile_number');
    //$email = $this->input->post('email');
    
    $this->form_validation->set_rules('district_head_id', 'District Head', 'trim|required');
    $this->form_validation->set_rules('kisan_mitra_id', 'Block Head', 'trim|required'); //Kisaan Mitra
    $this->form_validation->set_rules('kisan_sahayak_id', 'Kisaan Mitra', 'trim|required'); //KM Sahyogi
    $this->form_validation->set_rules('country_id', 'Country', 'trim|required');
    $this->form_validation->set_rules('state_id', 'State', 'trim|required');
    $this->form_validation->set_rules('city_id', 'District', 'trim|required');
    $this->form_validation->set_rules('block_id', 'Block', 'trim|required');
    $this->form_validation->set_rules('panchayat_id', 'Panchayat', 'trim|required');
    $this->form_validation->set_rules('village_id', 'Village', 'trim|required');

    $this->form_validation->set_rules('first_name', 'Kisaan Name', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('fathers_name', "Father's Name", 'trim|required|max_length[80]');
    $this->form_validation->set_rules('birth_date', "D.O.B.", '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('alt_name', 'Alternate Name', 'trim|max_length[80]');
    $this->form_validation->set_rules('alt_mobile', 'Alternate Mobile No.', 'trim|max_length[15]');
    $this->form_validation->set_rules('relationship', 'Relationship', 'trim|max_length[80]');
    $this->form_validation->set_rules('land_size_owned', 'Land Size (Owned)', 'trim|required|is_valid_amount|max_length[20]');
    $this->form_validation->set_rules('land_size_owned_unit', 'Land Size Unit (Owned) ', 'trim|required');
    $this->form_validation->set_rules('land_size_leased', 'Land Size (Leased)', 'trim|required|is_valid_amount|max_length[20]');
    $this->form_validation->set_rules('land_size_leased_unit', 'Land Size Unit (Leased)', 'trim|required');
    $this->form_validation->set_rules('total_land_size', 'Total Land Size', 'trim|required|is_valid_amount|max_length[25]');
    $this->form_validation->set_rules('total_land_size_unit', 'Total Land Size Unit', 'trim|required');
    $this->form_validation->set_rules('current_annual_income', 'Current Annual Income', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('major_issues', 'Major Issues/Problems/Challenges Faced by Farmer', 'trim|required|max_length[499]');
    // $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('image1', 'Profile Picture', 'file_allowed_type[image]');


    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 = "";
      $infra_uploaded_file2 = "";
      $infra_uploaded_file3 = "";
      $infra_uploaded_file4 = "";
      

      $aadhar_card = "";
      if (!empty($_FILES) && $_FILES['aadhar_card']['name'] != '') {
        $config['max_size'] = '2048';
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('aadhar_card', 'user');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $aadhar_card = $uploaded_data['upload_data']['file_name'];
        }
      }
      $pan_card = "";
      if (!empty($_FILES) && $_FILES['pan_card']['name'] != '') {
        $config['max_size'] = '2048';
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('pan_card', 'user');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pan_card = $uploaded_data['upload_data']['file_name'];
        }
      }
      $cancelled_Cheque = "";
      if (!empty($_FILES) && $_FILES['cancelled_Cheque']['name'] != '') {
        $config['max_size'] = '2048';
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('cancelled_Cheque', 'user');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $cancelled_Cheque = $uploaded_data['upload_data']['file_name'];
        }
      }
      $address_proof = "";
      if (!empty($_FILES) && $_FILES['address_proof']['name'] != '') {
        $config['max_size'] = '2048';
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('address_proof', 'user');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $address_proof = $uploaded_data['upload_data']['file_name'];
        }
      }
      

      $password = '';

      $posted_data_customers = array(
          'district_head_id' => $this->input->post('district_head_id'),
          'kisan_mitra_id' => $this->input->post('kisan_mitra_id'),
          'kisan_sahayak_id' => $this->input->post('kisan_sahayak_id'),
          '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'),
          'fathers_name' => $this->input->post('fathers_name'),
          'birth_date' => $this->input->post('birth_date'),
          'profile_picture' => $uploaded_file,
          'alt_name' => $this->input->post('alt_name'),
          'alt_mobile' => $this->input->post('alt_mobile'),
          'relationship' => $this->input->post('relationship'),
          'land_size_owned' => $this->input->post('land_size_owned'),
          'land_size_owned_unit' => $this->input->post('land_size_owned_unit'),
          'land_size_leased' => $this->input->post('land_size_leased'),
          'land_size_leased_unit' => $this->input->post('land_size_leased_unit'),
          'total_land_size' => $this->input->post('total_land_size'),
          'current_annual_income' => $this->input->post('current_annual_income'),
          'major_issues' => $this->input->post('major_issues'),
          'aadhar_card' => $aadhar_card,
          'pan_card' => $pan_card,
          'cancelled_Cheque' => $cancelled_Cheque,
          'address_proof' => $address_proof,
          'country_id' => $this->input->post('country_id'),
          'state_id' => $this->input->post('state_id'),
          'city_id' => $this->input->post('city_id'),
          'block_id' => $this->input->post('block_id'),
          'panchayat_id' => $this->input->post('panchayat_id'),
          'village_id' => $this->input->post('village_id'),
          'status' => '1',
          'add_admin_type' => $this->session->userdata('admin_type'),
          'actkey' => md5($this->input->post('mobile_number')),
          '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);
      //SELECT * FROM `wps_kisan_crops` WHERE 1`id`, `category_id`, `customers_id`, `category_links`, `qty_per_year`, `selling_price_msp`, `selling_month`
      $customerID = $this->kisans_model->safe_insert('wps_customers', $posted_data_customers, FALSE);


      //password generated
      $passname=substr(trim($this->input->post('first_name')),0,10);
      $password=$passname.$customerID;
      $posted_password = array(
        'password' => $this->safe_encrypt->encode($password)       
      );
      //trace($posted_customer_factsheet);
      $where_pass = "customers_id = '" . $customerID . "'";
      $this->kisans_model->safe_update('wps_customers', $posted_password, $where_pass, FALSE);
      
      //insert crops data
      $postCategory = $this->input->post('category_id');
      $category_links = "";
      $catlink = $ctl = "";
      foreach ($postCategory as $ctv) {
        $catlink = get_parent_categories($ctv, "AND status='1'", "category_id,parent_id");
        $ctl = array_keys($catlink);
        $category_links .= implode(",", $ctl) . ',';
      }
      $category_links = substr($category_links, 0, -1);

      $posted_kisan_crops = array(
        'customers_id' => $customerID,
        'category_id' => implode(',', $this->input->post('category_id')),
        'category_links' => $category_links,
        'qty_per_year' => implode(',', $this->input->post('qty_per_year')),
        'selling_price_msp' => implode(',', $this->input->post('selling_price_msp')),
        'selling_month' => implode(',', $this->input->post('selling_month')),
    );
    //trace($posted_customer_factsheet);
    $this->kisans_model->safe_insert('wps_kisan_crops', $posted_kisan_crops, 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->kisans_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/kisans', '');
    }

    
    $data['landSizeUnitArray'] = $this->config->item('landSizeUnitArray');
    $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['country'] = $this->db->query("SELECT id,name FROM wps_countries_list WHERE status='1' ORDER BY name ASC")->result_array();
    $data['states'] = $this->db->query("SELECT id,name FROM wps_states_list WHERE status='1' ORDER BY name ASC")->result_array();
    $data['cities'] = $this->db->query("SELECT id,city FROM wps_cities_list WHERE status='1' ORDER BY city ASC")->result_array();
    $data['blocks'] = $this->db->query("SELECT id,name FROM `wps_blocks_list` WHERE status='1' order by name asc")->result_array();
    $data['panchayats'] = $this->db->query("SELECT id,name FROM `wps_panchayats_list` WHERE status='1' order by name asc")->result_array();
    $data['villages'] = $this->db->query("SELECT id,name FROM `wps_villages_list` WHERE status='1' order by name asc")->result_array();

    if($this->input->get_post('kisan_mitra_id')){
      $conditions_mitra='AND parent_admin_id="'.$this->input->get_post('kisan_mitra_id').'"';
    }else{
      $conditions_mitra='';
    }

    $data['district_heads'] = $this->db->query("SELECT admin_id,admin_name FROM wps_admin WHERE admin_type='2' AND status='1' ORDER BY admin_name ASC")->result_array();
    $data['kisan_mitras'] = $this->db->query("SELECT admin_id,admin_name FROM wps_admin WHERE admin_type='3' AND status='1' ORDER BY admin_name ASC")->result_array();
    $data['kisan_sahayaks'] = $this->db->query("SELECT admin_id,admin_name FROM wps_admin WHERE admin_type='4' AND status='1' $conditions_mitra ORDER BY admin_name ASC")->result_array();
    $data['heading_title'] = 'Add kisaan';
    $this->load->view('kisan/view_kisan_add', $data);
  }

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

    $mres = $this->kisans_model->get_kisan_row($custId);
    $factRes = $this->kisans_model->get_kisan_factsheet($custId);
    $cropsRes = $this->kisans_model->get_kisan_crops($custId);

    $mobile_number = $this->input->post('mobile_number');
    //$email = $this->input->post('email');
    $this->form_validation->set_rules('district_head_id', 'District Head', 'trim|required');
    $this->form_validation->set_rules('kisan_mitra_id', 'Block Head', 'trim|required'); //Kisaan Mitra
    $this->form_validation->set_rules('kisan_sahayak_id', 'Kisaan Mitra', 'trim|required'); //KM Sahyogi
    $this->form_validation->set_rules('country_id', 'Country', 'trim|required');
    $this->form_validation->set_rules('state_id', 'State', 'trim|required');
    $this->form_validation->set_rules('city_id', 'District', 'trim|required');
    $this->form_validation->set_rules('block_id', 'Block', 'trim|required');
    $this->form_validation->set_rules('panchayat_id', 'Panchayat', 'trim|required');
    $this->form_validation->set_rules('village_id', 'Village', 'trim|required');

    $this->form_validation->set_rules('first_name', 'Kisaan Name', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('fathers_name', "Father's Name", 'trim|required|max_length[80]');
    $this->form_validation->set_rules('birth_date', "D.O.B.", '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 customers_id!="'.$custId.'"]');
    $this->form_validation->set_rules('alt_name', 'Alternate Name', 'trim|max_length[80]');
    $this->form_validation->set_rules('alt_mobile', 'Alternate Mobile No.', 'trim|max_length[15]');
    $this->form_validation->set_rules('relationship', 'Relationship', 'trim|max_length[80]');
    $this->form_validation->set_rules('land_size_owned', 'Land Size (Owned)', 'trim|required|is_valid_amount|max_length[20]');
    $this->form_validation->set_rules('land_size_owned_unit', 'Land Size Unit (Owned) ', 'trim|required');
    $this->form_validation->set_rules('land_size_leased', 'Land Size (Leased)', 'trim|required|is_valid_amount|max_length[20]');
    $this->form_validation->set_rules('land_size_leased_unit', 'Land Size Unit (Leased)', 'trim|required');
    $this->form_validation->set_rules('total_land_size', 'Total Land Size', 'trim|required|is_valid_amount|max_length[25]');
    $this->form_validation->set_rules('total_land_size_unit', 'Total Land Size Unit', 'trim|required');
    $this->form_validation->set_rules('current_annual_income', 'Current Annual Income', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('major_issues', 'Major Issues/Problems/Challenges Faced by Farmer', 'trim|required|max_length[499]');

    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);
        }
      }

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

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

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

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

      //$password = $this->input->post('password');
      $password = '';
      $posted_data_customers = array(
          'district_head_id' => $this->input->post('district_head_id'),
          'kisan_mitra_id' => $this->input->post('kisan_mitra_id'),
          'kisan_sahayak_id' => $this->input->post('kisan_sahayak_id'),
          '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'),
          'fathers_name' => $this->input->post('fathers_name'),
          'birth_date' => $this->input->post('birth_date'),
          'profile_picture' => $uploaded_file,
          'alt_name' => $this->input->post('alt_name'),
          'alt_mobile' => $this->input->post('alt_mobile'),
          'relationship' => $this->input->post('relationship'),
          'land_size_owned' => $this->input->post('land_size_owned'),
          'land_size_owned_unit' => $this->input->post('land_size_owned_unit'),
          'land_size_leased' => $this->input->post('land_size_leased'),
          'land_size_leased_unit' => $this->input->post('land_size_leased_unit'),
          'total_land_size' => $this->input->post('total_land_size'),
          'current_annual_income' => $this->input->post('current_annual_income'),
          'major_issues' => $this->input->post('major_issues'),
          'aadhar_card' => $aadhar_card,
          'pan_card' => $pan_card,
          'cancelled_Cheque' => $cancelled_Cheque,
          'address_proof' => $address_proof,
          'country_id' => $this->input->post('country_id'),
          'state_id' => $this->input->post('state_id'),
          'city_id' => $this->input->post('city_id'),
          'block_id' => $this->input->post('block_id'),
          'panchayat_id' => $this->input->post('panchayat_id'),
          'village_id' => $this->input->post('village_id'),
          'actkey' => md5($this->input->post('mobile_number')),
          '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->kisans_model->safe_update('wps_customers', $posted_data_customers, $where_ship, FALSE);

      //update crops info

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

      $posted_kisan_crops = array(
        'customers_id' => $mres['customers_id'],
        'category_id' => implode(',', $this->input->post('category_id')),
        'category_links' => $category_links,
        'qty_per_year' => implode(',', $this->input->post('qty_per_year')),
        'selling_price_msp' => implode(',', $this->input->post('selling_price_msp')),
        'selling_month' => implode(',', $this->input->post('selling_month')),
    );
    //trace($posted_customer_factsheet);
    $where_crops = "customers_id = '" . $mres['customers_id'] . "'";
    $this->kisans_model->safe_update('wps_kisan_crops', $posted_kisan_crops, $where_crops, 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->kisans_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/kisans', '');
    }

    $data['landSizeUnitArray'] = $this->config->item('landSizeUnitArray');
    $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');

    if($this->input->post('country_id')){
      $country_id=$this->input->post('country_id');
    }else{
      $country_id=$mres['country_id'];
    }
    if($this->input->post('state_id')){
      $state_id=$this->input->post('state_id');
    }else{
      $state_id=$mres['state_id'];
    }

    if($this->input->post('city_id')){
      $city_id=$this->input->post('city_id');
    }else{
      $city_id=$mres['city_id'];
    }

    if($this->input->post('block_id')){
      $block_id=$this->input->post('block_id');
    }else{
      $block_id=$mres['block_id'];
    }
    if($this->input->post('panchayat_id')){
      $panchayat_id=$this->input->post('panchayat_id');
    }else{
      $panchayat_id=$mres['panchayat_id'];
    }

    if($this->input->get_post('district_head_id')){
      $conditions_district_head='AND district_head_id="'.$this->input->get_post('district_head_id').'"';
    }else{
      //$conditions_district_head='';
      $conditions_district_head='AND district_head_id="'.$mres['district_head_id'].'"';
    }
    if($this->input->get_post('kisan_mitra_id')){
      $conditions_kisan_mitras='AND kisan_mitra_id="'.$this->input->get_post('kisan_mitra_id').'"';
    }else{
      //$conditions_kisan_mitras='';
      $conditions_kisan_mitras='AND kisan_mitra_id="'.$mres['kisan_mitra_id'].'"';
    }


   // $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['states'] = $this->db->query("SELECT id,name FROM wps_states_list WHERE country_id='".$country_id."' AND status='1' ORDER BY name ASC")->result_array();
    $data['cities'] = $this->db->query("SELECT id,city FROM wps_cities_list WHERE country_id='".$country_id."' AND state_id='".$state_id."' AND status='1' ORDER BY city ASC")->result_array();
    $data['blocks'] = $this->db->query("SELECT id,name FROM `wps_blocks_list` WHERE country_id='".$country_id."' AND state_id='".$state_id."' AND city_id='".$city_id."' AND status='1' order by name asc")->result_array();
    $data['panchayats'] = $this->db->query("SELECT id,name FROM `wps_panchayats_list` WHERE country_id='".$country_id."' AND state_id='".$state_id."' AND city_id='".$city_id."' AND block_id='".$block_id."' AND status='1' order by name asc")->result_array();
    $data['villages'] = $this->db->query("SELECT id,name FROM `wps_villages_list` WHERE country_id='".$country_id."' AND state_id='".$state_id."' AND city_id='".$city_id."' AND block_id='".$block_id."' AND panchayat_id='".$panchayat_id."' AND status='1' order by name asc")->result_array();

    $data['district_heads'] = $this->db->query("SELECT admin_id,admin_name FROM wps_admin WHERE admin_type='2' AND status='1' ORDER BY admin_name ASC")->result_array();
    $data['kisan_mitras'] = $this->db->query("SELECT admin_id,admin_name FROM wps_admin WHERE admin_type='3' AND status='1' $conditions_district_head ORDER BY admin_name ASC")->result_array();

    $data['kisan_sahayaks'] = $this->db->query("SELECT admin_id,admin_name FROM wps_admin WHERE admin_type='4' AND status='1' $conditions_kisan_mitras ORDER BY admin_name ASC")->result_array();

    $data['heading_title'] = 'Edit kisaan';
    $data['mres'] = $mres;
    $data['cropsRes'] = $cropsRes;
    $data['factRes'] = $factRes; //

    $this->load->view('kisan/view_kisan_edit', $data);
  }

  public function details() {



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

    //$mres = $this->kisans_model->get_kisan_row($customers_id);
    $mres = $this->db->query("select ad.*,c.name as country_name,s.name as state_name,d.city as district_name,b.name as block_name,p.name as panchayat_name,v.name as village_name,k.admin_name as kisan_mitra_name,k.admin_name as kisan_sahayak_name,dh.admin_name as district_head_name from  wps_customers as ad join wps_countries_list as c on ad.country_id=c.id join wps_states_list as s on ad.state_id=s.id join wps_cities_list as d on ad.city_id=d.id join wps_blocks_list as b on ad.block_id=b.id join wps_panchayats_list as p on ad.panchayat_id=p.id join wps_villages_list as v on ad.village_id=v.id join wps_admin as k on ad.kisan_mitra_id=k.admin_id join wps_admin as ks on ad.kisan_sahayak_id=ks.admin_id join wps_admin as dh on ad.district_head_id=dh.admin_id where ad.customers_id = '" . $customers_id . "' ")->row_array();


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

    $data['mres'] = $mres;

    $this->load->view('kisan/view_kisan_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'] = 'kisans Login Details';

    $data['mres'] = $mres;

    $this->load->view('kisan/view_kisan_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->kisans_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->kisans_model->delete_in('wps_ticket_support', $where, FALSE);
    }





    $data['page_links'] = admin_pagination("kisans/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('kisan/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('kisan/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/kisans/ticket_reply/' . $res_data->id, '');



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

  // update for kisan sahayak
  public function edit_password() {

    $this->form_validation->set_rules('old_pass', 'Old Password', 'required|max_length[80]');
    $this->form_validation->set_rules('new_pass', 'New Password', 'required|valid_password|max_length[80]');
    $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[new_pass]|max_length[80]');
    if ($this->form_validation->run() == TRUE) {
      $this->kisan_sahayak_model->update_password($this->input->post('old_pass'),$this->session->userdata('admin_id'));
      redirect('sitepanel/kisans/edit_password', '');
    }

    $data['heading_title'] = 'Update Password';
    $data['mres'] = $this->kisan_sahayak_model->get_kisan_sahayak_row($this->session->userdata('admin_id'));
    $this->load->view('kisan_sahayak/edit_password_view', $data);
  }

  // update for kisan sahayak

  public function edit_profile() {

    $mres = $this->kisan_sahayak_model->get_kisan_sahayak_row($this->session->userdata('admin_id'));

    $this->form_validation->set_rules('admin_name', 'Name', 'trim|required|max_length[80]');
    $this->form_validation->set_rules('image1', 'Upload Photo', 'file_allowed_type[image]');
    $this->form_validation->set_rules('phone', 'Mobile Number', 'trim|required|max_length[15]');
    $this->form_validation->set_rules('contact_phone', 'Alt Mobile Number', 'trim|max_length[15]');
    $this->form_validation->set_rules('admin_email', 'Personal Email ID', 'trim|required|valid_email');
    $this->form_validation->set_rules('contact_email', 'Official Email ID', 'trim|valid_email');
    $this->form_validation->set_rules('address', 'Address', 'trim|max_length[255]');
    $this->form_validation->set_rules('pincode', 'PIN Code', 'trim|max_length[15]');
    //$this->form_validation->set_rules('country_id', 'Country', 'trim|required');
    //$this->form_validation->set_rules('state_id', 'State', 'trim|required');
    //$this->form_validation->set_rules('city_id', 'District', 'trim|required');
    //$this->form_validation->set_rules('block_id', 'Block', 'trim|required');
    //$this->form_validation->set_rules('panchayat_id', 'Panchayat', 'trim|required');
    //$this->form_validation->set_rules('village_id', 'Village', 'trim|required');
    $this->form_validation->set_rules('aadhar_card', 'Aadhar Card', 'file_allowed_type[image]');
    $this->form_validation->set_rules('pan_card', 'PAN Card', 'file_allowed_type[image]');
    $this->form_validation->set_rules('cancelled_Cheque', 'Cancelled Cheque', 'file_allowed_type[image]');
    $this->form_validation->set_rules('address_proof', 'Address Proof', 'file_allowed_type[image]');
    
    $this->form_validation->set_rules('has_laptop', 'Has Laptop', 'trim');
    $this->form_validation->set_rules('has_smartphone', 'Has Smartphone', 'trim');
    $this->form_validation->set_rules('has_vehicle', 'Has Vehicle', 'trim'); 
    $this->form_validation->set_rules('which_vehicle[]', 'Which Vehicle', 'trim');

    //$this->form_validation->set_rules('facebook', 'Facebook Link', 'trim|max_lenght[240]');
    //$this->form_validation->set_rules('twitter', 'Twitter Link', 'trim|max_lenght[240]');
    //$this->form_validation->set_rules('linkedin', 'Linkedin Link', 'trim|max_lenght[240]');
    //$this->form_validation->set_rules('youtube', 'Youtube Channel Link', 'trim|max_lenght[240]');
    //$this->form_validation->set_rules('whatsapp', 'WhatsApp Number', 'trim|max_lenght[240]');

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

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

      $aadhar_card = $mres['aadhar_card'];
      $unlink_image = array('source_dir' => "kisan_sahayak", 'source_file' => $mres['aadhar_card']);
      if (!empty($_FILES) && $_FILES['aadhar_card']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('aadhar_card', 'kisan_sahayak');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $aadhar_card = $uploaded_data['upload_data']['file_name'];
          removeImage($unlink_image);
        }
      }

      $pan_card = $mres['pan_card'];
      $unlink_image = array('source_dir' => "kisan_sahayak", 'source_file' => $mres['pan_card']);
      if (!empty($_FILES) && $_FILES['pan_card']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('pan_card', 'kisan_sahayak');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pan_card = $uploaded_data['upload_data']['file_name'];
          removeImage($unlink_image);
        }
      }

      $cancelled_Cheque = $mres['cancelled_Cheque'];
      $unlink_image = array('source_dir' => "kisan_sahayak", 'source_file' => $mres['cancelled_Cheque']);
      if (!empty($_FILES) && $_FILES['cancelled_Cheque']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('cancelled_Cheque', 'kisan_sahayak');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $cancelled_Cheque = $uploaded_data['upload_data']['file_name'];
          removeImage($unlink_image);
        }
      }

      $address_proof = $mres['address_proof'];
      $unlink_image = array('source_dir' => "kisan_sahayak", 'source_file' => $mres['address_proof']);
      if (!empty($_FILES) && $_FILES['aadhar_card']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('address_proof', 'kisan_sahayak');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $address_proof = $uploaded_data['upload_data']['file_name'];
          removeImage($unlink_image);
        }
      }
      
      $which_vehicle='';
      if(!empty($this->input->post('which_vehicle')) && $this->input->post('has_vehicle')=='Yes'){
        $which_vehicle=implode(",",$this->input->post('which_vehicle'));
      }
      
      $this->kisans_model->update_profile($mres['admin_id'],$uploaded_file,$aadhar_card,$pan_card,$cancelled_Cheque,$address_proof,$which_vehicle);      redirect('sitepanel/kisans/edit_profile', '');
    }
    $data['heading_title'] = 'Edit Profile';
    $data['mres'] = $mres;
    $this->load->view('kisan_sahayak/edit_profile_view', $data);
  }

}

// End of controller