<?php

class Cart extends Public_Controller {

  public function __construct() {

    parent::__construct();
    $this->load->helper(array('cart', 'products/product'));
    $this->load->model(array('products/product_model', 'members/members_model', 'cart_model', 'order/order_model', 'pages/pages_model'));
    $this->load->library(array('safe_encrypt', 'Auth', 'Dmailer'));
    $this->form_validation->set_error_delimiters("<div class='required fs12'>", "</div>");
  }

  public function index() {
    // trace($this->cart->total_items()); die;
    $order_cart_id = $this->session->userdata('working_order_id');
    if ($order_cart_id != '') {
      $this->session->unset_userdata('working_order_id');
    }
    if ($this->input->post('EmptyCart') != "") {
      $this->empty_cart();
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', $this->config->item('cart_empty'));
      redirect('cart');
    }
    //cart Items
   // trace($this->cart->contents());
    $tax_cent = $this->cart_model->get_vat();
    $data['tax_cent'] = $tax_cent;
    $data['title'] = "Shopping Cart";
    //echo "<pre>";print_r($data);die;
    $this->load->view('view_my_cart', $data);
  }

 
 

  public function checkout() {
    //trace($this->cart->total_items()); die;
    if (!$this->cart->total_items() > 0) {
      redirect('home');
    }
    if (!$this->auth->is_user_logged_in()) {
      $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[80]');

      if ($this->form_validation->run() == TRUE) {
        $username = $this->input->post('email');
        if ($this->input->post('checkout_type') == 'User') {
          $this->form_validation->set_rules('password', 'Password', 'trim|required');
          if ($this->form_validation->run() == TRUE) {
          $password = $this->input->post('password');

          $this->auth->verify_user($username, $password);
          if ($this->auth->is_user_logged_in()) {
            redirect('cart/delivery_info', '');
          } else {
            $this->session->set_userdata(array('msg_type' => 'error'));
            $this->session->set_flashdata('error', $this->config->item('login_failed'));
            $data['title'] = "Checkout Info";
            $this->load->view('view_cart_checkout', $data);
          }
        }else{
          $data['title'] = "Checkout Info";
          $this->load->view('view_cart_checkout', $data);
        }
        } elseif ($this->input->post('checkout_type') == 'Register') {
          $this->form_validation->set_rules('name', 'Name', 'trim|required|alpha|max_length[32]');
          $this->form_validation->set_rules('mobile_number', 'Mobile No', 'trim|required|numeric|max_length[10]');
          $this->form_validation->set_rules('password_register', 'Password', 'trim|required|max_length[20]|valid_password');
          if ($this->form_validation->run() == TRUE) {

            $registerId = $this->create_user();
            $name = $this->input->post('name', TRUE);
            $username = $this->input->post('email', TRUE);
            $password = $this->input->post('password_register', TRUE);
            if ($registerId != '') {
              /* Send  mail to user */
              $content = get_content('wps_auto_respond_mails', '1');
              $subject = str_replace('{site_name}', $this->config->item('site_name'), $content->email_subject);
              $body = $content->email_content;
              $verify_url = "<a href=" . base_url() . "users/verify/" . $registerId . ">Verify Your Email Address </a>";
              $name = " User ";
              $body = str_replace('{mem_name}', $name, $body);
              $body = str_replace('{username}', $username, $body);
              $body = str_replace('{password}', $password, $body);
              $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
              $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
              $body = str_replace('{url}', base_url(), $body);
              $body = str_replace('{link}', $verify_url, $body);

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

              }
              /* End send  mail to admin */
            }
            $this->auth->verify_user($username, $password);
            if ($this->auth->is_user_logged_in()) {
              redirect('cart/delivery_info', '');
            } else {
              $this->session->set_userdata(array('msg_type' => 'error'));
              $this->session->set_flashdata('error', $this->config->item('login_failed'));
              redirect('cart/checkout', '');
            }
          } else {
            $data['title'] = "Checkout Info";
            $this->load->view('view_cart_checkout', $data);
          }
        } else {
          $this->session->set_userdata('username', $username);
          redirect('cart/delivery_info', '');
        }
      } else {
        $data['title'] = "Checkout Info";
        $this->load->view('view_cart_checkout', $data);
      }
    } else {
      redirect('cart/delivery_info', '');
    }
  }

  public function create_user() {
    // $password = $this->safe_encrypt->encode($this->input->post('password_register', TRUE));
    $password = $this->input->post('password_register', TRUE);
    $name = ($this->input->post('name', TRUE) != '') ? $this->input->post('name', TRUE) : $this->input->post('bil_name', TRUE);
    $mobile = ($this->input->post('mobile_number', TRUE) != '') ? $this->input->post('mobile_number', TRUE) : $this->input->post('bil_mobile', TRUE);
    $register_array = array(
        'user_name' => $this->input->post('email', TRUE),
        'password' => $password,
        'first_name' => $name,
        'mobile_number' => $mobile,
        'actkey' => md5($this->input->post('email', TRUE)),
        'account_created_date' => $this->config->item('config.date.time'),
        'current_login' => $this->config->item('config.date.time'),
        'status' => '1',
        'is_verified' => '1',
        'ip_address' => $this->input->ip_address()
    );
    $insId = $this->cart_model->safe_insert('wps_customers', $register_array, FALSE);
    if ($insId > 0) {
      $add_array = array(
          'customer_id' => $insId,
          'reciv_date' => $this->config->item('config.date.time'),
          'address_type' => 'Bill',
          'default_status' => 'Y'
      );
      $this->cart_model->safe_insert('wps_customers_address_book', $add_array, FALSE);
    }
    return $insId;
  }

  public function view_order_review() {
    if (!$this->cart->total_items() > 0) {
      redirect('home');
    }
    $data['title'] = 'Receiver Details';
    //Delivery Message Details validation
    //$this->form_validation->set_rules('delivery_datetime', 'Date', 'trim|required');
    if ($this->form_validation->run() === FALSE) {
      $this->load->view('cart/view_order_review', $data);
    } else {
      redirect('cart/view_make_payment');
    }
  }

  public function delivery_info() {
    if (!$this->cart->total_items() > 0) {
      redirect('home');
    }
    // trace($this->input->post());
    $data['title'] = 'Delivery Information';
    //trace($this->session->userdata);
    $is_same_bill_ship = $this->input->post('is_same', TRUE);
    $mres = $this->members_model->get_member_row($this->session->userdata('user_id'));
    if (is_array($mres) && !empty($mres)) {
      $email = $mres['user_name'];
    } else {
      $email = $this->session->userdata['username'];
    }

    //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|min_length[10]|max_length[20]|numeric');
    $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[6]|numeric');
   $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|min_length[10]|max_length[20]|numeric');
    $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[6]|numeric');
    $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]');


    $name = $this->input->post('name') . ' ' . $this->input->post('lname');
    
    $posted_data = array(
        'customer_id' => $this->session->userdata('user_id'),
        'mtitle' => $this->input->post('mtitle'),
        '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'),
        'bmtitle' => $this->input->post('bmtitle'),
        'bil_name' => $this->input->post('bil_name'),
        'bil_mobile' => $this->input->post('bil_mobile'),
        'bil_address' => $this->input->post('bil_address'),
        'bil_landmark' => $this->input->post('bil_lmark'),
        'bil_zipcode' => $this->input->post('bil_pin'),
        'bil_country' => $this->input->post('bil_country'),
        'bil_city' => $this->input->post('bil_city'),
        'bil_state' => $this->input->post('bil_state'),
        'last_shopping_comment' => $this->input->post('last_shopping_comment')
    );
     

    if (is_array($mres) && !empty($mres)) {
      if ($this->form_validation->run() === FALSE) {
        $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)) {
          $mres = array(
              'mtitle' => $mres_address['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' => $mres_address_bil['mtitle'],
              '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'],
              'last_shopping_comment' => $this->input->post('last_shopping_comment')
          );
        } else {
          $mres = 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' => '',
              'last_shopping_comment' => ''
          );
        }
        $data['mres'] = $mres;
        $this->load->view('view_cart_delivery', $data);
      } else {

            $this->session->set_userdata('selected_city', $this->input->post('ship_city'));
          
        
        //Count Ship Address
        $shipAddRessCount = count_record('wps_customers_address_book', "customer_id = '" . $mres['customers_id'] . "' AND mobile = '" . $this->db->escape_str($this->input->post('ship_mobile')) . "' AND address = '" . $this->db->escape_str($this->input->post('ship_address')) . "' AND city = '" . $this->db->escape_str($this->input->post('ship_city')) . "' AND address_type = 'Ship'");
        if ($shipAddRessCount == 0) {
          $name = $this->input->post('name') . ' ' . $this->input->post('lname');
          if($this->input->post('ship_city')=='Other'){ 
            $ship_cities = $this->input->post('otherShipCity');
          }else{ 
            $ship_cities = $this->input->post('ship_city');
          }
          $addressData = array(
              'customer_id' => $mres['customers_id'],
              'mtitle' => $this->input->post('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' => $ship_cities,
              'state' => $this->input->post('ship_state'),
              'address_type' => 'Ship'
          );
          $addressIDs = $this->cart_model->safe_insert('wps_customers_address_book', $addressData);
        }

        //Count Bill Address
        $shipAddRessCount = count_record('wps_customers_address_book', "customer_id = '" . $mres['customers_id'] . "' AND mobile = '" . $this->db->escape_str($this->input->post('bil_mobile')) . "' AND address = '" . $this->db->escape_str($this->input->post('bil_address')) . "' AND city = '" . $this->db->escape_str($this->input->post('bil_city')) . "' AND address_type = 'Bill'");
        if ($shipAddRessCount == 0) {
          $name = $this->input->post('name') . ' ' . $this->input->post('lname');
          if($this->input->post('ship_city')=='Other'){ 
            $bil_cities = $this->input->post('otherShipCity');
          }else{ 
            $bil_cities = $this->input->post('bil_city');
          }
          $addressDataBill = array(
              'customer_id' => $mres['customers_id'],
              'mtitle' => $this->input->post('bmtitle'),
              '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' => $bil_cities,
              'state' => $this->input->post('bil_state'),
              'address_type' => 'Bill'
          );
          $addressIDs = $this->cart_model->safe_insert('wps_customers_address_book', $addressDataBill);
        }

        /* if ($this->input->post('default_address') != '') {
          $this->db->query("update wps_customers_address_book SET default_address = 'N' where customer_id = '" . $mres['customers_id'] . "'");
          $this->db->query("update wps_customers_address_book SET default_address = 'Y' where address_id = '" . $this->input->post('default_address') . "'");
          } */

        $shipcharge = 0;
        $cart_total = $this->cart->total();
        //$rate_dhl = $this->DHLShipPrice($totweight);

        $this->session->set_userdata('posted_data', $posted_data);
        $this->session->set_userdata('is_same_bill_ship', $is_same_bill_ship);
        redirect('cart/view_order_review');
        //   $this->add_customer_order($posted_data,$is_same_bill_ship);
      }
    } else {
      if ($this->form_validation->run() == FALSE) {
        $data['mres'] = $posted_data;
        $this->load->view('view_cart_delivery', $data);
      } else {
        $shipcharge = 0;
        $cart_total = $this->cart->total();
        $this->session->set_userdata('posted_data', $posted_data);
        $this->session->set_userdata('is_same_bill_ship', $is_same_bill_ship);
        redirect('cart/view_order_review');
        // $this->add_customer_order($posted_data,$is_same_bill_ship);           
      }
    }
  }

  public function make_payment() {
    if (!$this->cart->total_items() > 0) {
      redirect('home');
    }
    $posted_data = $this->session->userdata('posted_data');
    $data['posted_data'] = $posted_data;
    $data['mtitle'] = $this->config->item('titleArray');
    if (is_array($posted_data) && !empty($posted_data) && $this->cart->total_items() > 0 && $this->input->get_post('pay') != '') {
      $posted_data['cod_amount'] = 0.00;
      $costumer_data['shipping_amount'] = 0.00;
      // if ($this->input->get_post('pay') == 'COD') {
      //   $posted_data['cod_amount'] = '0.00';
      // }
      // if ($posted_data['country'] != 'India') {
      //   $posted_data['shipping_amount'] = '0.00';
      // }
      $posted_data['payment_mode'] = $this->input->get_post('pay');

      $this->add_customer_order($posted_data, $this->session->userdata('is_same_bill_ship'));

      $this->session->unset_userdata('posted_data');
      $this->session->unset_userdata('email');
      $this->session->unset_userdata('is_same_bill_ship');


      $orderID = $this->session->userdata('working_order_id');

      //Mailer to Admin for Order Initiated
      $ordmaster = $this->order_model->get_order_master($orderID);
      $orddetail = $this->order_model->get_order_detail($orderID);
      $bodyAdmin = invoice_content_print($ordmaster, $orddetail, $type='admin');
      $mailContentHtmlAdminC = ob_get_contents();
      $mail_conf_admin_c = array(
          'subject' => 'Order #' . $ordmaster['invoice_number'] . ' Initiated - rajshree-packaging',
          'to_email' => 'webpulseindia@gmail.com', //
          'from_email' => $ordmaster['email'],
          'from_name' => $this->config->item('site_name'),
          'body_part' => $mailContentHtmlAdminC
      );
      //trace($mail_conf_admin_c); die;
      //$this->dmailer->mail_notify($mail_conf_admin_c);
      ob_clean();
      //Mailer End Here


      $payMode = $this->input->get_post('pay');
      if ($payMode == "Payu") {
        $working_order_id = $this->session->userdata('working_order_id');
        $order_res = $this->order_model->get_order_master($working_order_id);
        $this->load->view('view_payu_form');
        //payuForm($order_res);
      } else {
        redirect('payment?pay_method=' . $this->input->get_post('pay'));
      }
    }

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

  private function add_customer_order($costumer_data = array(), $is_same_bill_ship) {
    if ($this->cart->total_items() > 0) {
      $userId = $this->session->userdata('user_id');
      $invoice_number = "rajshree-packaging_" . get_auto_increment('wps_order');
      $coupon_id = $this->session->userdata('coupon_id');
      $discount_amount = $this->session->userdata('discount_amount');
      $currency_code = $this->session->userdata('currency_code');
      $currency_value = $this->session->userdata('currency_value');
      $customers_id = ( $userId != '') ? $userId : 0;
      $cart_total = $this->cart->total();

      $ship_method = 'none';
      
      $deliveryCharge = delivery_charge(0,$cart_total);
      $gst = gst($cart_total);
      $ship_amount = $deliveryCharge; //$costumer_data['shipping_amount'];

      $cart_total = ($ship_amount + $cart_total) - $discount_amount;

      $data_order = array(
          'customers_id' => $customers_id,
          'invoice_number' => $invoice_number,
          'first_name' => $costumer_data['name'],
          'last_name' => '',
          'email' => $this->session->userdata('username'),
          'billing_title' => $costumer_data['bmtitle'],
          'billing_name' => $costumer_data['bil_name'],
          'billing_phone' => $costumer_data['bil_mobile'],
          'billing_address' => $costumer_data['bil_address'],
          'billing_landmark' => $costumer_data['bil_landmark'],
          'billing_zipcode' => $costumer_data['bil_zipcode'],
          'billing_country' => $costumer_data['bil_country'],
          'billing_city' => $costumer_data['bil_city'],
          'billing_state' => $costumer_data['bil_state'],
          'shipping_title' => $costumer_data['mtitle'],
          'shipping_name' => $costumer_data['name'],
          'shipping_phone' => $costumer_data['mobile'],
          'shipping_address' => $costumer_data['address'],
          'shipping_landmark' => $costumer_data['landmark'],
          'shipping_zipcode' => $costumer_data['zipcode'],
          'shipping_country' => $costumer_data['country'],
          'shipping_state' => $costumer_data['state'],
          'shipping_city' => $costumer_data['city'],
          'last_shopping_comment' => $costumer_data['last_shopping_comment'],
          'shipping_method' => $ship_method,
          'discount_coupon_id' => $coupon_id,
          'coupon_discount_amount' => $discount_amount,
          'shipping_amount' => $ship_amount,
          'cod_amount' => $costumer_data['cod_amount'],
          'total_amount' => $cart_total,
          'vat_amount' => $gst,
          'vat_applied_cent' => '',
          'currency_code' => $currency_code,
          'currency_value' => $currency_value,
          'order_status' => '0',
          'order_received_date' => $this->config->item('config.date.time'),
          'payment_method' => $costumer_data['payment_mode'],
          'payment_status' => 'Unpaid'
      );
      if (!$this->cart_model->is_order_no_exits($invoice_number)) {
        $orderId = $this->cart_model->safe_insert('wps_order', $data_order, FALSE);
        $this->session->set_userdata(array('working_order_id' => $orderId));
        foreach ($this->cart->contents() as $items) {
            $thumbc['width'] = 195;
            $thumbc['height'] = 150;
            $thumb_name = "thumb_" . $thumbc['width'] . "_" . $thumbc['height'] . "_" . $items['img'];
            $image_file = IMG_CACH_DIR . "/" . $thumb_name;
            $default_no_img = FCROOT . "assets/designer/themes/default/images/noimage.jpg";
            $file_data = ( file_exists($image_file) ) ? file_get_contents($image_file) : file_get_contents($default_no_img);
            $data = array(
                'order_id' => $orderId,
                'products_id' => $items['pid'],
                'product_name' => $items['origname'],
                'product_code' => $items['code'],
                'product_image' => $file_data,
                'product_image_name' => $items['img'],
                'product_price' => $items['price'],
                'quantity' => $items['qty'],
                'color_id' => @$items['options']['Color'],
                'size_id' => @$items['options']['Size'],
                'gst' => '0',
                'product_size' => '',
                'discount_id' => 0,
                'special_offer_id' => 0,
                'shipping_charges' => '0',
            );
            $this->cart_model->safe_insert('wps_orders_products', $data, FALSE);
        }
        $user_id = $this->session->userdata('user_id');
        $this->cart->destroy();
        $data = array('shipping_id' => 0, 'coupon_id' => 0, 'discount_amount' => 0, 'posted_data' => 0, 'is_same_bill_ship' => 0);
        $this->session->unset_userdata($data);
        $this->session->unset_userdata('coupon_id');
        $this->session->unset_userdata('discount_amount');
        $this->session->unset_userdata('posted_data');
        $this->session->unset_userdata('is_same_bill_ship');
      }
      
    }
   
  }

  public function add_to_cart() {
    $this->add_cart();
  }

  private function add_cart() {
    $productId =  $this->input->post('product_id');
    $color = (int) $this->input->post('color_id');
    $size = (int) $this->input->post('size_id');
    $qty = ($this->input->post('qty') > 0) ? $this->input->post('qty') : 1;
    
    $option = array('productid' => $productId);
    $pres = $this->product_model->get_products(1, 0, $option);
    $pres = $pres[0];
    $res_base_price = array();
    $prod_option = array('Size' => $size, 'Color' => $color);
    $bulkDiscountedPrice = $pres['product_discounted_price'];
    $product_price = $pres['product_price'];
    $media = $pres['media'];
   
    $res_base_price['bulkDiscountedPrice'] = $bulkDiscountedPrice;
    $res_base_price['product_price'] = $product_price;
    if($color>0 && $size>0){
      $res = $this->db->select('quantity,product_price,product_discounted_price')->get_where('wps_product_attributes', array('color_id' => $color, 'size_id' => $size, 'product_id' => $productId))->row();
      if (is_object($res)) {
        $res_base_price['bulkDiscountedPrice'] = $res->product_discounted_price;
        $res_base_price['product_price'] = $res->product_price;
        $res_base_price['quantity'] = $res->quantity;
      }
    }elseif($color>0 && $size<1){
      $res = $this->db->select('quantity,product_price,product_discounted_price')->get_where('wps_product_attributes', array('color_id' => $color,'product_id' => $productId))->row();
      if (is_object($res)) {
        $res_base_price['bulkDiscountedPrice'] = $res->product_discounted_price;
        $res_base_price['product_price'] = $res->product_price;
        $res_base_price['quantity'] = $res->quantity;
      }
    }elseif($color<1 && $size>0){
      $res = $this->db->select('quantity,product_price,product_discounted_price')->get_where('wps_product_attributes', array('size_id' => $size,'product_id' => $productId))->row();
      if (is_object($res)) {
        $res_base_price['bulkDiscountedPrice'] = $res->product_discounted_price;
        $res_base_price['product_price'] = $res->product_price;
        $res_base_price['quantity'] = $res->quantity;
      }
    }else{
       $res_base_price['quantity'] = $pres['product_qty'];
    }
    $cart_price = ($res_base_price['bulkDiscountedPrice'] > 0) ? $res_base_price['bulkDiscountedPrice'] : $res_base_price['product_price'];

    if ((is_array($pres) && !empty($pres)) && (is_array($res_base_price) && !empty($res_base_price))) {
      $cart_price = ((int) $res_base_price['bulkDiscountedPrice'] > 0) ? $res_base_price['bulkDiscountedPrice'] : $res_base_price['product_price'];
      $is_exits_inot_cart = $this->check_product_exits_into_cart($pres);
      if ($is_exits_inot_cart == 1) {
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Product already exists to cart.');
        //redirect('cart', 'refresh');
        redirect($_SERVER['HTTP_REFERER'], 'refresh');
      } else {
        $availableqty = $res_base_price['quantity'];
        $cart_data = array(
            'id' => random_string('numeric', 6),
            'qty' => $qty,
            'availableqty' => $availableqty,
            'price' => $cart_price,
            'product_price' => $res_base_price['product_price'],
            'discount_price' => $res_base_price['bulkDiscountedPrice'],
            'name' => url_title($pres['product_name']),
            'origname' => $pres['product_name'],
            'pid' => $pres['products_id'],
            'img' => $media,
            'code' => $pres['product_code'],
            'options' => $prod_option
        );
        $this->cart->insert($cart_data);
        
        
        //re calculate coupon
        if ($this->session->userdata('coupon_id') != '' && $this->session->userdata('discount_amount') > 0) {
          $this->reApplycoupon($this->session->userdata('coupon_id'));
        }
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Product has been added to cart.');
        // redirect('cart', 'refresh');
        redirect($_SERVER['HTTP_REFERER'], 'refresh');
      }
    } else {
      redirect("home");
    }
  }

 

  public function check_product_exits_into_cart($pres) {
    $cart_array = $this->cart->contents();
    $insert_flag = 0;
    if (is_array($cart_array) && !empty($cart_array)) {
      foreach ($this->cart->contents() as $item) {
        if (array_key_exists('pid', $item)) {
          if ($item['pid'] == $pres['products_id']) {
            $insert_flag = 1;
          }
        }
      }
    }
    return $insert_flag;
  }

  public function empty_cart() {
    $this->cart->destroy();
    $data2 = array(
        'shipping_id' => 0,
        'coupon_id' => 0,
        'discount_amount' => 0
    );
    $this->session->unset_userdata($data2);
    redirect('cart');
  }

  public function remove_item() {
    $data = array(
        'rowid' => $this->uri->segment(3),
        'qty' => 0
    );
    $this->cart->update($data);
    if ($this->cart->total_items() == 0) {
      //$this->session->unset_userdata(array('coupon_id' => 0, 'discount_amount' => 0));
      $this->session->unset_userdata('coupon_id');
      $this->session->unset_userdata('discount_amount');
    } else {
      //re calculate coupon
      if ($this->session->userdata('coupon_id') != '' && $this->session->userdata('discount_amount') > 0) {
        $this->reApplycoupon($this->session->userdata('coupon_id'));
      }
    }
    $this->session->set_userdata(array('msg_type' => 'success'));
    $this->session->set_flashdata('success', $this->config->item('cart_delete_item'));
    redirect($_SERVER['HTTP_REFERER'], 'refresh');
  }

  public function update_cart_qty() {

    $cart = $this->cart->contents();
    for ($i = 1; $i <= count($cart); $i++) {
      $item = $this->input->post($i);
      $cart_id = $item['rowid'];
      if ($item['qty'] <= 0) {
        $res = array('error_type' => 'error', 'error_msg' => "Can not update less then 0");
      } elseif (1000 >= $item['qty']) {
        $data = array(
            'rowid' => $item['rowid'],
            'qty' => $item['qty'],
        );
        
        $this->cart->update($data);
        $res = array('error_type' => 'pass', 'error_msg' => $this->config->item('cart_quantity_update'));
      } else {
        $res = array('error_type' => 'error', 'error_msg' => "Can not update more then available quantity");
      }
    }
    //re calculate coupon
    if ($this->session->userdata('coupon_id') != '' && $this->session->userdata('discount_amount') > 0) {
      $this->reApplycoupon($this->session->userdata('coupon_id'));
    }
    echo json_encode($res);
  }

  public function count_cart_item() {
    return $this->cart->total_items();
  }

  public function cart_total_amount() {
    $total = $this->cart->total();
    return $total;
  }

  public function display_cart_image($orders_products_id) {
    $binary_data = get_db_field_value('wps_orders_products', 'product_image', array('orders_products_id' => $orders_products_id));
    header("Content-Type: image/jpeg");
    echo $binary_data;
  }

  public function applycoupon() {
          $coupon_code = $this->input->get_post('couponcode');
          $amt = $this->input->get_post('amt');
          //AND minimum_amount_for_coupan_apply <= '" . $amt . "'
          $cdets = get_db_single_row('wps_discount_coupans', "cpn_id, cpn_type, cpn_code, cpn_rate, cpn_start_date, cpn_end_date", "cpn_start_date <= '" . date('Y-m-d') . "' AND cpn_end_date >= '" . date('Y-m-d') . "' AND cpn_code = '" . $coupon_code . "' AND minimum_amount_for_coupan_apply <= '" . $amt . "'");
          // print_r($cdets);
          if (is_array($cdets) && !empty($cdets)) {
            if ($cdets['cpn_type'] == '0') {
              $discount = "";
              $discount = $cdets['cpn_rate'];
              $this->session->set_userdata('discount_amount', $discount);
              $this->session->set_userdata('coupon_id', $cdets['cpn_id']);
            } else {
              //check content of cart 
              $discountAmt = 0;
              foreach ($this->cart->contents() as $items) {
                $pprice = ($items['discount_price'] > 0) ? $items['discount_price'] : $items['product_price'];
                $discount = (($pprice * $items['qty']) * $cdets['cpn_rate'] / 100);
                $discountAmt += $discount;
              }
              //echo $discountAmt;
              $this->session->set_userdata('coupon_id',  $cdets['cpn_id']);
              $this->session->set_userdata('discount_amount', $discountAmt);
              //print_r($this->session->userdata('discount_amount'));
            }
            echo "Coupon Applied Successfully!";
          } else {
            echo "Invalid or Expired Coupon!";
          }
    
 
  }

  public function reApplycoupon($couponid) {
    $COUPONCODE = get_db_single_row('wps_discount_coupans', "cpn_code", "cpn_id = '" . $couponid . "'");
    $totalAmount = '';
    $cart = $this->cart->contents();
    foreach ($cart as $items) {
      $pprice = ($items['discount_price'] > 0) ? $items['discount_price'] : $items['product_price'];
      $totalAmount += ($pprice * $items['qty']);
    }

    $cdets = get_db_single_row('wps_discount_coupans', "cpn_id, cpn_type, cpn_code, cpn_rate, cpn_start_date, cpn_end_date", "cpn_start_date <= '" . date('Y-m-d') . "' AND cpn_end_date >= '" . date('Y-m-d') . "' AND cpn_code = '" . $COUPONCODE['cpn_code'] . "' AND minimum_amount_for_coupan_apply <= '" . $amt . "'");
    //echo_sql();
    if (is_array($cdets) && !empty($cdets)) {
      if ($cdets['cpn_type'] == '0') {
        $discount = "";
        $discount = $cdets['cpn_rate'];
        $this->session->set_userdata('discount_amount', $discount);
        $this->session->set_userdata('coupon_id', $cdets['cpn_id']);
      } else {
        //check content of cart
        $discountAmt = 0;
        foreach ($this->cart->contents() as $items) {
          $pprice = ($items['discount_price'] > 0) ? $items['discount_price'] : $items['product_price'];
          $discount = (($pprice * $items['qty']) * $cdets['cpn_rate'] / 100);
          $discountAmt += $discount;
        }
        $this->session->set_userdata('coupon_id', $cdets['cpn_id']);
        $this->session->set_userdata('discount_amount', round($discountAmt));
      }
      //echo "Coupon Applied Successfully!";
    } else {
      $this->session->unset_userdata('coupon_id');
      $this->session->unset_userdata('discount_amount');
    }
  }

  public function removecoupon() {
    $couponData = array(
        'coupon_id' => 0,
        'discount_amount' => 0
    );
    $this->session->unset_userdata('coupon_id');
    $this->session->unset_userdata('discount_amount');
    echo 'Coupon Removed Successfully!';
  }

  public function add_to_wishlist() {
    $product_id = (int) $this->uri->segment(3);

    //trace($category_id);
    if ($this->session->userdata('user_id') > 0) {
      $this->cart_model->add_wislists($product_id, $this->session->userdata('user_id'));
      redirect('members/mywishlist');
    } else {
      redirect('login');
    }
  }

  public function print_invoice() {
    $this->load->model(array('order/order_model'));
    $ordId = $this->uri->segment(3, $this->session->userdata('working_order_id'));
    $order_res = $this->order_model->get_order_master($ordId);
    $order_details_res = $this->order_model->get_order_detail($order_res['order_id']);
    $data['orddetail'] = $order_details_res;
    $data['ordmaster'] = $order_res;
    $data['ordId'] = $ordId;
    $this->load->view('view_invoice_print', $data);
  }

}

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