<?php

class Payment extends Public_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->helper(array('cart/cart', 'file' , 'payment/razorpay','payment/paypal'));
    $this->load->model(array('order/order_model', 'payment/payment_model'));
    $this->load->library(array('Dmailer', 'safe_encrypt'));
    $this->page_section_ct = 'common';
  }

  public function index() {
    $payMode = str_replace('.html', '', $this->input->get_post('pay_method'));
    //print_r($payMode);
if ($payMode == "COD") {
      $this->pay_by_check();
     } elseif ($payMode == "Paypal") {
        $data = array('payment_method' => $payMode, 'payment_status' => 'Unpaid');
        $ordId = $this->session->userdata('working_order_id');
        $where = "order_id = '" . $ordId . "' ";
        $order_res = $this->order_model->get_order_master($ordId);    
        paypalForm($order_res);
      }
  }


 public function pay_by_check() {
    $data = array('payment_method' => 'Cash', 'payment_status' => 'Unpaid');
    $ordId = $this->session->userdata('working_order_id');
    $where = "order_id = '" . $ordId . "' ";
    $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
    $condition = "&& order_id='" . $ordId . "'";
    $cupn = $this->order_model->get_orders(0, 1, $condition);
    $cupn = $cupn[0];
    $ordId = md5($ordId);
    $res = get_db_field_value('wps_order', 'order_id', array('MD5(order_id)' => $ordId));
    $ordmaster = $this->order_model->get_order_master($res);
    $orddetail = $this->order_model->get_order_detail($res);
    // print_r($ordmaster);
    // print_r($orddetail);
    // echo $body;
    // exit(); 
    if (is_array($ordmaster) && !empty($ordmaster)) {
      ob_start();
      $mail_subject = $this->config->item('site_name') . " Order Oerview";
      $from_email = $this->admin_info->admin_email;
      $from_name = $this->config->item('site_name');
      $mail_to = $ordmaster['email'];
      $body = invoice_content_print($ordmaster, $orddetail);
      $msg = ob_get_contents();
      $mail_conf = array(
          'subject' => $this->config->item('site_name') . " Order overview",
          'to_email' => $mail_to,
          'from_email' => $from_email,
          'from_name' => $this->config->item('site_name'),
          'body_part' => $msg
      );
      //trace($mail_conf); die;
      $this->dmailer->mail_notify($mail_conf);
  if($this->admin_info->website_mode=='Live'){
      $mail_conf2 = array(
          'subject' => $this->config->item('site_name') . " Order overview",
          'to_email' => $this->admin_info->admin_email,
          'from_email' => $from_email,
          'from_name' => $this->config->item('site_name'),
          'body_part' => $msg
      );
      //trace($mail_conf); die;
      $this->dmailer->mail_notify($mail_conf2);
      $mail_conf4 = array(
          'subject' => $this->config->item('site_name') . " Order overview",
          'to_email' => "webpulseindia@gmail.com",
          'from_email' => $from_email,
          'from_name' => $this->config->item('site_name'),
          'body_part' => $msg
      );
      $this->dmailer->mail_notify($mail_conf4);
    }else{
      $mail_conf4 = array(
                  'subject' => $this->config->item('site_name') . " Order overview",
                  'to_email' => 'test.webpulse@gmail.com', //
                  'from_email' => $from_email,
                  'from_name' => $this->config->item('site_name'),
                  'body_part' => $msg,
              );
              $this->dmailer->mail_notify($mail_conf4);
    }
    }
    redirect('payment/thanks/' . $ordId, '');
  }
  
  public function order_success() {
    $ordId = $this->uri->segment(3);
    $this->session->unset_userdata(array('discount_amount' => 0));
    //update payment status
    $responses = json_encode($_REQUEST);
    print_r($responses); exit();
    if($_REQUEST['status']=='success'){
        $data = array('payment_method' => 'Payu', 'payment_status' => 'Paid', 'paymentResponse' => $responses);
        //$where = "MD5(order_id) = '$ordId' ";
        $where = "order_id = '$ordId' ";
        $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
        //echo_sql();
        //exit;
        // $res = get_db_field_value('wps_order', 'order_id', array('MD5(order_id)' => $ordId));
        $res = get_db_field_value('wps_order', 'order_id', array('order_id' => $ordId));
        $ordmaster = $this->order_model->get_order_master($res);
        $orddetail = $this->order_model->get_order_detail($res);
        $this->update_stocks($ordId);
        if (is_array($ordmaster) && !empty($ordmaster)) {
          ob_start();
          $mail_subject = $this->config->item('site_name') . " Order Oerview";
          $from_email = $this->admin_info->admin_email;
          $from_name = $this->config->item('site_name');
          $mail_to = $ordmaster['email'];
          $body = invoice_content_print($ordmaster, $orddetail);
          $msg = ob_get_contents();

          $mail_conf = array(
              'subject' => $this->config->item('site_name') . " Order overview",
              'to_email' => $mail_to,
              'from_email' => $from_email,
              'from_name' => $this->config->item('site_name'),
              'body_part' => $msg
          );
          //trace($mail_conf); die;
          $this->dmailer->mail_notify($mail_conf);
            if($this->admin_info->website_mode=='Live'){
                $mail_conf2 = array(
                    'subject' => $this->config->item('site_name') . " Order overview",
                    'to_email' => $this->admin_info->admin_email,
                    'from_email' => $from_email,
                    'from_name' => $this->config->item('site_name'),
                    'body_part' => $msg
                );
                //trace($mail_conf); die;
                $this->dmailer->mail_notify($mail_conf2);
                $mail_conf4 = array(
                    'subject' => $this->config->item('site_name') . " Order overview",
                    'to_email' => "webpulseindia@gmail.com",
                    'from_email' => $from_email,
                    'from_name' => $this->config->item('site_name'),
                    'body_part' => $msg
                );
                $this->dmailer->mail_notify($mail_conf4);
            }else{
              $mail_conf4 = array(
                          'subject' => $this->config->item('site_name') . " Order overview",
                          'to_email' => 'test.webpulse@gmail.com', //
                          'from_email' => $from_email,
                          'from_name' => $this->config->item('site_name'),
                          'body_part' => $msg,
                      );
                      $this->dmailer->mail_notify($mail_conf4);
            }
        }
        $this->session->set_flashdata('msg', $this->config->item('payment_success'));
    }else{
      $data = array('payment_method' => 'Payu', 'payment_status' => 'Unpaid', 'paymentResponse' => $responses);
      $where = "order_id = '$ordId' ";
      $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
      $this->session->set_flashdata('msg', $this->config->item('payment_failed'));
    }
    $this->session->unset_userdata(array('working_order_id' => 0));
    redirect('payment/thanks/'.md5($ordId));
  }

  

  public function order_cancle() {
    $ordId = $this->uri->segment(3);
    $responses = json_encode($_REQUEST);
    $data = array('order_status' => '5', 'paymentResponse' => $responses);
    $where = "MD5(order_id) = '$ordId' ";
    // $where = "order_id = '$ordId' ";

    // print_r($responses); exit();
    $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
    $this->session->unset_userdata(array('working_order_id' => 0));
    $this->session->set_flashdata('msg', $this->config->item('payment_failed'));
    redirect('payment/thanks/'.$ordId);
  }

  public function thanks() {
    $order_id = str_replace('.html', '', $this->uri->segment(3));
    $res = get_db_field_value('wps_order', 'order_id', array('md5(order_id)' => $order_id));
    if ($res > 0) {
      $data['title'] = "Invoice Print";
      $order_res = $this->order_model->get_order_master($res);
      //trace($order_res);
      $order_details_res = $this->order_model->get_order_detail($res);
      $data['orddetail'] = $order_details_res;
      $data['ordmaster'] = $order_res;
      $this->load->view('payment/pay_thanks', $data);
    }
  }

    //RAZORPAY INTEGRATION STARTS HERE
  private function get_curl_handle($payment_id, $amount) {
    $amount = ($amount > 0) ? $amount : 100;
    $headers = array();
    $url = 'https://api.razorpay.com/v1/payments/' . $payment_id . '/capture';
    $key_id = RAZOR_KEY_ID;
    $key_secret = RAZOR_KEY_SECRET;
    $headers[] = "Content-Type: application/json";
    $headers[] = 'Authorization:Basic ' . base64_encode($key_id . ':' . $key_secret);

    $post_data = json_encode(array(
        "amount" => $amount,
    ));
    $timeout = 100; // set to zero for no timeout
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $result = curl_exec($ch);
    //$curl_error = curl_errno($ch);
    //trace($result);
    return $result;
  }

  // callback method
  public function callback() {
    //trace($_POST);
    if (!empty($this->input->post('razorpay_payment_id'))) {
      $razorpay_payment_id = $this->input->post('razorpay_payment_id');
      //trace($this->session->userdata);
      $merchant_order_id = $this->uri->segment(3);//$this->session->userdata('working_order_id');
      $where = "order_id = '" . $merchant_order_id . "' ";
      $order_res = $this->order_model->get_order_master($merchant_order_id);
      $amount = (($order_res['total_amount'] + $order_res['shipping_amount'] - $order_res['coupon_discount_amount']) * 100);

      $success = false;
      $error = '';
      try {
        $result = $this->get_curl_handle($razorpay_payment_id, $amount);
        //trace($result);
        //execute post
        if ($result === false) {
          $success = false;
          $data = array('payment_method' => 'RazorPay', 'paymentResponse' => $result);
          $where = "order_id = '$merchant_order_id' ";
          $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
          redirect(site_url() . 'payment/failed/' . $merchant_order_id);
          //$error = 'Curl error: ' . curl_error($ch);
        } else {
          $response_array = json_decode($result, true);
          if (isset($response_array['status']) && $response_array['status'] == 'captured') {
            $this->success($merchant_order_id, $result);
          } elseif ($response_array['error']['field']['status'] == 'captured') {
            $this->success($merchant_order_id, $result);
          } else {
            $data = array('payment_method' => 'RazorPay', 'paymentResponse' => $result);
            $where = "order_id = '$merchant_order_id' ";
            $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
            redirect(site_url() . 'payment/failed/' . $merchant_order_id);
          }
        }
      } catch (Exception $e) {
        $success = false;
        $data = array('payment_method' => 'RazorPay', 'paymentResponse' => $result);
        $where = "order_id = '$merchant_order_id' ";
        $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
        redirect(site_url() . 'payment/failed/' . $merchant_order_id);
      }
    } else {
      $data = array('payment_method' => 'RazorPay', 'paymentResponse' => $result);
      $where = "order_id = '$merchant_order_id' ";
      $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
      redirect(site_url() . 'payment/failed/' . $merchant_order_id);
      //echo 'An error occured. Contact site administrator, please!';
    }
  }

    public function success($ordId, $response) {
    $data = array('payment_method' => 'RazorPay', 'payment_status' => 'Paid', 'paymentResponse' => $response);
    $where = "order_id = '$ordId' ";
    $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
    //echo_sql();
    //exit;

    $res = get_db_field_value('wps_order', 'order_id', array('order_id' => $ordId));
    $ordmaster = $this->order_model->get_order_master($res);
    $orddetail = $this->order_model->get_order_detail($res);
    $order_res = $orddetail;
    if (is_array($ordmaster) && !empty($ordmaster)) {
      ob_start();
      $mail_subject = $this->config->item('site_name') . " Order Oerview";
      $from_email = $this->admin_info->admin_email;
      $from_name = $this->config->item('site_name');
      $mail_to = $ordmaster['email'];
      $body = invoice_content_print($ordmaster, $orddetail);
      $msg = ob_get_contents();
      $ord_data['orddetail'] = $orddetail;
      $ord_data['ordmaster'] = $ordmaster;
      //$msg = $this->load->view('mailers/order_success', $ord_data, true);

      //mail to user
      $mail_conf = array(
          'subject' => $this->config->item('site_name') . " Order overview",
          'to_email' => $mail_to,
          'from_email' => $from_email,
          'from_name' => $this->config->item('site_name'),
          'body_part' => $msg
      );
      //trace($mail_conf); die;
      $this->dmailer->mail_notify($mail_conf);
      //end
      //Mail to Admin
      $mail_conf = array(
          'subject' => "New Order Received",
          'to_email' => $from_email,
          'from_email' => $from_email,
          'from_name' => $this->config->item('site_name'),
          'body_part' => $msg
      );
      //trace($mail_conf); die;
      //$this->dmailer->mail_notify($mail_conf);
      //End here
      //Inventory Updation
      foreach ($order_res as $res1) {
        $qty1 = $res1['quantity'];
        //$this->db->query("UPDATE wl_products SET product_qty = product_qty-$qty1 WHERE products_id='" . $res['products_id'] . "'");
      }
    }

    $this->session->set_flashdata('msg', $this->config->item('payment_success'));
    redirect('payment/thanks/' . md5($ordId), '');
    //$this->load->view('razorpay/success', $data);
  }

   public function failed() {
    $ordId = (int) $this->uri->segment(3);
    if($ordId <= 0){
      $ordId = $this->session->userdata('working_order_id');
    }
    //trace($this->session->userdata);
    //trace($_POST);
    //echo $ordId; die;
    $data = array('order_status' => 'Canceled');
    $where = "order_id = '$ordId' ";
    $this->payment_model->safe_update('wps_order', $data, $where, FALSE);

    $res = get_db_field_value('wps_order', 'order_id', array('order_id' => $ordId));
    $this->session->unset_userdata(array('working_order_id' => 0));
    $this->session->set_flashdata('msg', $this->config->item('payment_failed'));

    $ordmaster = $this->order_model->get_order_master($res);
    //trace($ordmaster);
    $orddetail = $this->order_model->get_order_detail($res);
    $data['orddetail'] = $orddetail;
    $data['ordmaster'] = $ordmaster;

    $this->load->view('payment/pay_thanks', $data);
    //$this->load->view('razorpay/failed', $data);
  }

  public function update_stocks($order_id) {
    $order_id = (int) $order_id;
    $condtion = array('field' => "products_id,quantity,color_id,size_id", 'condition' => "order_id ='$order_id'", 'index' => 'products_id');
    $orders_res = $this->order_model->findAll('wps_orders_products', $condtion);
    if (is_array($orders_res) && !empty($orders_res)) {
      foreach ($orders_res as $v) {
          $qty = $v['quantity'];
          $sql = "UPDATE wps_products SET product_qty = product_qty-$qty WHERE products_id = '" . $v['products_id'] . "'";
          $this->db->query($sql);

          if($v['color_id']>0 && $v['size_id']>0){
            $qty = $v['quantity'];
            $sql = "UPDATE wps_product_attributes SET quantity = quantity-$qty WHERE product_id = '" . $v['products_id'] . "' and color_id = '" . $v['color_id'] . "' and size_id = '" . $v['size_id'] . "'";
            $this->db->query($sql);
          }elseif($v['color_id']>0 && $v['size_id']=='0'){
            $qty = $v['quantity'];
            $sql = "UPDATE wps_product_attributes SET quantity = quantity-$qty WHERE product_id = '" . $v['products_id'] . "' and color_id = '" . $v['color_id'] . "' and size_id = '0'";
            $this->db->query($sql);
          }elseif($v['color_id']=='0' && $v['size_id']>0){
            $qty = $v['quantity'];
            $sql = "UPDATE wps_product_attributes SET quantity = quantity-$qty WHERE product_id = '" . $v['products_id'] . "' and color_id = '0' and size_id = '" . $v['size_id'] . "'";
            $this->db->query($sql);
          }
      }
    }
  }

  

}

/* End of file member.php */

/* Location: .application/modules/products/controllers/cart.php */