<?php

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

class MY_Front_Controller extends MY_Controller

{

    function __construct()
    {
        parent::__construct();
        $this->load->model('front_model','front'); 
        $this->load->model("user_login/user_login_model","login");
        $this->load->helper('front');
        $this->is_user_logged_in = $this->session->userdata('is_user_logged_in');
        $this->profileid = $this->session->userdata('profileid');
        $this->ud = $this->common->getsData('user',array('profileid'=>$this->profileid));
        $this->level = 0; //($this->ud)?$this->ud['package']:0;
        $this->dprice = 0;
        /*if($this->dollar=='USD'){ 
            $rate = $this->common->getsData('dollarprice',array('id'=>1));
            $this->dprice = $rate['rate'];
        }*/
        $this->load->library('paypal_lib');
    }

    public function applyCoupon()
    {
        // $query = 'SELECT coupon_amount,cart_amount,coupon_type FROM coupon WHERE coupon_code = "'.$_POST['coupon_code'].'" AND (profileid = "'.$this->profileid.'" OR email = "'.$this->session->userdata("email").'") AND coupon_quantity > 0 AND UNIX_TIMESTAMP() < UNIX_TIMESTAMP(coupon_expiry_date)';
        $query = 'SELECT coupon_code,productid,coupon_amount,cart_amount,coupon_type FROM coupon WHERE coupon_code = "'.$_POST['coupon_code'].'" AND coupon_quantity > 0 AND UNIX_TIMESTAMP() < UNIX_TIMESTAMP(coupon_expiry_date)';

        $coupon_amount = $this->db->query($query)->result_array();
        // echo $this->db->last_query();die;
        if ($coupon_amount) {
            if($coupon_amount[0]['productid']!=''){
                $pids = explode(',', $coupon_amount[0]['productid']);
                $coupon_amount[0]['productid'] = $pids[0];
                // echo $coupon_amount[0]['productid']; die;
                $pcoupon = $coupon_amount[0];
                foreach ($this->cart->contents() as $key => $value){
                    if($value['id']==$coupon_amount[0]['productid']){
                        $product = $this->common->getsData('products',array('productid'=>$pcoupon['productid']));
                        $product_coupon[$pcoupon['productid']] = array(
                            'coupon_code'=>$pcoupon['coupon_code'],
                            'coupon_amount'=>$pcoupon['coupon_amount'],
                            'coupon_type'=>$pcoupon['coupon_type'],
                        ); 
                        $this->session->set_userdata('product_coupon',$product_coupon);
                        $this->session->set_flashdata('message','Coupon code applied!');
                    }
                }
                redirect($_SERVER['HTTP_REFERER']);
            }else{
                $cart_amount = $this->cart->total();
                if($coupon_amount[0]['cart_amount']!="" && $coupon_amount[0]['cart_amount']>$cart_amount) {
                    $this->session->set_flashdata('emessage','Coupon entered cannot be used for this order. Please check your coupon terms and try again.');
                    redirect($_SERVER['HTTP_REFERER']);
                }
                // echo "<pre>";
                // print_r($coupon_amount[0]['coupon_amount']);
                // print_r($_POST['coupon_code']); die;
                if($coupon_amount[0]['coupon_type']==0 && $coupon_amount[0]['cart_amount']<=$coupon_amount[0]['coupon_amount']){
                    $this->session->set_flashdata('emessage','The code you entered is invalid');
                    redirect($_SERVER['HTTP_REFERER']);
                }
                if($coupon_amount[0]['cart_amount']<=$cart_amount){
                    $this->session->set_userdata('user_coupon',$coupon_amount[0]['coupon_amount']);
                    $this->session->set_userdata('user_coupon_code',$_POST['coupon_code']);
                    $this->session->set_userdata('user_coupon_type',$coupon_amount[0]['coupon_type']);
                    $this->session->set_flashdata('message','Coupon code applied!');
                }else{
                    $this->session->set_flashdata('emessage','Coupon entered cannot be used for this order. Please check your coupon terms and try again.');
                }
            }
        }else{
            /*$newsletter = $this->common->getsData('newsletter',array('email'=>$this->session->userdata("email")));
            if($newsletter){
                $query = 'SELECT coupon_amount,cart_amount,coupon_type FROM coupon WHERE coupon_code = "'.$_POST['coupon_code'].'" AND profileid = "admin123423" AND coupon_quantity > 0 AND UNIX_TIMESTAMP() < UNIX_TIMESTAMP(coupon_expiry_date)';
                $coupon_amount = $this->db->query($query)->result_array();
                if ($coupon_amount) {
                    $cart_amount = $this->cart->total();
                    if($coupon_amount[0]['cart_amount']!="" && $coupon_amount[0]['cart_amount']>$cart_amount) {
                        $this->session->set_flashdata('emessage','Coupon entered cannot be used for this order. Please check your coupon terms and try again.');
                        redirect($_SERVER['HTTP_REFERER']);
                    }
                    if($coupon_amount[0]['coupon_type']==0 && $coupon_amount[0]['cart_amount']<=$coupon_amount[0]['coupon_amount']){
                        $this->session->set_flashdata('emessage','The code you entered is invalid');
                        redirect($_SERVER['HTTP_REFERER']);
                    }
                    if($coupon_amount[0]['cart_amount']<=$cart_amount){
                        $this->session->set_userdata('user_coupon',$coupon_amount[0]['coupon_amount']);
                        $this->session->set_userdata('user_coupon_code',$_POST['coupon_code']);
                        $this->session->set_userdata('user_coupon_type',$coupon_amount[0]['coupon_type']);
                        $this->session->set_flashdata('message','Coupon code applied!');
                    }else{
                        $this->session->set_flashdata('emessage','Coupon entered cannot be used for this order. Please check your coupon terms and try again.');
                    }
                }else{
                    $this->session->set_flashdata('emessage','The code you entered is invalid');
                }
            }else{
                $this->session->set_flashdata('emessage','The code you entered is invalid');
            }*/
                $this->session->set_flashdata('emessage','The code you entered is invalid');
        } 
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function destroyCoupon($value='')
    {
        $this->session->unset_userdata('user_coupon');
        $this->session->unset_userdata('user_coupon_code');
    }


    public function doLogin()
    {
        if((isset($_POST['email']) && $_POST['email']!="") && (isset($_POST['password']) && $_POST['password']!=""))
        {
            if(isset($_POST['user_login_type']) && $_POST['user_login_type']=="register_user")
            {
                $field = "";
                if(is_numeric($_POST['email'])){
                    $field = "mobile_no";
                }else{
                    $field = "email";
                }
                if($data = $this->common->getsData('user',array($field=>$_POST['email'],'password'=>md5($_POST['password']))))
                {
                    if(($data[$field]!=$_POST['email']) || ($data['password']!=md5($_POST['password'])))
                    {
                        $this->session->set_flashdata('emessage',$this->lang->line('error_user_login'));
                        redirect(base_url("checkout"));
                    }else{
                        $this->loginRedirect($data,$_POST['user_login_type']);
                    }
                }else{
                    $this->session->set_flashdata('emessage',"Email or password is wrong!");
                    redirect(base_url("checkout"));
                }
            }
        }else
            if(isset($_POST['user_login_type']) && $_POST['user_login_type']=="guest_user")
            {
                if($this->common->getData("user",array("email"=>$_POST['email'],'user_type'=>'register_user')))
                {
                    $this->session->set_flashdata("emessage",'You have already registered an account. Please login to proceed.');
                    $location=base_url("checkout");
                }/*else if($this->common->getData("user",array("mobile_no"=>$_POST['mobile_no'],'user_type'=>'register_user'))){
                    $this->session->set_flashdata("emessage",'You have already registered an account. Please login to proceed.');
                    $location=base_url("checkout");
                }*/ /* else if($this->common->getData("user",array("mobile_no"=>$_POST['mobile_no'],'user_type'=>'guest_user'))){
                    if()
                    $prid = $this->common->getsData("user",array("mobile_no"=>$_POST['mobile_no'],'user_type'=>'guest_user'));
                    $_POST['profileid'] = $prid['profileid'];
                    $_POST['email'] = $prid['email'];
                    $location = $this->loginRedirect($_POST);
                } */ else if($this->common->getData("user",array("email"=>$_POST['email'],'user_type'=>'guest_user'))){
                    if(isset($_POST['user_action']) && $_POST['user_action']=='update'){
                        $updatedata = $this->common->getField('user',$_POST);
                        $this->common->updateData('user',$updatedata,array("email"=>$_POST['email'],'user_type'=>'guest_user'));
                    }
                    $prid = $this->common->getsData("user",array("email"=>$_POST['email'],'user_type'=>'guest_user'));
                    $_POST['profileid'] = $prid['profileid'];
                    $_POST['email'] = $prid['email'];
                    $location = $this->loginRedirect($_POST,$_POST['user_login_type']);
                }else{
                    $_POST['profileid'] = strtotime(date("Y-m-d H:i:s"));
                    $_POST['reg_date'] = date("Y-m-d H:i:s");
                    $_POST['user_type'] = 'guest_user';
                    $_POST['verify'] = 1;
                    $res = $this->login->registerUser($_POST);
                    if($res){
                        /*$yes = $this->common->getsData('newsletter',array('email'=>$_POST['email']));
                        if($yes){
                            
                        }else{
                            $ip = $this->input->ip_address();
                            $res = $this->common->insertData('newsletter',array('email'=>$_POST['email'],'name'=>$_POST['name'],'ip_address'=>$ip,'date'=>date('Y-m-d H:i:s')));
                        }*/

                        $location = $this->loginRedirect($_POST,$_POST['user_login_type']);
                    }else{
                        $location = base_url("checkout");
                    }
                }
                redirect($location);
            }else{
                redirect(base_url("checkout"));
            }
    }

    public function loginRedirect($data='',$user_login_type='')
    {
        $sdata = array(
            'email' => $data['email'],
            'profileid' =>  $data['profileid'],
            'is_user_logged_in' => true,
            'user_login_type' => $user_login_type
        );
        $this->session->set_userdata($sdata);
        redirect(base_url("checkout"));
    }

    public function sociallogin()
    {       
        $data['name'] = strtolower($this->input->post('fname')).' '.strtolower($this->input->post('lname'));
        $data['email'] = $this->input->post('email');
        $result = $this->common->getsData('user',array('email'=>$data['email']));
        if(empty($result)){
            $data['profileid'] = strtotime(date("Y-m-d H:i:s"));
            $data['reg_date'] = date("Y-m-d H:i:s");
            $data['user_type'] = 'register_user';
            $this->common->insertData('user',$data);
        }else{
            $data['profileid'] = $result['profileid'];
        }

        $location = $this->loginRedirect($data,'register_user');       
        redirect($location);
    }

    public function checkPincodeAvailabilityOnOrder($pincode='',$pmethod=''){
        $status = 0;
        /*if($this->common->getsData("pincode",array("pincode"=>$pincode,"cod"=>'Y'))){
            $status = 1;
        }else{
            if($pmethod=='COD'){
                $this->session->set_flashdata('emessage',"Only Online Payment Method Available for this Pincode (".$pincode.").");
                redirect(base_url('checkout'));
            }else{
                $status = 1;
            } 
        }
        return $status; */
        return 1;
    }


    public function placeOrder()
    {
       //echo "hello";die;
        // print_r($_POST); die;
        if(isset($_POST['sname']) && $_POST['sname']==''){
            $_POST['sname'] = $_POST['bname'];
        }
        if(isset($_POST['semail']) && $_POST['semail']==''){
            $_POST['semail'] = $_POST['bemail'];
        }
        if(isset($_POST['smobile_no']) && ($_POST['smobile_no']=='')){
            $_POST['smobile_no'] = $_POST['bmobile_no'];
        }
        if(isset($_POST['saddress1']) && $_POST['saddress1']==''){
            $_POST['saddress1'] = $_POST['baddress1'];
        }
        if(isset($_POST['saddress2']) && $_POST['saddress2']==''){
            $_POST['saddress2'] = $_POST['baddress2'];
        }
        if(isset($_POST['scity']) && $_POST['scity']==''){
            $_POST['scity'] = $_POST['bcity'];
        }
        if(isset($_POST['sstate']) && $_POST['sstate']==''){
            $_POST['sstate'] = $_POST['bstate'];
        }
        if(isset($_POST['spincode']) && ($_POST['spincode']=='' || $_POST['spincode']==0)){
            // $pcheck = $this->checkPincodeAvailabilityOnOrder($_POST['bpincode'],$_POST['payment_method']);
            // if($pcheck==0){
            //     redirect(base_url('checkout'));
            // }
            $_POST['spincode'] = $_POST['bpincode'];
        }else{
            // $pcheck = $this->checkPincodeAvailabilityOnOrder($_POST['spincode'],$_POST['payment_method']);
            // if($pcheck==0){
            //     redirect(base_url('checkout'));
            // }
        }
        //print_r($this->session->userdata('profileid'));die;
        $useraddress = $this->common->getData('user_address',array('profileid'=>$this->session->userdata('profileid')));
        if(!$useraddress){
            $useraddressdata = $this->common->getField('user_address',$_POST);
            $useraddressdata['profileid'] = $this->session->userdata('profileid');
            $useraddressdata['isDefault'] = 1;
            $this->common->insertData('user_address',$useraddressdata);
        }
        if($this->session->userdata("cart_contents")!=""){
            $this->session->set_userdata('userdata',$_POST);
            // echo "<pre>";
            // print_r($_POST);
            if(isset($_POST['payment_method']) && $_POST['payment_method']=="COD"){
                $orderid = orderid_prefix.strtotime(date('Y-m-d H:i:s'));
                $this->session->set_userdata(array("orderid"=>$orderid));
                $this->paymentDone();
            }else if(isset($_POST['payment_method']) && $_POST['payment_method']=="paynow"){
                $this->goToHitPay();
            }else if(isset($_POST['payment_method']) && $_POST['payment_method']=="omise"){
                // $this->goToOmise();
                $this->session->set_flashdata('emessage',"Sorry this Payment method Unavailable for some time.");
                redirect(base_url('checkout'));
            }else{
                $this->session->set_flashdata('emessage',"Sorry this Payment method Unavailable for some time.");
                redirect(base_url('checkout'));
            }
        }else{
            redirect(base_url());
        }
        
    }

    public function goToHitPay($post='')
    {
        $orderid = orderid_prefix.strtotime(date('Y-m-d H:i:s'));
        $this->session->set_userdata(array("orderid"=>$orderid));

        $product_coupon_amount = 0;
        $cart_mapping = $this->cart->contents();
        foreach ($cart_mapping as $key => $value){
            if($this->session->userData('product_coupon')){
                $coupon_apply = $this->session->userData('product_coupon');
                if(isset($coupon_apply[$value['id']]) && $coupon_apply[$value['id']]){
                    if($coupon_apply[$value['id']]['coupon_type']==0){
                      $product_coupon_amount += $coupon_apply[$value['id']]['coupon_amount'];
                    }else{
                      $product_coupon_amount += ($value['price']*$coupon_apply[$value['id']]['coupon_amount'])/100;
                    }
                }
            }
        }

        // $cart_amount = $this->cart->total()-$this->session->userdata('cart_points');
        $cart_amount = $this->cart->total()-$product_coupon_amount;

        if($this->session->userdata("user_coupon")!=""){
            if($this->session->userdata('user_coupon_type')==0){
                $coupon_amount = $this->session->userdata('user_coupon');
            }else{
                $coupon_amount = (($cart_amount)*$this->session->userdata('user_coupon'))/100;
            }
        }else{
           $coupon_amount = 0; 
        }

        if($this->session->userdata('delivery_charge')){
            $delivery_charge = $this->session->userdata('delivery_charge');
        }else{
            $delivery_charge = 0;
        }

        if($this->session->userdata('birthday_discount')){
            $birthday_discount = $this->session->userdata('birthday_discount');
        }else{
            $birthday_discount = 0;
        }

        /*if($cart_amount >= 100) {
            $first_order = $this->db->query("select orderid from `orders` where profileid = '".$this->profileid."'")->num_rows();
            if($first_order==0) {
                $first_order = 5;
            }else{
                $first_order = 0;
            }
        }else{
            $first_order = 0; 
        }*/
        $first_order = 0;

        $t_amount = ($cart_amount-$coupon_amount-$first_order+$delivery_charge-$birthday_discount);

        $use_coins_amount = 0;
        $us = $this->session->userdata('userdata');
        $isWallet = (isset($us['isWallet']))?$us['isWallet']:0;
       
        if($isWallet==1){
            $wal = $this->common->getsData('user',array('profileid'=>$this->profileid),array('remain_point'));
            if($wal['remain_point']>1000){
                $wallet = $wal['remain_point']/200;
                if($wallet>$t_amount){
                    $use_coins_amount = $t_amount;
                }else{
                    $use_coins_amount = $wallet;
                }
            }
        }

        $total_amount = ($t_amount-$use_coins_amount);

        $user = $this->userOrderAddress();

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

        $curlpost = 'email='.$user['bemail'].'&name='.$user['bname'].'&redirect_url='.base_url('front/hitPaySuccess').'&webhook='.base_url('common/hitPayWebhook').'&amount='.$total_amount.'&currency=SGD&reference_number='.$orderid.'&send_email=true';
        // echo "<pre>";
        // print_r ($curlpost);
        // echo "</pre>";die;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"https://api.hit-pay.com/v1/payment-requests");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$curlpost);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Requested-With: XMLHttpRequest','Content-Type: application/x-www-form-urlencoded','X-BUSINESS-API-KEY: '.hitpay_apikey));
        // receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $server_output = curl_exec ($ch);
        curl_close ($ch);
        $payres = json_decode($server_output,true);
        // echo "<pre>";
        // print_r ($payres);
        // echo "</pre>"; die;
        $this->session->set_userdata('paymentid',$payres['id']);
        redirect($payres['url']);
    }

    function getRandomString($digits) { 
        $total_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
        $randomString = ''; 
            for ($i = 0; $i < $digits; $i++) { 
                $index = rand(0, strlen($total_characters) - 1); 
                $randomString .= $total_characters[$index]; 
            }
        return $randomString; 
    }

    public function hitPaySuccess()
    {
        if(isset($_GET['status']) && $_GET['status']=='failed'){
            $this->session->set_flashdata('emessage',"Sorry your payment is unsuccessful. Please try again.");
            redirect(base_url('checkout'));
        }else if(isset($_GET['status']) && $_GET['status']=='expired'){
            $this->session->set_flashdata('emessage',"Sorry your payment is unsuccessful. Please try again.");
            redirect(base_url('checkout'));
        }else if(isset($_GET['status']) && $_GET['status']=='canceled'){
            $this->session->set_flashdata('emessage',"Sorry your payment is cancelled. Please try again.");
            redirect(base_url('checkout'));
        }else if(isset($_GET['reference']) && $_GET['reference']!=''){
            if($_GET['status']=='completed'){
                $status = "Complete";
            }else{
                $status = "Pending";
            }
            $this->paymentDone($_GET['reference'],$status);
        }else{
            $this->session->set_flashdata('emessage',"Sorry your payment is unsuccessful. Please try again.");
            redirect(base_url('checkout'));
        }
    }

    public function payNowFailed() {
        $this->session->set_flashdata('emessage',"Sorry your payment is unsuccessful. Please try again.");
        redirect(base_url('checkout'));
    } 

    public function paymentDone($txnid='',$pstatus='Pending')
    {
        // echo "<pre>";
        // print_r($this->session->userdata('rozorpay_paymentid')); die;

        if($this->session->userdata("cart_contents")!="" && $this->session->userdata("orderid"))
        {
            $product_coupon_amount = 0;
            $cart_mapping = $this->cart->contents();
            foreach ($cart_mapping as $key => $value){
                if($this->session->userData('product_coupon')){
                    $coupon_apply = $this->session->userData('product_coupon');
                    if(isset($coupon_apply[$value['id']]) && $coupon_apply[$value['id']]){
                        if($coupon_apply[$value['id']]['coupon_type']==0){
                          $product_coupon_amount += $coupon_apply[$value['id']]['coupon_amount'];
                        }else{
                          $product_coupon_amount += ($value['price']*$coupon_apply[$value['id']]['coupon_amount'])/100;
                        }
                    }
                }
            }
            $orderid = $this->session->userdata('orderid');

            $sessiondata = $this->session->all_userdata();


            $order['orderid'] = $orderid;

            $order['profileid'] = $this->session->userdata("profileid");

            if($this->session->userdata("user_coupon")!=""){
                if($this->session->userdata('user_coupon_type')==0){
                    $order['coupon_amount'] = $this->session->userdata('user_coupon');
                }else{
                    $order['coupon_amount'] = (($this->cart->total()-$product_coupon_amount)*$this->session->userdata('user_coupon'))/100;
                }
                //$order['coupon_amount'] = $this->session->userdata("user_coupon");
            }else{
               $order['coupon_amount'] = 0; 
            }

            if($this->session->userdata("user_coupon_code")!=""){
                $order['coupon_code'] = $this->session->userdata("user_coupon_code");
            }else{
                $order['coupon_code'] = '';
            }

            if($this->session->userdata('delivery_charge')){
                $order['delivery_charge'] = $this->session->userdata('delivery_charge');
            }else{
                $order['delivery_charge'] = 0;
            }

            if($this->session->userdata('birthday_discount')){
                $order['birthday_discount'] = $this->session->userdata('birthday_discount');
            }else{
                $order['birthday_discount'] = 0;
            }

            if($this->session->userdata('pweight')){
                $order['pweight'] = $this->session->userdata('pweight');
            }else{
                $order['pweight'] = 0;
            }

            if($this->session->userdata('out_of_stock')){
                $order['out_of_stock'] = $this->session->userdata('out_of_stock');
            }else{
                $order['out_of_stock'] = '';
            }
            
            $order['order_time'] = date("Y-m-d H:i:s");

            $order['quantity'] = $this->cart->total_items();

            $order['shipping'] = 0;

            $order['subtotal'] = $this->cart->total()-$this->session->userdata('cart_points')-$product_coupon_amount;

            if($this->dollar=='USD' && $this->dprice!=0){
                $order['payment_currency'] = "USD";
                $order['usd_rate'] = $this->dprice;
            }else{
                $order['payment_currency'] = "INR";
                $order['usd_rate'] = 0;
            }

            $order['payment_status'] = "Pending";

            $payment_method = $this->session->userdata('userdata');

            $payment_method = $payment_method['payment_method'];
            $order['payment_id'] = '';
            $order['charge_id'] = '';
            if($payment_method=="COD"){
               $order['payment_method']=1; 
               $order['txn_id'] = '';
            }else if ($payment_method=="paynow") {
                $order['payment_method']=2;
                $order['payment_status'] = $pstatus;
                $order['txn_id'] = $txnid;
            }else if($payment_method=="paypal"){
                $order['payment_method']=4; 
                $order['txn_id'] = '';
            }

            if($this->session->userdata('user_login_type')=='register_user'){
                
                $oamt = ($order['subtotal']-$order['coupon_amount']-$order['birthday_discount']);
                $user = $this->common->getsData("user",array("profileid"=>$this->session->userdata("profileid")),'verify,total_point');
                if($user['verify']==1){
                    // if($user['total_point']>500){
                    //     $level = 20;
                    // }else if($user['total_point']>300 && $user['total_point']<=500){
                    //     $level = 10;
                    // }else{
                    //     $level = 5;
                    // }
                    // $order['earn_point'] = round($oamt)*$level;
                    $order['earn_point'] = round(($oamt*$this->coinspend));
                    if($oamt>100){
                        $order['earn_point'] = $order['earn_point']+$this->extra_coin;
                    }
                }else{
                    $order['earn_point'] = 0;
                }
            }else{
                $order['earn_point'] = 0;
            }
            // echo "<pre>";
            // print_r ($order);
            // echo "</pre>";die;


            $order['grandtotal'] = ($order['subtotal']-$order['coupon_amount']+$order['delivery_charge']-$order['birthday_discount']);

            $order['use_coins'] = 0;
            $order['use_coins_amount'] = 0;
            $us = $this->session->userdata('userdata');
            $isWallet = (isset($us['isWallet']))?$us['isWallet']:0;
           
            if($isWallet==1){
                $wal = $this->common->getsData('user',array('profileid'=>$this->profileid),array('remain_point'));
                if($wal['remain_point']>1000){
                    $wallet = $wal['remain_point']/200;
                    if($wallet>$order['grandtotal']){
                        $order['use_coins'] = $order['grandtotal']*200;
                        $order['use_coins_amount'] = $order['grandtotal'];
                    }else{
                        $order['use_coins'] = $wal['remain_point'];
                        $order['use_coins_amount'] = $wallet;
                    }
                }
            }

            $order['grandtotal'] = $order['grandtotal']-$order['use_coins_amount'];

            /*if($this->profileid && $this->cart->contents()) {
                if($this->cart->total() > 100) {
                    $first_order = $this->db->query("select orderid from `orders` where profileid = '".$this->profileid."'")->num_rows();
                    if($first_order==0) {
                        $order['first_order'] = 5;
                        $this->session->set_userdata("first_order",$order['first_order']);
                        $order['grandtotal'] -= 5;
                    }else{
                        $order['first_order'] = 0;
                        $this->session->set_userdata("first_order",0);
                    }
                }else{
                    $order['first_order'] = 0;
                    $this->session->set_userdata("first_order",0);  
                }
            }else{
                $order['first_order'] = 0;
            }*/
            $order['first_order'] = 0;
            $this->session->set_userdata("first_order",0); 

            $this->session->set_userdata('orderTotal',$order['grandtotal']);

            $order['order_status'] = 1;

            $order['order_by'] = "web";

            $coupon = $this->session->userdata('user_coupon');

            $grandtotal = $this->cart->total();

            //echo "<pre>";
            // print_r($order); die;
            // print_r($this->cart->contents()); die;
            // $invoice_no = 12345;
            // $this->mailToConfirmOrder($orderid,$order['order_time'],$order['coupon_amount'],$order['first_order'],$order['payment_currency'],$order['txn_id'],$order['delivery_charge'],$order['birthday_discount'],$order['payment_method'],$invoice_no);die;
            if(!($this->common->getData('orders',array("orderid"=>$orderid)))){
                if($this->common->insertData("orders",$order)){  
                    $loid = $this->db->insert_id(); 
                    if(strlen((string)$loid)>=3){
                        $invoice_no = orderid_prefix.date('y').$loid;
                    }else if(strlen((string)$loid)==2){
                        $invoice_no = orderid_prefix.date('y')."0".$loid;
                    }else{
                        $invoice_no = orderid_prefix.date('y')."00".$loid;
                    }  
                    $this->common->updateData('orders',array('invoice_no'=>$invoice_no),array("orderid"=>$orderid));            
                    $cm=array();
                    foreach ($cart_mapping as $key => $value) {
                        $cm1 = $value['options'];
                        unset($value['options']);

                        $product_coupon_code = '';
                        $product_coupon_amount = 0;
                        if($this->session->userData('product_coupon')){
                            $coupon_apply = $this->session->userData('product_coupon');
                            if(isset($coupon_apply[$value['id']]) && $coupon_apply[$value['id']]){
                              $product_coupon_code = $coupon_apply[$value['id']]['coupon_code'];
                              if($coupon_apply[$value['id']]['coupon_type']==0){
                                $product_coupon_amount = $coupon_apply[$value['id']]['coupon_amount'];
                              }else{
                                $product_coupon_amount = ($value['price']*$coupon_apply[$value['id']]['coupon_amount'])/100;
                              }
                            }
                        }

                        $cm[$key] = array_merge(array("orderid"=>$orderid,"profileid"=>$this->session->userdata("profileid"),'product_coupon_amount'=>$product_coupon_amount,'product_coupon_code'=>$product_coupon_code),$cm1,$value);
                        unset($cm[$key]['price']);
                        unset($cm[$key]['id']);
                        unset($cm[$key]['name']);
                        unset($cm[$key]['rowid']);
                        //print_r($cm[$key]); die;
                        $this->common->insertData("cart_mapping",$cm[$key]);
                    }
                    $user_order_address = $this->userOrderAddress();
                    $this->common->insertData("user_order_address",$user_order_address);

                    $productStockUpdate = $this->cart->contents();
                    foreach ($productStockUpdate as $key => $value) {
                       $productStock = $this->common->getsData('products',array('productid'=>$value['options']['productid']),'product_stock');
                       $this->common->updateData('products',array('product_stock'=>($productStock['product_stock']-$value['qty'])),array('productid'=>$value['options']['productid']));
                       
                       // $productStock = $this->common->getsData('product_unit',array('productid'=>$value['options']['productid'],'type'=>$value['options']['product_type']),'product_stock');
                       // $this->common->updateData('product_unit',array('product_stock'=>($productStock['product_stock']-$value['qty'])),array('productid'=>$value['options']['productid'],'type'=>$value['options']['product_type']));
                    }

                    if($order['coupon_code']!=''){
                        $query = ('UPDATE  coupon SET  `coupon_quantity` =  coupon_quantity-1 WHERE  `coupon`.`coupon_code` ="'.$order['coupon_code'].'"');
                        $this->db->query($query);
                    }

                    /*if ($this->session->userdata('cart_points')>0) {
                        $tpoint = $this->session->userdata('cart_points');
                        $ud = $this->common->getsData('user',array('profileid'=>$this->session->userdata("profileid")));
                        $this->db->query('UPDATE user SET withdraw_point = withdraw_point + '.$tpoint.', remain_point = remain_point - '.$tpoint.' WHERE id = '.$ud['id']);
                        $reason = "Withdraw points on order - #".$orderid;
                        $this->common->insertData('point_history',array('orderid'=>$orderid,'point'=>$tpoint,'profileid'=>$this->session->userdata("profileid"),'type'=>1,'reason'=>$reason,'date'=>date('Y-m-d H:i:s')));
                    }*/

                    /*if($order['earn_point']>0){
                        if($order['payment_method']!=1){
                            $query = ('UPDATE  user SET `total_point` =  total_point+'.$order['earn_point'].', `remain_point` =  remain_point+'.$order['earn_point'].' WHERE `profileid` ="'.$this->session->userdata("profileid").'"');
                            $this->db->query($query);
                            $reason = "Earn points on order - #".$orderid;
                            $this->common->insertData('point_history',array('orderid'=>$orderid,'point'=>$order['earn_point'],'profileid'=>$this->session->userdata("profileid"),'type'=>0,'reason'=>$reason,'date'=>date('Y-m-d H:i:s')));
                        }
                    }*/

                    $this->mailToConfirmOrder($orderid,$order['order_time'],$order['coupon_amount'],$order['first_order'],$order['payment_currency'],$order['txn_id'],$order['delivery_charge'],$order['birthday_discount'],$order['payment_method'],$invoice_no,$pstatus);

                    $this->session->unset_userdata("cart_contents");

                    $this->session->unset_userdata("bname");

                    $this->session->unset_userdata("bemail");

                    $this->session->unset_userdata("bmobile_no");

                    $this->session->unset_userdata("baddress1");

                    $this->session->unset_userdata("baddress2");

                    $this->session->unset_userdata("bcity");

                    $this->session->unset_userdata("bstate");

                    $this->session->unset_userdata("bpincode");

                    $this->session->unset_userdata("sname");

                    $this->session->unset_userdata("semail");

                    $this->session->unset_userdata("smobile_no");

                    $this->session->unset_userdata("saddress1");

                    $this->session->unset_userdata("saddress2");

                    $this->session->unset_userdata("scity");

                    $this->session->unset_userdata("sstate");

                    $this->session->unset_userdata("spincode");

                    $this->session->unset_userdata("payment_method");
                    $this->session->unset_userdata("rozorpay_paymentid");
                    $this->session->unset_userdata("paypal_txnid");

                    $this->session->unset_userdata("orderTotal");

                    $this->session->unset_userdata("user_coupon");

                    $this->session->unset_userdata("user_coupon_code");
                    $this->session->unset_userdata("birthday_discount");
                    $this->session->unset_userdata("product_coupon");
                    echo 'Your order is completed. If you are not auto redirect to thank you page please click on - <a href="'.base_url("thank-you").'">thank you</a>';
                    // redirect(base_url("thank-you"));
                    echo "<script>location.href='".base_url("thank-you")."';</script>";
                    header('Location: '.base_url("thank-you")); exit();

                }else{
                    $this->session->set_flashdata('emessage','Something Went Wrong. Please Try Again...');
                    redirect(base_url('checkout'));
                } 
            }else{

                // $this->session->set_flashdata('emessage','Order Already Placed...');

                // redirect(base_url());
                echo "<script>location.href='".base_url("thank-you")."';</script>";
                header('Location: '.base_url("thank-you")); exit();

            } 
        }

    }


    public function userOrderAddress()
    {
        $userOrderAddress = $this->session->userdata('userdata');
        $data = array();

        $data['orderid'] = $this->session->userdata('orderid');;

        $data['profileid'] = $this->session->userdata("profileid");

        $data['bname'] = $userOrderAddress['bname'];

        $data['bemail'] = $userOrderAddress['bemail'];

        $data['bmobile_no'] = $userOrderAddress['bmobile_no'];

        $data['baddress1'] = $userOrderAddress['baddress1'];

        $data['baddress2'] = $userOrderAddress['baddress2'];

        $data['bcountry'] = $userOrderAddress['bcountry'];

        $data['bcity'] = $userOrderAddress['bcity'];

        $data['bstate'] = $userOrderAddress['bstate'];

        $data['bpincode'] = $userOrderAddress['bpincode'];

        $data['sname'] = $userOrderAddress['sname'];

        $data['semail'] = $userOrderAddress['semail'];

        $data['smobile_no'] = $userOrderAddress['smobile_no'];

        $data['saddress1'] = $userOrderAddress['saddress1'];

        $data['saddress2'] = $userOrderAddress['saddress2'];

        $data['scountry'] = $userOrderAddress['scountry'];

        $data['scity'] = $userOrderAddress['scity'];

        $data['sstate'] = $userOrderAddress['sstate'];

        $data['spincode'] = $userOrderAddress['spincode'];

        return $data;
    }


    public function mailToConfirmOrder($orderid='',$order_time='',$coupon='',$firstorder='',$currency='',$txn_id='',$dcharge='',$birthday='',$payment_method='',$invoice_no='',$pstatus='')
    {
        $cart = $this->cart->contents();
        $options = array_column($cart, 'options');
        $product = array_column($options, 'product_name');
        if(isset($product) && !empty($product)){
            $products_name = implode(',', $product);
        }else{
            $products_name = author;
        }
        // echo "<pre>";
        // print_r($products_name);
            //die;
        $data['userdata'] = $this->common->getsData("user",array("profileid"=>$this->session->userdata("profileid")));

        $data['cart'] = $this->cart->contents();

        $data['orderid'] = $orderid;
        $data['currency'] = $currency;
        $data['txn_id'] = $txn_id;

        $data['order_time'] = $order_time;

        $data['coupon'] = $coupon;
        $data['firstorder'] = $firstorder;
        $data['ship_charge'] = $dcharge;
        $data['birthday'] = $birthday;
        $data['payment_method'] = $payment_method;
        // $data['invoice_no'] = $invoice_no;
        $data['invoice_no'] = $orderid;

        $data['coupon_apply'] = $this->session->userData('product_coupon');

        $data['address'] = $this->common->getsData("user_order_address",array("profileid"=>$this->session->userdata("profileid"),'orderid'=>$orderid));
        if(empty($data['address'])){
            $data['address'] = $this->common->getsData("user_address",array("profileid"=>$this->session->userdata("profileid")));
        }
        if($pstatus=='Pending' || $payment_method=='pending'){
            $subject = "We have received your order. Order ID: ".$orderid;
            $umessage = $this->load->view("email_temp/email-pending",$data,true);
        }else{
            $subject = "Thank you for your purchase. Order ID: ".$orderid;
            $umessage = $this->load->view("email_temp/email",$data,true);
        }

        // echo $umessage; die;

        // $this->email->from("ben@websentials.com.sg",author);

        // $this->email->to($this->session->userdata("email"));
        // $this->email->subject($subject);

        // $this->email->message($umessage);
        $res = $this->common->sendMailBySendGrid($this->session->userdata("email"),'',from_email,author,$subject,$umessage);

        $admin_subject = "You have a new order - ".$orderid;
        $admin_message = $this->load->view("email_temp/admin-email",$data,true);

        $res = $this->common->sendMailBySendGrid(order_email,'',from_email,author,$admin_subject,$admin_message);


       if($res){
           $amount = $this->session->userdata('orderTotal');
            if($this->session->userdata('user_login_type')=='guest_user'){
                $mno = $this->session->userdata('bmobile_no');
                $unam = $this->session->userdata('bname');
            }else{
                $mno = $data['userdata']['mobile_no'];
                $unam = $data['userdata']['name'];
            }
            $Date = date('Y-m-d');
            $ddate = date('Y-m-d', strtotime($Date. ' + 1 days'));
            $rurl = base_url('user-order-detail/'.$orderid);
            //print_r($mno); die;
           $message = "Order Placed: your order for ".$products_name." ,amounting Rs ".$amount." has been placed. You can expect delivery by ".date('d-m-Y',strtotime($ddate)).". We will send you an update when your order is packed/shipped. For order details visit: ".$rurl." .";
           //$sresult = $this->common->sendMessage($message,$mno);
           // $adminmno = '9424489669';
           $adminmno = '7869967152';
           $adminmessage = "Hello ".author." ADMIN , you have received New order id is ".$orderid." Amount ".$amount.".";
           //$sresult1 = $this->common->sendMessage($adminmessage,$adminmno);
        }
        return true;
    }

    public function checkPincodeAvailability(){
        $status = 0;
        $message="";
        $message1="";
        //print_r($_POST);
        if($this->common->getsData("pincode",array("pincode"=>$_POST['pincode'],"cod"=>'Y'))){
            $status=1;
            $message="Item available for this pincode.";
        }else{
            $status=2;
            $message1="Only Online Payment Method Available for this Pincode."; 
        }
        header('Content-type: application/json; charset=utf-8"');
        echo json_encode(array("status"=>$status,"message"=>$message,'message1'=>$message1));die;
    }

    public function trackOrderAction()
    {
        if(isset($_POST['orderid']) && $_POST['orderid']!=''){
            $orderid = $_POST['orderid'];
            $data['trackorder'] = $this->front->getOrders($orderid,1);
            // echo "<pre>";
            // print_r($data['trackorder']); die;
            $this->loadHtml("track-order","Track Order",$data);
        }else{
            $data['trackorder']='';
            $this->loadHtml("track-order","Track Order",$data);
        }
    }

} 