<?php

defined('BASEPATH') OR exit('No direct script access allowed');



class Order extends CI_Controller {



	function __construct() 

	{

       // error_reporting(0);

        parent::__construct();

        $this->load->library('cart');

        $this->load->model('CommonModel');

        $this->load->helper('Security');

        $this->load->library('instamojo');

    }

    public function checkout(){
        if($this->session->userdata('customer')){
        // $input_data = $this->input->post();
        // $input_data = $this->security->xss_clean($input_data);
        $chechout_data = $this->db->select('*')->where('c_id', $this->session->userdata('customer'))->get('chechout')->result_array();
        $data['chechout_data']=$chechout_data;
        $prod_id='';
        //$prod_id=implode(",", $input_data['prd_id']);
        //$p_quantity=implode(',', $input_data['quantity']);
        $p_quantity='';
        foreach ($chechout_data as $key => $chk_data) {
            if ($prod_id=='') {
                $prod_id=$chk_data['prd_id'];
            }
            else
            {
                $prod_id=$prod_id.','.$chk_data['prd_id'];
            }
            if ($p_quantity=='') {
                $p_quantity=$chk_data['quantity'];
            }
            else
            {
                $p_quantity=$p_quantity.','.$chk_data['quantity'];
            }
        }
        $this->session->set_userdata('chkprd_id', $prod_id);
        $this->session->set_userdata('chkquantity', $p_quantity);
        $this->session->set_userdata('login_session', true);
        //print_r($prod_id); die;chechout
         
        $data['content'] = 'checkout';
        $this->load->view('layout_home', $data);
        }
        else{
            redirect(base_url("product/cart_details/"));
        }
    }

    public function pin_search(){
        $input_data = $this->input->post();
        $input_data = $this->security->xss_clean($input_data);
        $pinchk = $this->db->select('*')->where('pin', $input_data['pin'])->get('active_pin')->result_array();
        if(empty($pinchk)){
            echo 'failed';
        }
        else{
            echo 'success';
        }
    }
	public function order_booking(){
        // print_r($this->session->userdata('prd_id')); die;

 ///////////////////////Shipping data Add /////////////////////////////////////

		date_default_timezone_set('Asia/Kolkata');
		$date = date('d-m-Y h:i:s a', time());
        $delivery_date = date('Y-m-d',strtotime('+7 day',strtotime($date)));
		$input_data = $this->input->post();
    	$input_data = $this->security->xss_clean($input_data);
        
		$insert_data['c_id'] = $this->session->userdata('customer');
        $insert_data['name'] = $input_data['name'];
        $insert_data['email'] = $input_data['email'];
        $insert_data['mobile'] = $input_data['mobile'];
        $insert_data['delivery_add'] = $input_data['address'];
        $insert_data['country'] = 'India';
        $insert_data['state'] = $input_data['state'];
        $insert_data['city'] = $input_data['city'];
        $insert_data['pin'] = $input_data['pin'];
        $insert_data['lmark'] = $input_data['landmark'];
        $insert_data['time'] = $date;
        $this->db->insert('shipping',$insert_data);
        $shipping_id = $this->db->insert_id();
        $order_number='TOP10O00'.date('ymd').$shipping_id;
        $shipping_upd = "UPDATE `shipping` SET `order_number` = '".$order_number."' WHERE `id` = '".$shipping_id."'";
        $this->db->query($shipping_upd);
        $user_upd = "UPDATE `customer` SET `state` = '".$input_data['state']."',`city` = '".$input_data['city']."', `address` = '".$input_data['address']."',`pin` = '".$input_data['pin']."' WHERE `c_id` = '".$this->session->userdata('customer')."'";
        $this->db->query($user_upd);

        

/////////////////////////////// Order Booking //////////////////////////////////////

        if($this->session->userdata('customer')){
            $input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);
            $mode=$input_data['payment'];
            $sql = "UPDATE `shipping` SET `mode` = '".$mode."' WHERE `id` = '".$shipping_id."'";
            $this->db->query($sql);
            //$p_id=implode(',', $this->session->userdata('prd_id'));
            //$p_quantity=implode(',', $this->session->userdata('quantity'));
            $product_id=explode(",", $this->session->userdata('chkprd_id'));
            $row_checkout = $this->db->select('*')->where('c_id', $this->session->userdata('customer'))->get('chechout')->result_array();
            $all_product='';
            foreach ($row_checkout as $key_product) {    
            $insert_data_order['shipping_id'] = $shipping_id;
            $insert_data_order['date'] = $date;
            $insert_data_order['delevery_date'] = $delivery_date;
            $insert_data_order['status'] = 'Pending';
            $this->db->insert('order_history',$insert_data_order);
            $last_id = $this->db->insert_id();
            $last_ivn=$last_id;
            $odate=date("dmy");
            $invoice_no="Top1000".$odate.$last_ivn;
            
                $row_product = $this->db->select('*')->where('prd_id', $key_product['prd_id'])->get('product')->result_array();
                $pindetails = $this->db->where('pin', $input_data['pin'])->get('active_pin')->result_array();
                $total=$key_product['quantity']*$row_product[0]['p_sell_price'];
                $total=$total+$row_product['0']['shiping_chrg'];
                $colour='';
                $size=''; 
                $product_name=$row_product[0]['p_title'];
                $all_product=$all_product.' '.$product_name;
                $order_upd_2 = "UPDATE `order_history` SET `invoice_no` = '".$invoice_no."',`prd_id` = '".$key_product['prd_id']."',`pqun` = '".$key_product['quantity']."', `colour` = '".$key_product['colour']."',`size` = '".$key_product['size']."',`sell_price` = '".$row_product[0]['p_sell_price']."',`mrp` = '".$row_product[0]['p_mrp']."',`pname` = '".$row_product[0]['p_title']."',`total` = '".$total."' WHERE `order_id` = '".$last_id."'";
                 $this->db->query($order_upd_2);
                }
            if($mode=='Online'){
                $prod_name ='';
                $price = 0;
                $order_id = '';
                 $resulti = $this->db->select('*')->where('shipping_id', $shipping_id)->get('order_history')->result_array();
                 foreach ($resulti as $key => $res_val) {
                    $prod_name = substr($res_val['pname'], 0,30);
                    $price = $price + $res_val['total'];
                 }
                 $fetch_cus = $this->db->select('*')->where('id', $resulti[0]['shipping_id'])->get('shipping')->result_array();
                $name = $fetch_cus[0]['name'];
                $phone = $fetch_cus[0]['mobile'];
                $email = $fetch_cus[0]['email'];
                //include APPPATH.'instamojo/src/Instamojo.php';
                $api = new Instamojo\Instamojo('cad88114fc20c5e28c778cc73e28227c', '062c7590831a212e7c06e14f5fbf5f95','https://www.instamojo.com/api/1.1/');
                try {
                    $response = $api->paymentRequestCreate(array(
                        "purpose" => $all_product,
                        "amount" => $price,
                        "buyer_name" => $name,
                        "phone" => $phone,
                        "send_email" => true,
                        "send_sms" => true,
                        "email" => $email,
                        'allow_repeated_payments' => false,
                        "redirect_url" => "https://gaineronline.com/order/thanks/?menu=".$shipping_id,
                        "webhook" => "https://gaineronline.com/instamojo/webhook.php"
                        ));
                    //print_r($response);
                    $pay_ulr = $response['longurl'];
                    //Redirect($response['longurl'],302); //Go to Payment page
                    header("Location: $pay_ulr");
                    exit();
                }
                catch (Exception $e) {
                    print('Error: ' . $e->getMessage());
                }     
            }
            else{
                $prod_ttl='THANK-YOU-For-Shopping-With-Us';
                redirect(base_url("order/thanks/?".$prod_ttl."&menu=".$shipping_id."&payment_status=Credit"));
            }
        }
        else{
            redirect(base_url());
        }
	}

    public function thanks()
    {
        $input_data = $this->input->get();
        $input_data = $this->security->xss_clean($input_data);
        if(!empty($this->input->get('menu')) && $this->input->get('payment_status')=='Credit'){

$orderval=$this->db->select('*')->where('shipping_id', $this->input->get('menu'))->get('order_history')->result_array();


foreach($orderval as $row_checkout_success){

     $fetch_product = $this->db->select('*')->where('prd_id', $row_checkout_success['prd_id'])->get('product')->result_array();
     $order_shipping=$this->db->select('*')->where('id', $this->input->get('menu'))->where('c_id', $this->session->userdata('customer'))->get('shipping')->result_array();

         $id=$row_checkout_success['prd_id'];

    //     $quantity=$fetch_product[0]['primary_image'];

        $order_quantity=$row_checkout_success['pqun'];

        //$new_quantity=$quantity-$order_quantity;

        $upd_prd= "update `product` set `p_quantity`=`p_quantity`-$order_quantity where `prd_id`='".$id."'";

        $this->db->query($upd_prd);

        $upd="UPDATE `inventory` SET `available_stock` = `available_stock`-$order_quantity WHERE `size` = '".$row_checkout_success['size']."' and `prd_id`='".$id."' ";
        $query = $this->db->query($upd);
    $order_upd_2 = "UPDATE `order_history` SET `booking_status` = '1' WHERE `order_id` = '".$row_checkout_success['order_id']."'";

    $this->db->query($order_upd_2); 


$content="<!DOCTYPE html>

<html lang='en'>

  <head>

    <meta charset='utf-8'>

    <meta http-equiv='X-UA-Compatible' content='IE=edge'>

    <meta name='viewport' content='width=device-width, initial-scale=1'>

    <title>Mailer</title>



<style>

@import url('https://fonts.googleapis.com/css?family=Open+Sans');

body{

font-family: 'Open Sans', sans-serif;

}

.mailerMain{

width:540px;

background:#fbfbfb;

margin:0 auto;

padding:15px 30px;

}
table{
        margin:30px 0;
        }
        table tr td, table tr th{
        border: 1px solid #ccc;
        padding: 6px;
        line-height: 1.42857143;
        vertical-align: middle;
        font-size: 14px;
        }
.logoimgHeight{

height:75px;

}

.cartbag{

margin-top:20px;

height:80px;

}

.btn-black {

    background: #7e7e7e;

    color: #fff;

    padding: 4px 20px;

    text-decoration:none;

    font-size:13px;

}

.social img{

        height:30px;

        margin:10px 5px;

        }

@media screen and (max-width: 768px){

.mailerMain{

width:auto;

padding:15px;

}

}

</style>

</head>

<body>

<div class='mailerMain' align='center'>

    <div class='mailHead'>

        <img src='https://gaineronline.com/assets/images/logo.png' class='logoimgHeight'>

    </div>

    <div class='mailBody'>

        <img src='https://gaineronline.com/images/tenor.gif' class='cartbag'>

        <p style='font-weight:bold; color:#000;'>Your order has been booked successfully</p>

        <table class='table resImg' cellspacing='0' cellpadding='0' width='100%'>
                            <tr>
                                <th width='50%' style='background:#eee;'>Order ID</th>
                                <td width='50%'>".$row_checkout_success['invoice_no']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Product</th>
                                <td width='50%'>".$row_checkout_success['pname']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Contact Number</th>
                                <td width='50%'>".$order_shipping[0]['mobile']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Address</th>
                                <td width='50%'>".$order_shipping[0]['delivery_add']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Quantity</th>
                                <td width='50%'>".$row_checkout_success['pqun']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Size</th>
                                <td width='50%'>".$row_checkout_success['size']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Colour</th>
                                <td width='50%'>".$row_checkout_success['colour']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Total Amount</th>
                                <td width='50%'>".$row_checkout_success['total']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Booking Date</th>
                                <td width='50%'>".$row_checkout_success['date']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Status</th>
                                <td width='50%'>".$row_checkout_success['status']."</td>
                            </tr>
                            <tr>
                                <th width='50%' style='background:#eee;'>Product Image</th>
                                <td width='50%'><img src='https://gaineronline.com/uploads/product/".$fetch_product[0]['primary_image']."' width='250' height='250'></td>
                            </tr>
                            
                            
                        </table>

    </div>

    <div class='mailFoot' style='border-top:1px solid #ccc; margin-top:10px;'>

        <div class='social' align='center'>

            <a href=''><img src='https://gaineronline.com/images/fb.png'></a>

            <a href=''><img src='https://gaineronline.com/images/tw.png'></a>

            <a href=''><img src='https://gaineronline.com/images/link.png'></a>

        </div>

        <p style='font-size:12px; margin:0;'>3rd Floor, 15A, J.L.Nehru Road, Shop No.508, Kolkata, West Bengal 700013</p>

    </div>

</div>

</body>

</html>";



 $content;
 $config = Array(        

                    'protocol' => 'sendmail',

                    'smtp_host' => 'your domain SMTP host',

                    'smtp_port' => 25,

                    'smtp_user' => 'SMTP Username',

                    'smtp_pass' => 'SMTP Password',

                    'smtp_timeout' => '4',

                    'mailtype'  => 'html', 

                    'charset'   => 'iso-8859-1'

                );

                $this->load->library('email', $config);
                if($fetch_product[0]['seller_id']=='0')
                {
                $send_email=array('zakianwar508@gmail.com','gaineronline1@gmail.com','robiatur.rayee@zeewebvalley.com');
                }
                else
                {
                    $fetch_seller = $this->db->select('*')->where('id', $fetch_product[0]['seller_id'])->get('sellers')->result_array();
                    $send_email=array($fetch_seller[0]['s_email'],'gaineronline1@gmail.com');
                }

                $this->email->set_newline("\r\n");

                foreach ($send_email as $key => $sending_email) {
                
                $this->email->from('info','gaineronline');

                $subject=$row_checkout_success['pname'].'booking Success';

                $this->email->to($sending_email);
                //$this->email->to('robiatur.rayee@zeewebvalley.com');

                $this->email->subject($subject); // replace it with relevant subject 

                $this->email->message($content);   

                $responds=$this->email->send();
                $this->email->clear();

                }


    

}
$del_checkout= "delete from `chechout` where `c_id`='".$this->session->userdata('customer')."'";
$this->db->query($del_checkout);

        redirect(base_url('order/thankyou/'));
}
else
{
redirect(base_url('order/failed/'));
}
    }
    public function thankyou()
    {
        $data['content'] = 'thankyou';
        $this->load->view('layout_home', $data);
    }
public function failed()
    {
        $data['content'] = 'failed';
        $this->load->view('layout_home', $data);
    }

	public function payment($mode=''){

        $data['content'] = 'Product/Payment';

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

    }



    public function order_history(){

        $data['content'] = 'order_details';

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

    }
    public function buy_now_checkout(){

        // if($this->session->userdata('customer')){
        
         
        $data['content'] = 'buy_now_checkout';
        $this->load->view('layout_home', $data);
        // }
        // else{
        //     redirect(base_url());
        // }
    }
    public function buy_now_order(){
        // print_r($this->session->userdata('prd_id')); die;

 ///////////////////////Shipping data Add /////////////////////////////////////
        
         

        date_default_timezone_set('Asia/Kolkata');
        $date = date('d-m-Y h:i:s a', time());
        $input_data = $this->input->post();
        $input_data = $this->security->xss_clean($input_data);
        $pindetails = $this->db->where('pin', $input_data['pin'])->get('active_pin')->result_array();
        if (empty($pindetails)) {
            $message=urlencode('Service not available to this Pin');
          redirect(base_url("order/buy_now_checkout/?dna=".$message)); 
        }
        
        $insert_data['c_id'] = $this->session->userdata('customer');
        $insert_data['name'] = $input_data['name'];
        $insert_data['email'] = $input_data['email'];
        $insert_data['mobile'] = $input_data['mobile'];
        $insert_data['delivery_add'] = $input_data['address'];
        $insert_data['country'] = 'India';
        $insert_data['state'] = $input_data['state'];
        $insert_data['city'] = $input_data['city'];
        $insert_data['pin'] = $input_data['pin'];
        $insert_data['lmark'] = $input_data['landmark'];
        $insert_data['time'] = $date;
        $this->db->insert('shipping',$insert_data);        
        $shipping_id = $this->db->insert_id();
        $order_number='TOP10O00'.date('ymd').$shipping_id;
        $shipping_upd = "UPDATE `shipping` SET `order_number` = '".$order_number."' WHERE `id` = '".$shipping_id."'";
        $this->db->query($shipping_upd);
        $user_upd = "UPDATE `customer` SET `state` = '".$input_data['state']."',`city` = '".$input_data['city']."', `address` = '".$input_data['address']."',`pin` = '".$input_data['pin']."',`landmark` = '".$input_data['landmark']."' WHERE `c_id` = '".$this->session->userdata('customer')."'";
        $this->db->query($user_upd);

        

/////////////////////////////// Order Booking //////////////////////////////////////

        if($this->session->userdata('customer')){
            $input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);
            $mode=$input_data['payment'];
            $sql = "UPDATE `shipping` SET `mode` = '".$mode."' WHERE `id` = '".$shipping_id."'";
            $this->db->query($sql);
            
                $seller_id=0;
           
            $delivery_date = date('Y-m-d',strtotime('+7 day',strtotime($date)));
            $insert_data_order['seller_id'] = $seller_id;
            $insert_data_order['shipping_id'] = $shipping_id;
            $insert_data_order['date'] = $date;
            $insert_data_order['delevery_date'] =  $delivery_date;
            $insert_data_order['status'] = 'Pending';
            $this->db->insert('order_history',$insert_data_order);
            $last_id = $this->db->insert_id();
            $last_ivn=$last_id;
            $odate=date("dmy");
            $invoice_no="TOP10".$odate.$last_ivn;            
            $row_product = $this->db->select('*')->where('prd_id', $this->session->userdata('buynow_product_id'))->get('product')->result_array();
            //$pindetails = $this->db->where('pin', $input_data['pin'])->get('active_pin')->result_array();
            $total=$this->session->userdata('buynow_quantity')*$row_product[0]['p_sell_price'];
            $total=$total+$row_product['0']['shiping_chrg'];
            $colour=$this->session->userdata('colour');
            $size=$this->session->userdata('size'); 
            $product_name=$row_product[0]['p_title'];
            $all_product=$product_name;
            // $order_upd_2 = "UPDATE `order_history` SET `invoice_no` = '".$invoice_no."',`prd_id` = '".$this->session->userdata('buynow_product_id')."',`pqun` = '".$this->session->userdata('buynow_quantity')."', `colour` = '".$colour."',`size` = '".$size."',`total` = '".$total."' WHERE `order_id` = '".$last_id."'";


                
                
                
                $order_upd_2 = "UPDATE `order_history` SET `seller_id` = '".$row_product[0]['seller_id']."',`invoice_no` = '".$invoice_no."',`prd_id` = '".$this->session->userdata('buynow_product_id')."',`pqun` = '".$this->session->userdata('buynow_quantity')."', `colour` = '".$colour."',`size` = '".$size."',`sell_price` = '".$row_product[0]['p_sell_price']."',`mrp` = '".$row_product[0]['p_mrp']."',`pname` = '".$row_product[0]['p_title']."',`total` = '".$total."' WHERE `order_id` = '".$last_id."'";
             $this->db->query($order_upd_2);
                
            if($mode=='Online'){
                $prod_name ='';
                $price = 0;
                $order_id = '';
                 $resulti = $this->db->select('*')->where('shipping_id', $shipping_id)->get('order_history')->result_array();
                 foreach ($resulti as $key => $res_val) {
                    $prod_name = substr($res_val['pname'], 0,30);
                    $price = $price + $res_val['total'];
                 }
                 $fetch_cus = $this->db->select('*')->where('id', $resulti[0]['shipping_id'])->get('shipping')->result_array();
                $name = $fetch_cus[0]['name'];
                $phone = $fetch_cus[0]['mobile'];
                $email = $fetch_cus[0]['email'];
                //include APPPATH.'instamojo/src/Instamojo.php';
                $api = new Instamojo\Instamojo('cad88114fc20c5e28c778cc73e28227c', '062c7590831a212e7c06e14f5fbf5f95','https://www.instamojo.com/api/1.1/');
                try {
                    $response = $api->paymentRequestCreate(array(
                        "purpose" => $all_product,
                        "amount" => $price,
                        "buyer_name" => $name,
                        "phone" => $phone,
                        "send_email" => true,
                        "send_sms" => true,
                        "email" => $email,
                        'allow_repeated_payments' => false,
                        "redirect_url" => "https://gaineronline.com/order/thanks/?menu=".$shipping_id,
                        "webhook" => "https://gaineronline.com/instamojo/webhook.php"
                        ));
                    //print_r($response);
                    $pay_ulr = $response['longurl'];
                    //Redirect($response['longurl'],302); //Go to Payment page
                    header("Location: $pay_ulr");
                    exit();
                }
                catch (Exception $e) {
                    print('Error: ' . $e->getMessage());
                }     
            }
            else{


                $prod_ttl='THANK-YOU-For-Shopping-With-Us';
                redirect(base_url("order/thanks/?".$prod_ttl."&menu=".$shipping_id."&payment_status=Credit"));
            }
        }
        else{
            redirect(base_url());
        }
    
    }



    public function order_cancel(){

        $input_data = $this->input->post();

        $input_data = $this->security->xss_clean($input_data);

        $current_date = date("d M Y");

        $orderval=$this->db->select('*')->where('order_id', $input_data['order_id'])->get('order_history')->result_array();

        $id=$orderval['0']['prd_id'];
        $order_quantity=$orderval['0']['pqun'];

        $upd_prd= "update `product` set `p_quantity`=`p_quantity`+$order_quantity where `prd_id`='".$id."'";

        $this->db->query($upd_prd);

        $upd="UPDATE `inventory` SET `available_stock` = `available_stock`+$order_quantity WHERE `size` = '".$orderval['0']['size']."' and `prd_id`='".$id."' ";
        $query = $this->db->query($upd);


         $insert="insert into `order_cancel` (`can_id`,`order_id`,`reason`,`date`) values(NULL,'".$input_data['order_id']."','".$input_data['message']."','".$current_date."')";

         $this->db->query($insert);



         $upd="update `order_history` set `status`='Canceled' where `order_id`='".$input_data['order_id']."' ";

         $this->db->query($upd);  



$content="<!DOCTYPE html>

<html lang='en'>

  <head>

    <meta charset='utf-8'>

    <meta http-equiv='X-UA-Compatible' content='IE=edge'>

    <meta name='viewport' content='width=device-width, initial-scale=1'>

    <title>Mailer</title>



<style>

@import url('https://fonts.googleapis.com/css?family=Open+Sans');

body{

font-family: 'Open Sans', sans-serif;

}

.mailerMain{

width:540px;

background:#fbfbfb;

margin:0 auto;

padding:15px 30px;

}

.logoimgHeight{

height:75px;

}

.cartbag{

margin-top:20px;

height:80px;

}

.btn-black {

    background: #7e7e7e;

    color: #fff;

    padding: 4px 20px;

    text-decoration:none;

    font-size:13px;

}

.social img{

        height:30px;

        margin:10px 5px;

        }

@media screen and (max-width: 768px){

.mailerMain{

width:auto;

padding:15px;

}

}

</style>

</head>

<body>

<div class='mailerMain' align='center'>

    <div class='mailHead'>

        <img src='https://gaineronline.com/images/logo.png' class='logoimgHeight'>

    </div>

    <div class='mailBody'>

        <img src='https://gaineronline.com/images/cancel.png' class='cartbag'>

        <p style='font-weight:bold; color:#000;'>Your order has been successfully canceled</p>

        <p style='font-size:13px; line-height: 22px;'>We hope you enjoy your shoping at <a href='#'>esteovest.com</a> . If you have any question or trouble loggin please contact a site administrator</p>

    </div>

    <div class='mailFoot' style='border-top:1px solid #ccc; margin-top:10px;'>

        <div class='social' align='center'>

            <a href=''><img src='https://gaineronline.com/images/fb.png'></a>

            <a href=''><img src='https://gaineronline.com/images/tw.png'></a>

            <a href=''><img src='https://gaineronline.com/images/link.png'></a>

        </div>

        <p style='font-size:12px; margin:0;'>86B/2, Topsia Road, Gajraj Chambers, 2nd Floor, Topsia, Kolkata, West Bengal 700046</p>

    </div>

</div>

</body>

</html>";



echo $content;

                $config = Array(        

                    'protocol' => 'sendmail',

                    'smtp_host' => 'your domain SMTP host',

                    'smtp_port' => 25,

                    'smtp_user' => 'SMTP Username',

                    'smtp_pass' => 'SMTP Password',

                    'smtp_timeout' => '4',

                    'mailtype'  => 'html', 

                    'charset'   => 'iso-8859-1'

                );

                $this->load->library('email', $config);

                $this->email->set_newline("\r\n");



                $this->email->from('info','gaineronline');

                $subject='Order Cancelled';

                $this->email->to($input_data['email']);

                $this->email->subject($subject); // replace it with relevant subject 

                $this->email->message($content);   

                $responds=$this->email->send();

    }


    public function product_return(){

        $input_data = $this->input->post();

        $input_data = $this->security->xss_clean($input_data);

        $current_date = date("d M Y");

        $orderval=$this->db->select('*')->where('order_id', $input_data['order_id'])->get('order_history')->result_array();

        $id=$orderval['0']['prd_id'];
        $order_quantity=$orderval['0']['pqun'];

        $upd_prd= "update `product` set `p_quantity`=`p_quantity`+$order_quantity where `prd_id`='".$id."'";

        $this->db->query($upd_prd);

        $upd="UPDATE `inventory` SET `available_stock` = `available_stock`+$order_quantity WHERE `size` = '".$orderval['0']['size']."' and `prd_id`='".$id."' ";
        $query = $this->db->query($upd);


         $insert="insert into `order_cancel` (`can_id`,`order_id`,`reason`,`date`) values(NULL,'".$input_data['order_id']."','".$input_data['message']."','".$current_date."')";

         $this->db->query($insert);



         echo $upd="update `order_history` set `status`='Return' where `order_id`='".$input_data['order_id']."' ";

         $this->db->query($upd);  



$content="<!DOCTYPE html>

<html lang='en'>

  <head>

    <meta charset='utf-8'>

    <meta http-equiv='X-UA-Compatible' content='IE=edge'>

    <meta name='viewport' content='width=device-width, initial-scale=1'>

    <title>Mailer</title>



<style>

@import url('https://fonts.googleapis.com/css?family=Open+Sans');

body{

font-family: 'Open Sans', sans-serif;

}

.mailerMain{

width:540px;

background:#fbfbfb;

margin:0 auto;

padding:15px 30px;

}

.logoimgHeight{

height:75px;

}

.cartbag{

margin-top:20px;

height:80px;

}

.btn-black {

    background: #7e7e7e;

    color: #fff;

    padding: 4px 20px;

    text-decoration:none;

    font-size:13px;

}

.social img{

        height:30px;

        margin:10px 5px;

        }

@media screen and (max-width: 768px){

.mailerMain{

width:auto;

padding:15px;

}

}

</style>

</head>

<body>

<div class='mailerMain' align='center'>

    <div class='mailHead'>

        <img src='https://gaineronline.com/images/logo.png' class='logoimgHeight'>

    </div>

    <div class='mailBody'>

        <img src='https://gaineronline.com/images/cancel.png' class='cartbag'>

        <p style='font-weight:bold; color:#000;'>You have requested for product return.</p>

        <p style='font-size:13px; line-height: 22px;'>We hope you enjoy your shoping at <a href='#'>esteovest.com</a> . If you have any question or trouble loggin please contact a site administrator</p>

    </div>

    <div class='mailFoot' style='border-top:1px solid #ccc; margin-top:10px;'>

        <div class='social' align='center'>

            <a href=''><img src='https://gaineronline.com/images/fb.png'></a>

            <a href=''><img src='https://gaineronline.com/images/tw.png'></a>

            <a href=''><img src='https://gaineronline.com/images/link.png'></a>

        </div>

        <p style='font-size:12px; margin:0;'>86B/2, Topsia Road, Gajraj Chambers, 2nd Floor, Topsia, Kolkata, West Bengal 700046</p>

    </div>

</div>

</body>

</html>";



//echo $content;

                $config = Array(        

                    'protocol' => 'sendmail',

                    'smtp_host' => 'your domain SMTP host',

                    'smtp_port' => 25,

                    'smtp_user' => 'SMTP Username',

                    'smtp_pass' => 'SMTP Password',

                    'smtp_timeout' => '4',

                    'mailtype'  => 'html', 

                    'charset'   => 'iso-8859-1'

                );

                $this->load->library('email', $config);

                $this->email->set_newline("\r\n");



                $this->email->from('info','gaineronline');

                $subject='Return Request';

                $this->email->to($input_data['email']);

                $this->email->subject($subject); // replace it with relevant subject 

                $this->email->message($content);   

                $responds=$this->email->send();

    }



    // public function order_confirm_old(){

    //     date_default_timezone_set('Asia/Kolkata');

    //     $date = date('d-m-Y h:i:s a', time());

    //     if($this->session->userdata('customer')){

    //         $input_data = $this->input->post();

    //         $input_data = $this->security->xss_clean($input_data);



    //         $shipping_id=base64_decode($input_data['mode']);

    //         $mode=$input_data['payment'];



    //         $sql = "UPDATE `shipping` SET `mode` = '".$mode."' WHERE `id` = '".$shipping_id."'";

    //         $this->db->query($sql);



    //         $insert_data['shipping_id'] = $shipping_id;

    //         $insert_data['date'] = $date;

    //         $insert_data['status'] = 'Pending';

    //         $this->db->insert('order_history',$insert_data);

    //         $last_id = $this->db->insert_id();



    //         $last_ivn=$last_id;

    //         $odate=date("dmy");

    //         $invoice_no="OWS00".$odate.$last_ivn;

    //         //$p_id=implode(',', $this->session->userdata('prd_id'));

    //         //$p_quantity=implode(',', $this->session->userdata('quantity'));



    //         $order_upd = "UPDATE `order_history` SET `invoice_no` = '".$invoice_no."',`prd_id` = '".base64_decode($input_data['mode_prd'])."',`pqun` = '".base64_decode($input_data['mode_quantity'])."' WHERE `order_id` = '".$last_id."'";

    //         $this->db->query($order_upd);



    //         $fetch_chechout = $this->db->select('*')->where('c_id', $this->session->userdata('customer'))->get('chechout')->result_array();

    //         $total=0;

    //         $product_name='';

    //         $colour='';

    //         $size='';

    //         $sl=0;



    //         foreach ($fetch_chechout as $row_checkout) {

    //             $row_product = $this->db->select('*')->where('prd_id', $row_checkout['prd_id'])->get('product')->result_array();



    //             $total1=$row_checkout['quantity']*$row_product[0]['p_sell_price'];

    //             $total=$total+$total1;

                

    //             if ($sl==0) {

    //             $colour=$row_checkout['colour'];

    //             $size=$row_checkout['size'];

    //             $product_name=$row_product[0]['p_title'];

    //             }

    //             else{

    //             $colour=$colour.','.$row_checkout['colour'];

    //             $size=$size.','.$row_checkout['size'];

    //             $product_name=$product_name.','.$row_product[0]['p_title'];

    //             }



    //             $order_upd_2 = "UPDATE `order_history` SET `colour` = '".$colour."',`size` = '".$size."',`pname` = '".$product_name."',`total` = '".$total."' WHERE `order_id` = '".$last_id."'";

    //              $this->db->query($order_upd_2);



    //              $sl++;

    //         }



    //         if($mode=='Online'){

    //              $resulti = $this->db->select('*')->where('invoice_no', $invoice_no)->get('order_history')->result_array();

    //              $fetch_cus = $this->db->select('*')->where('id', $resulti[0]['shipping_id'])->get('shipping')->result_array();

    //             $prod_name = substr($resulti[0]['pname'], 0,30);

    //             $price = $resulti[0]['total'];

    //             $name = $fetch_cus[0]['name'];

    //             $phone = $fetch_cus[0]['mobile'];

    //             $email = $fetch_cus[0]['email'];

    //             //include APPPATH.'instamojo/src/Instamojo.php';

    //             $api = new Instamojo\Instamojo('079f87848ebe116ba8d11aa43439143d', '28f02892efac951b69a390d63c6d527b','https://www.instamojo.com/api/1.1/');

    //             try {

    //                 $response = $api->paymentRequestCreate(array(

    //                     "purpose" => $prod_name,

    //                     "amount" => $price,

    //                     "buyer_name" => $name,

    //                     "phone" => $phone,

    //                     "send_email" => true,

    //                     "send_sms" => true,

    //                     "email" => $email,

    //                     'allow_repeated_payments' => false,

    //                     "redirect_url" => "https://gaineronline.com/bill-mail.php?email='".$email."' ",

    //                     "webhook" => "https://gaineronline.com/instamojo/webhook.php"

    //                     ));

    //                 //print_r($response);

    //                 $pay_ulr = $response['longurl'];

    //                 //Redirect($response['longurl'],302); //Go to Payment page

    //                 header("Location: $pay_ulr");

    //                 exit();

    //             }

    //             catch (Exception $e) {

    //                 print('Error: ' . $e->getMessage());

    //             }     

    //         }

    //         else{

    //             $fetch_chechout_success = $this->db->select('*')->where('c_id', $this->session->userdata('customer'))->get('chechout')->result_array();

    //             foreach ($fetch_chechout_success as $row_checkout_success) {

    //              $fetch_product = $this->db->select('*')->where('prd_id', $row_checkout_success['prd_id'])->get('product')->result_array();

    //             $id=$fetch_product[0]['prd_id'];

    //             $quantity=$fetch_product[0]['p_quantity'];

    //             $order_quantity=$row_checkout_success['quantity'];

    //             $new_quantity=$quantity-$order_quantity;

    //             $upd_prd= "update `product` set `p_quantity`='".$new_quantity."' where `prd_id`='".$id."'";

    //             $this->db->query($upd_prd);

    //             }

    //             $del_checkout= "delete from `chechout` where `c_id`='".$this->session->userdata('customer')."'";

    //             $this->db->query($del_checkout);



    //             $data['content'] = 'Product/thanks';

    //             $this->load->view('layout_home', $data);

    //         }

    //     }

    //     else{

    //         redirect(base_url());

    //     }

    // }



    public function order_confirm(){
        date_default_timezone_set('Asia/Kolkata');
        $date = date('d-m-Y h:i:s a', time());
        if($this->session->userdata('customer')){
    		$input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);
            $shipping_id=base64_decode($input_data['mode']);
            $mode=$input_data['payment'];
            $sql = "UPDATE `shipping` SET `mode` = '".$mode."' WHERE `id` = '".$shipping_id."'";
            $this->db->query($sql);
            //$p_id=implode(',', $this->session->userdata('prd_id'));
            //$p_quantity=implode(',', $this->session->userdata('quantity'));
            $product_id=explode(",", base64_decode($input_data['mode_prd']));
            $all_product='';
            foreach ($product_id as $key_product) {    
            $insert_data['shipping_id'] = $shipping_id;
            $insert_data['date'] = $date;
            $insert_data['status'] = 'Pending';
            $this->db->insert('order_history',$insert_data);
            $last_id = $this->db->insert_id();
            $last_ivn=$last_id;
            $odate=date("dmy");
            $invoice_no="OWS00".$odate.$last_ivn;
            $row_checkout = $this->db->select('*')->where('c_id', $this->session->userdata('customer'))->where('prd_id', $key_product)->get('chechout')->result_array();
                $row_product = $this->db->select('*')->where('prd_id', $row_checkout[0]['prd_id'])->get('product')->result_array();
                $total=$row_checkout[0]['quantity']*$row_product[0]['p_sell_price'];
                $colour=$row_checkout[0]['colour'];
                $size=$row_checkout[0]['size']; 
                $product_name=$row_product[0]['p_title'];
                $all_product=$all_product.' '.$product_name;
                $order_upd_2 = "UPDATE `order_history` SET `invoice_no` = '".$invoice_no."',`prd_id` = '".$key_product."',`pqun` = '".$row_checkout[0]['quantity']."', `colour` = '".$colour."',`size` = '".$size."',`pname` = '".$product_name."',`total` = '".$total."' WHERE `order_id` = '".$last_id."'";
                 $this->db->query($order_upd_2);
                }
            if($mode=='Online'){
                $prod_name ='';
                $price = 0;
                $order_id = '';
                 $resulti = $this->db->select('*')->where('shipping_id', $shipping_id)->get('order_history')->result_array();

                 foreach ($resulti as $key => $res_val) {
                    $prod_name = substr($res_val['pname'], 0,30);
                    $price = $price + $res_val['total'];
                 }
                 $fetch_cus = $this->db->select('*')->where('id', $resulti[0]['shipping_id'])->get('shipping')->result_array();
                $name = $fetch_cus[0]['name'];
                $phone = $fetch_cus[0]['mobile'];
                $email = $fetch_cus[0]['email'];
                //include APPPATH.'instamojo/src/Instamojo.php';
                $api = new Instamojo\Instamojo('cad88114fc20c5e28c778cc73e28227c', '062c7590831a212e7c06e14f5fbf5f95','https://www.instamojo.com/api/1.1/');
                try {
                    $response = $api->paymentRequestCreate(array(
                        "purpose" => $all_product,
                        "amount" => $price,
                        "buyer_name" => $name,
                        "phone" => $phone,
                        "send_email" => true,
                        "send_sms" => true,
                        "email" => $email,
                        'allow_repeated_payments' => false,
                        "redirect_url" => "https://gaineronline.com/Product/thanks/?menu=".$shipping_id,
                        "webhook" => "https://gaineronline.com/instamojo/webhook.php"
                        ));
                    //print_r($response);
                    $pay_ulr = $response['longurl'];
                    //Redirect($response['longurl'],302); //Go to Payment page
                    header("Location: $pay_ulr");
                    exit();
                }
                catch (Exception $e) {
                    print('Error: ' . $e->getMessage());
                }     
            }
            else{
                redirect(base_url("Product/thanks/?menu=".$shipping_id.""));
            }
	    }
        else{
            redirect(base_url());
        }
    }

}

