<?php

class Members extends Private_Controller {

  private $mId;

  public function __construct() {
    parent::__construct();
    $this->load->model(array('members/members_model', 'users/users_model', 'order/order_model', 'products/product_model'));
    $this->load->helper(array('cart/cart', 'products/product'));
    $this->load->library(array('safe_encrypt', 'Dmailer', 'cart'));
    $this->form_validation->set_error_delimiters("<div class='required red'>", "</div>");
  }

  public function index() {
    redirect('members/myaccount', '');
  }

  public function myaccount() {
    $config['per_page'] = $this->config->item('per_page');
    $offset = $this->uri->segment(3, 0);
    $mres = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $data['mres'] = $mres;

    //My Recent Orders
    $condtion = "AND customers_id = '" . $this->userId . "'  and (payment_status='Paid' Or payment_method='Cash' Or payment_method='COD')";
    $res_array = $this->order_model->get_orders('0', '3', $condtion);
    $data['orders'] = $res_array;


    $data['title'] = "My Account";
    $this->load->view('view_member_myaccount', $data);
  }

  public function myprofile() {
      $config['per_page'] = $this->config->item('per_page');
    $offset = $this->uri->segment(3, 0);
    $mres = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $data['mres'] = $mres;

    //My Recent Orders
    $condtion = "AND customers_id = '" . $this->userId . "'  and (payment_status='Paid' Or payment_method='Cash' Or payment_method='COD')";
    $res_array = $this->order_model->get_orders('0', '3', $condtion);
    $data['orders'] = $res_array;
  $data['title'] = "My Profile";
    $this->load->view('members/view_member_myprofile', $data); 
  }

  public function order_details() {
    $id = (int) $this->uri->segment(3);
    $order_res = $this->order_model->get_order_master($id);
    $order_details_res = $this->order_model->get_order_detail($id);

    $data['order_res'] = $order_res;
    $data['order_details'] = $order_details_res;

    $this->load->view('members/view_order_details', $data);
  }

  public function remove_wishlist() {
    $wish_id = (int) $this->uri->segment(3);

    if ($wish_id > 0) {
      $record = count_record('wps_wishlists', "id ='" . $wish_id . "'");
      if ($record > 0) {
        $this->db->query("DELETE FROM wps_wishlists WHERE id = '" . $wish_id . "'");
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', "Product removed from wishlist.");
      } else {
        $this->session->set_userdata(array('msg_type' => 'warning'));
        $this->session->set_flashdata('warning', "Something went wrong, please try again!");
      }
    } else {
      $this->session->set_userdata(array('msg_type' => 'warning'));
      $this->session->set_flashdata('warning', "Wishlist product not found!");
    }
    redirect($_SERVER['HTTP_REFERER']);
  }
    
    public function cancel_order() {
   
//       $orderid = $_GET['orderId'];
        $orderid = $this->input->post('order_id');
//        $customerId = $_GET['customers_id'];
        $customerId = $this->userId;
        $reason =  $this->input->post('reason_for_cancelOrder');
      $cancelDate = $this->config->item('config.date.time');
        $getorderinfo = $this->db->query("select email,first_name,shiprocket_orderid,invoice_number,total_amount from wps_order where order_id = '$orderid'")->row_array(); 
        $userEmail = $getorderinfo['email'];
        $userName = $getorderinfo['first_name'];
        $bill = display_price($getorderinfo['total_amount']);
        $shiprocket_orderid =  $getorderinfo['shiprocket_orderid'];
        $invoice_number = $getorderinfo['invoice_number'];
    if ($orderid > 0) {
        
    $this->db->query("UPDATE wps_order SET order_status = '5', reason_for_cancelOrder = '$reason' , order_cancelled_date = '$cancelDate' WHERE order_id = '" . $orderid . "'");
 
    $Oid = $shiprocket_orderid;
    $response = $this->shiprocket->cancelOrder($Oid);
     trace($response);
    $memid = $customerId;
    $query = $this->db->query("SELECT * FROM wps_customers WHERE customers_id='" . $memid . "'");
    $row = $query->row_array();
    $trackinglink =rawurlencode('https://toyzoo.shiprocket.co/');
    $mobile = $row['mobile_number'];
    $site_url=rawurlencode(base_url());
    $tempid = "1207164707788985720";
    
$message="Cancellation%3A%20You%20have%20canceled%20your%20order%20%7B$invoice_number%7D.%20Your%20amount%20will%20be%20refunded%20within%203-5%20working%20days%20if%20it%27s%20not%20COD.%20Visit%20Toyzoo%20Store%20%7B$site_url%7D";
        
sendSms($mobile,$message,$tempid);

        $subject = "Cancel Request Received from Toyzoo";
          $content = get_content('wps_auto_respond_mails', '15');
          $body = $content->email_content;
          $body = str_replace('{mem_name}', 'Admin', $body);
          $body = str_replace('{orderId}', $orderid, $body);
          $body = str_replace('{name}', $userName, $body);
          $body = str_replace('{bill}', $bill, $body);
          $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
          $body = str_replace('{date}', $cancelDate, $body);
         
          $mail_conf = array(
              'subject' => $subject,
              'to_email' => $userEmail,
              'reply_to' => 'noreply@toyzoo.com',
              'reply_name' => 'Toyzoo',
              'from_email' => 'noreply@toyzoo.com',
              'from_name' => 'Toyzoo',
              'body_part' => $body
          );
           
       //Send the Mail To Client
          $this->dmailer->mail_notify($mail_conf);
          $cid = $memid;
         $subject1 = "Cancel Request Received from Toyzoo";
        $content = get_content('wps_auto_respond_mails', '16');
          $body = $content->email_content;
          $body = str_replace('{mem_name}', 'Admin', $body);
          $body = str_replace('{orderId}', $orderid, $body);
          $body = str_replace('{bill}', $bill, $body);
            $body = str_replace('{reason}', $reason, $body);
          $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
          $body = str_replace('{date}', $cancelDate, $body);
          $mail_conf1 = array(
              'subject' => $subject1,
              'to_email' => $this->admin_info->admin_email,
              'reply_to' => 'noreply@toyzoo.com',
              'reply_name' => 'Toyzoo',
              'from_email' => 'noreply@toyzoo.com',
              'from_name' => 'Toyzoo',
              'body_part' => $body
          );
           
       //Send the Mail To Admin
          $this->dmailer->mail_notify($mail_conf1);
        
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', "Your Order has been canceled successfully!");
        redirect($_SERVER['HTTP_REFERER']);
    } else {
      $this->session->set_userdata(array('msg_type' => 'error'));
      $this->session->set_flashdata('error', "Incorrect Order ID, Please try again!");
        redirect($_SERVER['HTTP_REFERER']);
    }
      redirect($_SERVER['HTTP_REFERER']);
  }

    
    public function return_order() {
    $orderid = $this->input->post('order_id');
    $getdetails = $this->db->query("select email, first_name from,total_amount wps_order where order_id = '$orderid'")->row_array(); 
    $userEmail = $getdetails['email'];
    $username = $getdetails['first_name'];
    $bill = display_price($getdetails['total_amount']);
    $this->form_validation->set_rules('reason_for_return', 'Reason For Return', 'trim|required');
    $returnDate = $this->config->item('config.date.time');
    $reasonText =$this->input->post('reason_for_return');
     if ($this->form_validation->run() == TRUE && $orderid > 0) {
         
    $this->db->query("UPDATE wps_order SET order_status = '6', reason_for_return = '$reasonText', order_returned_date = '$returnDate' WHERE order_id = '" . $orderid . "'");     
         
    $ordId = $orderid;
    $orderid = "TYZ000DEL0".$ordId;
    $memid = $userEmail;
    $query = $this->db->query("SELECT * FROM wps_customers WHERE user_name='" . $memid . "'");
    $row = $query->row_array();
    $trackinglink =rawurlencode('https://toyzoo.shiprocket.co/');
    $mobile = $row['mobile_number'];
    $site_url=rawurlencode(base_url());
    $tempid = "1207164707763329867";

$message = "Return%3A%20We%20have%20received%20your%20return%20request%20for%20the%20order%20%7B$orderid%7D.%20Once%20it%20is%20approved.%20We%20will%20start%20the%20return%20process.%20Visit%20Toyzoo%20Store%20%7B$site_url%7D";   
 
        sendSms($mobile,$message,$tempid);
     
        $subject = "Return Request Received from Toyzoo";
          $content = get_content('wps_auto_respond_mails', '14');
          $body = $content->email_content;
          $body = str_replace('{name}', $username, $body);
          $body = str_replace('{orderId}', $orderid, $body);
          $body = str_replace('{bill}', $bill, $body);
          $body = str_replace('{reason}', $this->input->post('reason_for_return'), $body);
          $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
          $body = str_replace('{date}', $returnDate, $body);
         
        $content1 = get_content('wps_auto_respond_mails', '17');
          $body1 = $content1->email_content;
          $body1 = str_replace('{orderId}', $orderid, $body1);
          $body1 = str_replace('{bill}', $bill, $body1);
          $body1 = str_replace('{reason}', $this->input->post('reason_for_return'), $body1);
          $body1 = str_replace('{site_name}', $this->config->item('site_name'), $body1);
          $body1 = str_replace('{date}', $returnDate, $body1);
         
          $mail_conf = array(
              'subject' => $subject,
              'to_email' => $userEmail,
              'reply_to' => 'noreply@toyzoo.com',
              'reply_name' => 'Toyzoo',
              'from_email' => 'noreply@toyzoo.com',
              'from_name' => 'Toyzoo',
              'body_part' => $body
          );
           
       //Send the Mail To User
          $this->dmailer->mail_notify($mail_conf);
          $mail_conf1 = array(
              'subject' => $subject,
              'to_email' => $this->admin_info->admin_email,
              'reply_to' => 'noreply@toyzoo.com',
              'reply_name' => 'Toyzoo',
              'from_email' => 'noreply@toyzoo.com',
              'from_name' => 'Toyzoo',
              'body_part' => $body1
          );
           
       //Send the Mail To admin
          $this->dmailer->mail_notify($mail_conf1);
          
            
       $res = 'success';    
        
    }
        else {
        $res = '<div class="alert alert-danger">
                        <strong>'.validation_errors().'
                    </div>';
      }
      echo $res;
        
      exit;    
        
      
  }
    public function updateProfile_account() {
       
  $adminRes = get_site_email();
   $data['adminRes'] = $adminRes;
      $this->form_validation->set_rules('mem_firstname', 'First Name', 'trim|required');
      $this->form_validation->set_rules('mem_email', 'Emial ID', 'trim|required');
      $this->form_validation->set_rules('mem_mobile', 'Mobile Number', 'trim|required|max_length[10]|min_length[10]|numeric');
      $this->form_validation->set_rules('mem_lastname', 'Last Name', 'trim');
      $this->form_validation->set_rules('mem_disname', 'Display Name', 'trim|required');
      $this->form_validation->set_rules('mem_id', 'You are Not registered User', 'trim|required');
     
      
        if ($this->form_validation->run() == TRUE) {  
        $posted_data = array (
          
          'first_name' => $this->input->post('mem_firstname'),
          'user_name' => $this->input->post('mem_email'),
          'mobile_number' => $this->input->post('mem_mobile'),
          'display_name' => $this->input->post('mem_disname'),
          'last_name' => $this->input->post('mem_lastname')
          
        );
            $where = "customers_id = '" . $this->input->post('mem_id') . "'";
        $this->members_model->safe_update('wps_customers', $posted_data, $where, FALSE);
        
    $res = 'success';     
      }else {
          $res = '<div class="alert alert-danger">
                          <strong>'.validation_errors().'
                      </div>';
      }
      echo $res;
      exit;
 
  }
    
    

  public function edit_account() {
    $data['unq_section'] = "Myaccount";
    $data['title'] = "Edit Account";
    $data['titleArray'] = $this->config->item('titleArray');
    $mres = $this->members_model->get_member_row($this->session->userdata('user_id'));
    //trace($mres);

    if (is_array($mres) && !empty($mres)) {
      $mres_address = $this->db->query("select * from wps_customers_address_book where  customer_id='" . $mres['customers_id'] . "' AND address_type = 'Ship' order by address_id desc limit 0, 1")->row_array();

      $mres_address_bil = $this->db->query("select * from wps_customers_address_book where  customer_id='" . $mres['customers_id'] . "' AND address_type = 'Bill' order by address_id desc limit 0, 1")->row_array();

      //trace($mres_address);
      if (is_array($mres_address) && !empty($mres_address)) {
        $mres1 = array(
            'mtitle' => '',
            'name' => $mres_address['first_name'],
            'mobile' => $mres_address['mobile'],
            'address' => $mres_address['address'],
            'landmark' => $mres_address['landmark'],
            'zipcode' => $mres_address['zipcode'],
            'country' => $mres_address['country'],
            'city' => $mres_address['city'],
            'state' => $mres_address['state'],
            'address_id' => $mres_address['address_id'],
            'bmtitle' => '',
            'bil_name' => $mres_address_bil['first_name'],
            'bil_mobile' => $mres_address_bil['mobile'],
            'bil_address' => $mres_address_bil['address'],
            'bil_landmark' => $mres_address_bil['landmark'],
            'bil_zipcode' => $mres_address_bil['zipcode'],
            'bil_country' => $mres_address_bil['country'],
            'bil_city' => $mres_address_bil['city'],
            'bil_state' => $mres_address_bil['state'],
            'bil_address_id' => $mres_address_bil['address_id'],
        );
      } else {
        $mres1 = array(
            'mtitle' => '',
            'name' => '',
            'mobile' => '',
            'address' => '',
            'landmark' => '',
            'zipcode' => '',
            'country' => '',
            'city' => '',
            'state' => '',
            'address_id' => '',
            'bmtitle' => '',
            'bil_name' => '',
            'bil_mobile' => '',
            'bil_address' => '',
            'bil_landmark' => '',
            'bil_zipcode' => '',
            'bil_country' => '',
            'bil_city' => '',
            'bil_state' => '',
            'bil_address_id' => @$mres_address_bil['address_id'],
            'last_shopping_comment' => ''
        );
      }
      $data['mres1'] = $mres1;

      //Shipping validation
      //$this->form_validation->set_rules('mtitle', 'Shipping Name Title', 'trim|required');
      $this->form_validation->set_rules('ship_name', 'Shipping Name', 'trim|required|alpha|max_length[160]');
      $this->form_validation->set_rules('ship_mobile', 'Ship Mobile No.', 'trim|required|max_length[20]|min_length[10]');
      $this->form_validation->set_rules('ship_address', 'Shipping Address', 'trim|required|max_length[200]');
      $this->form_validation->set_rules('ship_lmark', 'Shipping Landmark', 'trim|max_length[160]');
      $this->form_validation->set_rules('ship_city', 'Shipping City', 'trim|required|max_length[40]');
      $this->form_validation->set_rules('ship_pin', 'Pin Code', 'trim|required|max_length[20]');
      $this->form_validation->set_rules('ship_state', 'Shipping State', 'trim|required|max_length[40]');
      $this->form_validation->set_rules('ship_country', 'Shipping Country', 'trim|required|max_length[80]');

      //Billing validation
      //$this->form_validation->set_rules('bmtitle', 'Billing Name Title', 'trim|required');
      $this->form_validation->set_rules('bil_name', 'Billing Name', 'trim|required|alpha|max_length[160]');
      $this->form_validation->set_rules('bil_mobile', 'Billing Mobile No.', 'trim|required|max_length[20]|min_length[10]');
      $this->form_validation->set_rules('bil_address', 'Billing Address', 'trim|required|max_length[200]');
      $this->form_validation->set_rules('bil_lmark', 'Billing Landmark', 'trim|max_length[160]');
      $this->form_validation->set_rules('bil_city', 'Billing City', 'trim|required|max_length[40]');
      $this->form_validation->set_rules('bil_pin', 'Billing Pin Code', 'trim|required|max_length[20]');
      $this->form_validation->set_rules('bil_state', 'Billing State', 'trim|required|max_length[40]');
      $this->form_validation->set_rules('bil_country', 'Billing Country', 'trim|required|max_length[80]');

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

        $posted_user_data_ship = array(
            'mtitle' => '',
            'first_name' => $this->input->post('ship_name'),
            'mobile' => $this->input->post('ship_mobile'),
            'address' => $this->input->post('ship_address'),
            'landmark' => $this->input->post('ship_lmark'),
            'zipcode' => $this->input->post('ship_pin'),
            'country' => $this->input->post('ship_country'),
            'city' => $this->input->post('ship_city'),
            'state' => $this->input->post('ship_state'),
        );
        //trace($posted_user_data_ship);
        //exit;
        $where_ship = "address_id = '" . $mres1['address_id'] . "'";
        $this->members_model->safe_update('wps_customers_address_book', $posted_user_data_ship, $where_ship, FALSE);

        $posted_user_data = array(
            'mtitle' => '',
            'first_name' => $this->input->post('bil_name'),
            'mobile' => $this->input->post('bil_mobile'),
            'address' => $this->input->post('bil_address'),
            'landmark' => $this->input->post('bil_lmark'),
            'zipcode' => $this->input->post('bil_pin'),
            'country' => $this->input->post('bil_country'),
            'city' => $this->input->post('bil_city'),
            'state' => $this->input->post('bil_state'),
        );

        $where = "address_id = '" . $mres1['bil_address_id'] . "'";
        $this->members_model->safe_update('wps_customers_address_book', $posted_user_data, $where, FALSE);


        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Account has been updated successfully!!!');
        redirect('members/edit_account', 'refresh');
      }
    } else {
      redirect('members', '');
    }


    $data['mres'] = $mres;
    $this->load->view('view_member_edit_account', $data);
  }

  public function change_password() {
    $mres = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $data['mres'] = $mres;
    $this->form_validation->set_rules('old_password', 'Old Password', 'trim|required');
    $this->form_validation->set_rules('new_password', 'New Password', 'trim|required|valid_password');
    $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[new_password]');

    if ($this->form_validation->run() == TRUE) {
      $password_old = $this->input->post('old_password', TRUE);
      $mres = $this->members_model->get_member_row($this->userId, " AND password='$password_old' ");
      if (is_array($mres) && !empty($mres)) {
        $password = $this->input->post('new_password', TRUE);
        $data = array('password' => $password);
        $where = "customers_id=" . $this->session->userdata('user_id') . " ";
        $this->members_model->safe_update('wps_customers', $data, $where, FALSE);
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', ' Password has been changed successfully.');
      } else {
        $this->session->set_userdata(array('msg_type' => 'error'));
        $this->session->set_flashdata('error', ' Old Password is not valid.');
      }
      redirect('members/change_password', '');
    }
    /* End  member change password  */
    $data['unq_section'] = "Myaccount";
    $data['heading_title'] = "Account Settings";
    $this->load->view('members/view_member_change_password', $data);
  }
    
    public function reset_password() {
        
        $mres = $this->members_model->get_member_row($this->session->userdata('user_id'));
        $data['mres'] = $mres;
        $data['unq_section'] = "Myaccount";
        $data['heading_title'] = "Account Settings";
       $this->load->view('members/view_member_reset_password', $data); 
    
  }
    
    public function reset_otp()
    {
        $mobile = $this->input->post('mobile');
        $this->session->set_userdata('mobilenumber', $mobile); 
        $user = $this->users_model->check_mobile($mobile);
        if ($user) {
            $otp = substr(str_shuffle('1234567890'), 0, 6);
            $site_url = rawurlencode(base_url());
            $tempid = "1207164562251262511";
                    
                    // for reset password
             $message = "Dear%20user%2C%20OTP%20to%20RESET%20your%20password%20is%20%7B$otp%7D.%20Click%20on%20the%20link%20to%20visit%20Toyzoo%20store%20%7B$site_url%7D";
                    
                  
            if(sendSms($mobile,$message,$tempid))
            {
                $data = $this->users_model->saveotp($mobile, $otp);
                $this->session->set_userdata('mobnumber',$mobile); 
                 echo $res = 'success';   
            }
            else
            {
                echo $res = 'error1';
            }
            
//            $data = $this->users_model->saveotp($mobile, $otp);
            
        } else {
            
            echo $res = 'error2';
        }
      
    }
    
    public function verifyotp()
    {
        $mobile = $this->session->userdata('mobilenumber');
        $otp =  $this->input->post('otp');
        
        if ($this->users_model->verify($mobile, $otp)) {
            
            echo $res = "success";
        } else {
            echo $res = "error";
        }
    }

    
    public function resetpass()
    {
        $mres = $this->members_model->get_member_row($this->session->userdata('user_id'));
        if($this->input->post('action')=='reset')
        {
            $password = $this->input->post('password', TRUE);
            $data = array('password' => $password);
            $where = "customers_id=" . $this->session->userdata('user_id') . " ";
            $this->members_model->safe_update('wps_customers', $data, $where, FALSE);
            echo "success";
        }
          else {
        $this->session->set_userdata(array('msg_type' => 'error'));
        $this->session->set_flashdata('error', ' Old Password is not valid.');
              echo "error";
          }
    }
    

  public function mywishlist() {
    $data['mres'] = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $data['wishlist'] = $this->members_model->get_wislists(NULL, NULL, array());
    //echo_sql();
    $data['total_records'] = get_found_rows();
    $this->load->view('members/view_member_wishlist', $data);
  }

  public function remove_wislist() {
    $wishlists_id = $ordId = $this->uri->segment(3);
    if ($wishlists_id != '') {

      $where = array('id' => $wishlists_id, 'customer_id' => $this->userId);
      $this->members_model->safe_delete('wps_wishlists', $where, FALSE);

      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', $this->config->item('wish_list_delete'));
      redirect('members/mywishlist', '');
    }
  }  

  public function orders_history() {
    $data['unq_section'] = "Myaccount";
    $mres = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $data['mres'] = $mres;

    //get orders
    $record_per_page = (int) $this->input->post('per_page');
    $config['per_page'] =$this->config->item('per_page');
    $page_segment = find_paging_segment();
    $offset = (int) $this->uri->segment($page_segment, 0);
    //conditions
    $condtion = "AND customers_id = '$this->userId'  and (payment_status='Paid' Or payment_method='Cash' Or payment_method='COD') ";
    if ($this->input->post('order_id') != '') {
      $condtion .= "AND invoice_number = '" . $this->input->post('order_id') . "' ";
    }
    if ($this->input->post('start_date') != '') {
      $condtion .= "AND order_received_date >= '" . $this->input->post('start_date') . "' ";
    }
    if ($this->input->post('end_date') != '') {
      $condtion .= "AND order_received_date <= '" . $this->input->post('end_date') . "' ";
    }
    if ((int) $this->uri->segment(3, 0) == TRUE) {
      $condtion .= "AND order_id = '" . $this->uri->segment(3) . "' ";
    }

    $base_url = "members/orders_history/index/pg/";
    $res_array = $this->order_model->get_orders($offset, $config['per_page'], $condtion);
    $config['total_rows'] = $data['total_list_rows'] = $this->order_model->total_rec_found;
    $data['orders'] = $res_array;
    $this->load->view('view_member_orders', $data);
  }

  public function ajax_load_orders() {
    //get orders
    $config['per_page'] = $this->config->item('per_page');
    $offset = $this->input->get_post('stOffSet');
    $condtion = "AND customers_id = '$this->userId' ";
    if ($this->input->post('order_id') != '') {
      $condtion .= "AND invoice_number = '" . $this->input->post('order_id') . "' ";
    }
    if ($this->input->post('start_date') != '') {
      $condtion .= "AND order_received_date >= '" . $this->input->post('start_date') . "' ";
    }
    if ($this->input->post('end_date') != '') {
      $condtion .= "AND order_received_date <= '" . $this->input->post('end_date') . "' ";
    }
    if ((int) $this->uri->segment(3, 0) == TRUE) {
      $condtion .= "AND order_id = '" . $this->uri->segment(3) . "' ";
    }
    $res_array = $this->order_model->get_orders($offset, $config['per_page'], $condtion);
    $config['total_rows'] = $data['total_list_rows'] = $this->order_model->total_rec_found;
    $data['orders'] = $res_array;
    $this->load->view('view_member_orders_ajax', $data);
  }

  public function manage_addresses() {
    $customer_id = $this->session->userdata('user_id');

    $record_per_page = (int) $this->input->post('per_page');
    $parent_segment = (int) $this->uri->segment(3);
    $page_segment = find_paging_segment();

    $config['per_page'] = ( $record_per_page > 0 ) ? $record_per_page : $this->config->item('per_page');
    $offset = (int) $this->uri->segment($page_segment, 0);

    $parent_id = ( $parent_segment > 0 ) ? $parent_segment : '0';
    $base_url = ( $parent_segment > 0 ) ? "members/manage_addresses/$parent_id/pg/" : "members/manage_addresses/pg/";


    $address_res = $this->members_model->get_member_address_book($customer_id, $offset, $config['per_page']);
    $config['total_rows'] = $this->members_model->total_rec_found;
    $data['page_links'] = front_pagination("$base_url", $config['total_rows'], $config['per_page'], $page_segment);

    $data['address_res'] = $address_res;
    $data['heading'] = "Manage Addresses";
    $this->load->view('view_member_addresses', $data);
  }

  public function manage_addresses_add() {

    $this->form_validation->set_rules('name', 'Name', 'trim|required|alpha|max_length[80]');
    $this->form_validation->set_rules('mobile', 'Mobile No.', 'trim|required|max_length[20]');
    $this->form_validation->set_rules('phone', 'Phone No.', 'trim|max_length[20]');
    $this->form_validation->set_rules('zipcode', 'Pin Code', 'trim|required|max_length[20]');
    $this->form_validation->set_rules('address', 'Address', 'trim|required|max_length[200]');
    $this->form_validation->set_rules('landmark', 'Landmark', 'trim|required|max_length[200]');
    $this->form_validation->set_rules('city', 'City', 'trim|required|max_length[40]');
    $this->form_validation->set_rules('state', 'State', 'trim|required|max_length[40]');
    $this->form_validation->set_rules('country', 'Country', 'trim|required|max_length[80]');

    if ($this->form_validation->run() == TRUE) {
      $data = array(
          'customer_id' => $this->session->userdata('user_id'),
          'name' => $this->input->post('name'),
          'mobile' => $this->input->post('mobile'),
          'phone' => $this->input->post('phone'),
          'zipcode' => $this->input->post('zipcode'),
          'address' => $this->input->post('address'),
          'landmark' => $this->input->post('landmark'),
          'city' => $this->input->post('city'),
          'state' => $this->input->post('state'),
          'country' => $this->input->post('country'),
          'default_status' => 'Y'
      );
      //trace($data);
      //exit;
      $this->members_model->safe_insert('wps_customers_address_book', $data, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', 'New Address has been added successfully!!!');
      redirect('members/manage_addresses_add', '');
    }

    /* End  member change password  */

    $data['unq_section'] = "Myaccount";
    $data['heading_title'] = "Account Settings";
    $this->load->view('members/view_address_add', $data);
  }

  public function manage_addresses_edit() {

    //$addressid     = (int) $this->uri->segment(3);
    //$res=$this->db->query("select * from wps_customers_address_book where address_id='".$addressid."'")->row_array();

    $this->form_validation->set_rules('add_name', 'Name', 'trim|required|alpha|max_length[80]');
    $this->form_validation->set_rules('add_mobile', 'Mobile No.', 'trim|required|max_length[20]');

    $this->form_validation->set_rules('add_zipcode', 'Pin Code', 'trim|required|max_length[20]');
    $this->form_validation->set_rules('add_address', 'Address', 'trim|required|max_length[200]');
    $this->form_validation->set_rules('add_landmark', 'Landmark', 'trim|required|max_length[200]');
    $this->form_validation->set_rules('add_city', 'City', 'trim|required|max_length[40]');
    $this->form_validation->set_rules('add_state', 'State', 'trim|required|max_length[40]');
    $this->form_validation->set_rules('add_country', 'Country', 'trim|required|max_length[80]');

    if ($this->form_validation->run() == TRUE) {
      $data = array(
          'name' => $this->input->post('add_name'),
          'mobile' => $this->input->post('add_mobile'),
          'phone' => $this->input->post('add_mobile'),
          'zipcode' => $this->input->post('add_zipcode'),
          'address' => $this->input->post('add_address'),
          'landmark' => $this->input->post('add_landmark'),
          'city' => $this->input->post('add_city'),
          'state' => $this->input->post('add_state'),
          'country' => $this->input->post('add_country'),
      );
      //trace($data);
      //exit;
      $where = array('customer_id' => $this->session->userdata('user_id'));
      $this->members_model->safe_update('wps_customers_address_book', $data, $where, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      echo 2;
      //$this->session->set_flashdata('success', 'New Address has been updated successfully!!!');
      //redirect('members/manage_addresses_edit/' . $addressid, '');
    } else {
      echo validation_errors();
      die;
    }

    /* End  member change password  */
    /* $data['res'] = $res;
      //trace($res);
      $data['unq_section'] = "Myaccount";
      $data['heading_title'] = "Account Settings";
      $this->load->view('members/view_address_edit',$data); */
  }

  public function delete_address() {
    $addressid = (int) $this->uri->segment(3);
    $this->db->query("delete from wps_customers_address_book where address_id = '" . $addressid . "'");
    $this->session->set_userdata(array('msg_type' => 'success'));
    $this->session->set_flashdata('success', 'Address has been Deleted successfully!!!');
    redirect($_SERVER['HTTP_REFERER']);
  }

  public function post_review_old() {
    $productId = (int) $this->uri->segment(3);
    $data['proRes'] = get_db_single_row("wps_products", "*", "products_id = '" . $productId . "'");
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");
    $data['mres'] = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $this->form_validation->set_rules('ads_rating', 'Rating', 'trim|required|max_length[1]');
    $this->form_validation->set_rules('comment', 'Review', 'trim|required|max_length[450]');
    if ($this->form_validation->run() === TRUE) {
      $mem_id = $this->session->userdata('user_id');
      $posted_data = array(
        'product_id' => $this->input->post('products_id'),
        'entity_type' => 'product',
        'customer_id' => $this->session->userdata('user_id'),
        'ads_rating' => $this->input->post('ads_rating'),
        'author' => $this->session->userdata('fullname'),
        'author_email' => $this->session->userdata('username'),
        'text' => $this->input->post('comment'),
        'status' => '0',
        'review_date' => $this->config->item('config.date.time')
      );
      $this->product_model->safe_insert('wps_review', $posted_data, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', 'Thank you. Your review has been submitted successfully');
      redirect('members/post_review/' . $data['proRes']['products_id'], '');
    }
    $this->load->view('view_member_my_reviews', $data);
  }
    
  public function post_review() {
    $productId = (int) $this->uri->segment(3);

    $this->db->select('*');
    $this->db->from('wps_order');
    $this->db->where('customers_id',$this->session->userdata('user_id'));
    $this->db->where('products_id',$productId);
    $this->db->where('order_status',"8");
    $this->db->join('wps_orders_products', 'wps_orders_products.order_id = wps_order.order_id', 'left');
    $query = $this->db->get();
    $productcount = $query->num_rows();
    $product = $query->row();
//    print_r($product); exit();
    $data['proRes'] = get_db_single_row("wps_products", "*", "products_id = '" . $product->products_id . "'");
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");
    $data['mres'] = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $this->form_validation->set_rules('ads_rating', 'Rating', 'trim|required|max_length[1]');
    $this->form_validation->set_rules('comment', 'Review', 'trim|required|max_length[450]');
    if ($this->form_validation->run() === TRUE) {
      $mem_id = $this->session->userdata('user_id');
      //image section start
      $pic1 = '';
      if (!empty($_FILES) && $_FILES['img1']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/revies/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('img1');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $pic1 = $uploaded_data['upload_data']['file_name'];
        }
      }

      // print_r($_POST['ads_rating']);
      // exit;
      //image section end
      $posted_data = array(
        'entity_id' => $this->input->post('products_id'),
        'entity_type' => 'product',
        'customer_id' => $this->session->userdata('user_id'),
        'ads_rating' => $this->input->post('ads_rating'),
        'author' => $this->session->userdata('fullname'),
        'author_email' => $this->session->userdata('username'),
        'text' => $this->input->post('comment'),
        'upload_image' => $pic1,
        'status' => '0',
        'review_date' => $this->config->item('config.date.time')
      );
      $this->product_model->safe_insert('wps_review', $posted_data, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', 'Thank you. Your review has been submitted successfullys');
        
      redirect('members/post_review/' . $data['proRes']['products_id'], '');
    }
      if($productcount==0)
      {
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('reviewstatus', 'You are not authorized to Review & rating the Product. Untill buy the Particular product');
        redirect($_SERVER['HTTP_REFERER']);  
      }
      else
      {
       
           $query = $this->db->query("SELECT * FROM  wps_review WHERE customer_id='" . $this->session->userdata('user_id') . "' and entity_id='".$productId."'");
          if($this->session->userdata('user_id') && ($query->num_rows()>0) ){
               $data['reviews'] = $this->db->query("SELECT * FROM  wps_review WHERE customer_id='" . $this->session->userdata('user_id') . "'")->result_array();
                $this->load->view('view_review', $data);
          }
          else{
              $this->load->view('view_member_my_reviews', $data); 
          }
      }
    
  }
  
 public function reviews_old() {
    $data['mres'] = $this->members_model->get_member_row($this->session->userdata('user_id'));

    $data['reviews'] = $this->db->query("SELECT * FROM  wps_review WHERE customer_id='" . $this->session->userdata('user_id') . "'")->result_array();
    $this->load->view('view_review', $data);
  }
  
  public function reviews() {
    $data['mres'] = $this->members_model->get_member_row($this->session->userdata('user_id'));

    $data['reviews'] = $this->db->query("SELECT * FROM  wps_review WHERE customer_id='" . $this->session->userdata('user_id') . "'")->result_array();
    //echo "<pre>";print_r($data);
    $this->load->view('view_review', $data);
  }

 public function edit_review_old() {
    $reviewId = (int) $this->uri->segment(3);
    $data['proRes'] = $this->db->query("SELECT * FROM  wps_review WHERE review_id='" . $reviewId . "'")->result_array();
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");
    $data['mres'] = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $this->form_validation->set_rules('ads_rating', 'Rating', 'trim|required|max_length[1]');
    $this->form_validation->set_rules('comment', 'Review', 'trim|required|max_length[450]');
    if ($this->form_validation->run() === TRUE) {
      $mem_id = $this->session->userdata('user_id');
      $update_data = array(
        'product_id' => $this->input->post('products_id'),
        'entity_type' => 'product',
        'customer_id' => $this->session->userdata('user_id'),
        'ads_rating' => $this->input->post('ads_rating'),
        'author' => $this->session->userdata('fullname'),
        'author_email' => $this->session->userdata('username'),
        'text' => $this->input->post('comment'),
        'status' => '0',
        'review_date' => $this->config->item('config.date.time')
      );
      $where = "review_id=" . $reviewId . " ";
      $this->members_model->safe_update('wps_review', $update_data, $where, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', 'Thank you. Your review has been updated successfully');
      redirect('members/edit_review/' . $reviewId, '');
    }
    $this->load->view('edit_myreview', $data);
  }
  
  public function edit_review() {
    $reviewId = (int) $this->uri->segment(3);
    $data['proRes'] = $this->db->query("SELECT * FROM  wps_review WHERE review_id='" . $reviewId . "'")->result_array();
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");
    $data['mres'] = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $this->form_validation->set_rules('ads_rating', 'Rating', 'trim|required|max_length[1]');
    $this->form_validation->set_rules('comment', 'Review', 'trim|required|max_length[450]');
    if ($this->form_validation->run() === TRUE) {
      $mem_id = $this->session->userdata('user_id');
      $update_data = array(
        'entity_id' => $this->input->post('products_id'),
        'entity_type' => 'product',
        'customer_id' => $this->session->userdata('user_id'),
        'ads_rating' => $this->input->post('ads_rating'),
        'author' => $this->session->userdata('fullname'),
        'author_email' => $this->session->userdata('username'),
        'text' => $this->input->post('comment'),
        'status' => '0',
        'review_date' => $this->config->item('config.date.time')
      );
      $where = "review_id=" . $reviewId . " ";
      $this->members_model->safe_update('wps_review', $update_data, $where, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', 'Thank you. Your review has been updated successfully');
      redirect('members/edit_review/' . $reviewId, '');
    }
    $this->load->view('edit_myreview', $data);
  }
  
  public function remove_review_old() {
    $reviews_id = $ordId = $this->uri->segment(3);
    if ($reviews_id != '') {
      $where = array('review_id' => $reviews_id, 'customer_id' => $this->userId);
      $this->members_model->safe_delete('wps_review', $where, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', $this->config->item('wish_list_delete'));
      redirect('members/reviews', '');
    }
  }
   public function remove_review() {
    $reviews_id = $ordId = $this->uri->segment(3);
    if ($reviews_id != '') {
      $where = array('review_id' => $reviews_id, 'customer_id' => $this->userId);
      $this->members_model->safe_delete('wps_review', $where, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', $this->config->item('wish_list_delete'));
      redirect('members/reviews', '');
    }
  }
  
  public function feedback() {
    $data['mres'] = $this->members_model->get_member_row($this->session->userdata('user_id'));
    $testimonials = $this->db->query("SELECT * FROM  wps_testimonial WHERE user_id='" . $this->session->userdata('user_id') . "'")->row_array();
   
    $this->form_validation->set_rules('feedback', 'Feedback', 'trim|required');
   
    if ($this->form_validation->run() == TRUE) {
        if(count($testimonials)>0){
            $data = array('testimonial_description' => $this->input->post('feedback'), );
            $where = "user_id=" . $this->session->userdata('user_id') . " ";
            $this->members_model->safe_update('wps_testimonial', $data, $where, FALSE);
            $this->session->set_userdata(array('msg_type' => 'success'));
            $this->session->set_flashdata('success', 'Feedback Updated successfully.');
        }else{
            $data = array('testimonial_description' => $this->input->post('feedback'), 'user_id' => $this->session->userdata('user_id'));
            $this->members_model->safe_insert('wps_testimonial', $data);
            $this->session->set_userdata(array('msg_type' => 'success'));
            $this->session->set_flashdata('success', 'Feedback Added successfully.');
        }
       
        redirect('members/feedback', '');
    }
   
    $data['feedback'] = $testimonials;
    $this->load->view('view_member_my_feedback', $data);
  }
  
  public function notify() {
    //  $this->load->model(array('order/order_model'));
    $wishId = (int) $this->uri->segment(3);
    $data['wishId'] = $wishId;

    $param = array('condition' => "&& wishlists_id='" . $wishId . "'");

    $res = $this->members_model->get_wislists(0, 1, $param);

    $this->form_validation->set_rules('message', 'Message', 'trim|max_length[250]');
    if ($this->form_validation->run() == TRUE) {
      $data = array(
          'message' => $this->input->post('message', FALSE),
          'notify' => '1'
      );

      $where = array(
          'wishlists_id' => $wishId
      );

      $this->members_model->safe_update('wps_wishlists', $data, $where, TRUE);
      //		$this->session->set_userdata('msg_type',$res['error_type']);
      $this->session->set_flashdata('success', 'Your Notification has been set sucessfully.');
      redirect('members/notify/' . $wishId, '');
    }

    $data['wish'] = $res[0];
    $this->load->view('view_product_notify', $data);
  }
  
  public function track_order() {
    $data['unq_section'] = "Track Order";

    $this->form_validation->set_rules('order_id', 'Order No', 'trim|required');

    if ($this->form_validation->run() == TRUE) {
      redirect('members/orders_history/' . $this->input->post('order_id'));
    }
    $this->load->view('view_track_order', $data);
  }

}

/* End of file member.php */
/* Location: .application/modules/member/member.php */