<?php
class Payment extends Public_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->helper(array('cart/cart', 'file', 'payment/razorpay'));
    $this->load->model(array('order/order_model', 'payment/payment_model','members/members_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 == "RazorPay") {
      $working_order_id = $this->session->userdata('working_order_id');
      $order_res = $this->order_model->get_order_master($working_order_id);
      // trace($_POST);
      // exit;
      razorpayForm($order_res);
    } elseif ($payMode == "COD") {
      $this->pay_by_check();
    } else {
      $working_order_id = $this->session->userdata('working_order_id');
      $order_res = $this->order_model->get_order_master($working_order_id);
    //   trace($order_res);
    //   trace($_POST); exit();
     payuForm($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];
    $orderid = "TYZ000DEL0".$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);

    // trace($ordmaster);
    // trace($orddetail); 
    
    $response = $this->shiprocket->generateOrder($ordmaster,$orddetail);
    
    $shiprocket_orderid = $response['order_id'];
    $shiprocket_shipmentid = $response['shipment_id'];
    $data = array('shiprocket_orderid' => $shiprocket_orderid, 'shiprocket_shipmentid' => $shiprocket_shipmentid);
    $where = "order_id = '$ordId' ";
    $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
    // trace($response);
    // exit();
    
    $memid = $this->session->userdata('user_id');
    $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 = "1207164603082250900";

    $message = "Thanks%20for%20shopping%20with%20us.%20Your%20order%20%7B$orderid%7D%20is%20being%20processed%20for%20shipping.%20Once%20it%20is%20shipped%20you%20can%20track%20your%20order%20here%20%7B$trackinglink%7D.%20For%20more%20visit%20Toyzoo%20Store%20%7B$site_url%7D";
    
    if($response['status_code']==1){
    sendSms($mobile,$message,$tempid);
    }
    
    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->mode=='Live'){
      $mail_conf2 = array(
          'subject' => $this->config->item('site_name') . " Order overview",
          'to_email' => $this->admin_info->admin_email,
          'from_email' => $mail_to,
          'body_part' => $msg
      );
      //trace($mail_conf); die;
      $this->dmailer->mail_notify($mail_conf2);
      $mail_conf3 = array(
          'subject' => $this->config->item('site_name') . " Order overview",
          'to_email' => $this->admin_info->admin_email,
          'from_email' => $mail_to,
          'from_name' => $this->config->item('site_name'),
          'body_part' => $msg
      );
      $this->dmailer->mail_notify($mail_conf3);
    }else{
      $mail_conf4 = array(
                  'subject' => $this->config->item('site_name') . " Order overview",
                  'to_email' => $this->admin_info->admin_email,
                  'from_email' => $mail_to,
                  'from_name' => $this->config->item('site_name'),
                  'body_part' => $msg,
              );
              $this->dmailer->mail_notify($mail_conf4);
    }
    }
     
    redirect('payment/thanks/'.md5($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);

    if($_REQUEST['status']=='success'){
        $data = array('payment_method' => 'RazorPay', '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);
        $response = $this->shiprocket->generateOrder($ordmaster,$orddetail);
        
    $shiprocket_orderid = $response['order_id'];
    $shiprocket_shipmentid = $response['shipment_id'];
    $data = array('shiprocket_orderid' => $shiprocket_orderid, 'shiprocket_shipmentid' => $shiprocket_shipmentid);
    $where = "order_id = '$ordId' ";
    $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
        
    $ordId = $this->session->userdata('working_order_id');
    $orderid = "TYZ000DEL0".$ordId;
    $memid = $this->session->userdata('user_id');
    $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 = "1207164707719996835";

    $message = "Placed%3A%20Thanks%20for%20shopping%20with%20us.%20Your%20order%20%7B$orderid%7D%20is%20being%20processed%20for%20shipping.%20Once%20it%20is%20shipped%20you%20can%20track%20your%20order%20here%20%7B$trackinglink%7D";   
    
    if($response['status_code']==1){
    sendSms($mobile,$message,$tempid);
    } 
        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_conf3 = 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
                );
                $this->dmailer->mail_notify($mail_conf3);
            }else{
              $mail_conf4 = 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,
                      );
                      $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,'order_cancelled_date'=>$this->config->item('config.date.time'));
    // $where = "MD5(order_id) = '$ordId' ";
    $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));
    $ordmaster = $this->order_model->get_order_master($res);
    $orddetail = $this->order_model->get_order_detail($res);
    if (is_array($ordmaster) && !empty($ordmaster)) {
          ob_start();
          $mail_subject = $this->config->item('site_name') . " Payment failed";
          $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') . " Payment failed",
              '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') . " Payment failed",
                    '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_conf3 = array(
                    'subject' => $this->config->item('site_name') . " Payment failed",
                    'to_email' =>$this->admin_info->admin_email,
                    'from_email' => $from_email,
                    'from_name' => $this->config->item('site_name'),
                    'body_part' => $msg
                );
                $this->dmailer->mail_notify($mail_conf3);
            }else{
              $mail_conf4 = array(
                          'subject' => $this->config->item('site_name') . "Payment failed",
                          'to_email' => $this->admin_info->admin_email,
                          'from_email' => $from_email,
                          'from_name' => $this->config->item('site_name'),
                          'body_part' => $msg,
                      );
                      $this->dmailer->mail_notify($mail_conf4);
            }
        }  
      
    $this->session->unset_userdata(array('working_order_id' => 0));
    $this->session->set_flashdata('msg', $this->config->item('payment_failed'));
    redirect('payment/thanks/'.md5($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);
    }
  }

    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;

    $shiprocket_orderid = $response['order_id'];
    $shiprocket_shipmentid = $response['shipment_id'];
    $data = array('shiprocket_orderid' => $shiprocket_orderid, 'shiprocket_shipmentid' => $shiprocket_shipmentid);
    $where = "order_id = '$ordId' ";
    $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
        
    $ordId = $this->session->userdata('working_order_id');
    $orderid = "TYZ000DEL0".$ordId;
    $memid = $this->session->userdata('user_id');
    $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 = "1207164707719996835";

    $message = "Placed%3A%20Thanks%20for%20shopping%20with%20us.%20Your%20order%20%7B$orderid%7D%20is%20being%20processed%20for%20shipping.%20Once%20it%20is%20shipped%20you%20can%20track%20your%20order%20here%20%7B$trackinglink%7D";   
    
    if($response['status_code']==1){
    sendSms($mobile,$message,$tempid);
    } 

    $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;

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

      //End here
      //Inventory Updation
      foreach ($order_res as $res1) {
        $qty1 = $res1['quantity'];

      }
    }

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

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

  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 */