<?php

namespace App\Http\Controllers;
use App\Http\Controllers\PaypalExpress;
use App\Http\Controllers\MigsController;
use App\Models\Article;
use App\Models\Campaign;
use App\Models\Cart;
use App\Models\Chapter;
use App\Models\EbookVolume;
use App\Models\Node;
use App\Models\Orders;
use App\Models\Log;
use App\User;
use Auth;
use Crypt;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Mail;

class CartController extends BenthamController
{

    public function index(Request $request)
    {
        $cart_id = session()->get('uc_cart_id');
	
        $user = Auth::user();
        if ($user) {
            $cdata['cart_id'] = $user->id;
            Cart::UpdateCart($cart_id, $cdata);
        }
        $cid = $this->uc_cart_get_id();
		
		
        $cartlist      = Cart::GetCartProducts($cid);
        $promodiscount = session()->has('promo_discount') ? session()->get('promo_discount') : false;
        $leastpricenid = $this->get_leastpricenid($request, $cartlist);

        if ($leastpricenid != null) {

            $cnt = 0;
            foreach ($cartlist as $item) {
                if ($item->item_type == 'ebook_volume') {
                    if ($item->nid == $leastpricenid) {
                        session()->forget('promo_discount');
                        session()->forget('discount_type');
                        session()->forget('campaign_id');
                        $ebook_discount = 50;
                        $item_price     = round(($ebook_discount / 100) * ($item->item_price));
                        session(['least_price_nid' => $leastpricenid]);
                        session(['least_price' => ($item_price) * $item->qty]);
                        session(['original_price' => ($item->item_price) * $item->qty]);

                        $cartlist[$cnt]->item_price = round($item->item_cost - $item_price);
                        $cartlist[$cnt]->discount   = $ebook_discount;
                    }
                }

                $cnt++;
            }
        } elseif ($promodiscount) {
// if promotion code applicable

            session()->forget('least_price_nid');
            session()->forget('least_price');
            session()->forget('original_price');
            
            $data     = Campaign::GetCampaignById(session()->get('campaign_id'));
            $cartlist = $this->CheckPromoAccess($request, $data);

        }

        if (session()->has('uc_cart_count_item') && !session()->has('promo_discount')) {

            Session::flash('message', " if you buy a second book, or, more than one book, you will get a 50% discount on the lowest price book");
            session()->forget('uc_cart_count_item');
        }

        return View::make('cart.cart')->with('cartlist', $cartlist)->with('promodiscount', $promodiscount)->with('leastpricenid', $leastpricenid);
    }

    public function get_leastpricenid($request, $cartlist)
    {

        static $items = array();
        $leastprice   = null;
        $leastnid     = null;
        session()->forget('nids');
        session()->forget('least_price_nid');
        session()->forget('least_price');

        $cnt = 0;
        // find least price of ebook
        foreach ($cartlist as $item) {
            //only for ebook volume
            if ($item->item_type == "ebook_volume") {

                $price[$item->nid] = $item->item_cost;
                session(['uc_cart_count_item' => 1]);
                $cnt++;

            }

        } //foreach

        if ($cnt > 1) {
            //sort by least price of ebook and get nid
            asort($price);
            foreach ($price as $k => $p) {
                $leastprice    = $p; //p = price
                $leastpricenid = $k; // k = nid
                break;
            } //foreach
        }

        if ($cnt > 1) {
            //if ebook is more than 1 least price of ebook_nid return
            return $leastpricenid;

        } else {

            return null;
        }

    } //uc_get_nid

    /*
     * Date: 28-01-2019
     * Author: Arshad
     * Parameter: Request Parameter and PromoCode data row
     * Description:  this function will return the true false, if access conditions applicable
     *  LIKE -- Journal wise promotions
    -- Ebook wise promotions
    -- Country wise promotions
    -- IP base promotions
     */

    public function CheckPromoAccess($request, $promo_data)
    {

        $journal_access = false;
        $ebook_access   = false;
        $country_access = false;
        $ip_access      = false;
        $Promo_Access   = false;
        $userip         = $request->ip();

        $cid      = $this->uc_cart_get_id();
        $cartlist = Cart::GetCartProducts($cid);

        /*
         * Check if Promotion has been given on all journals, ebooks and All countries
         */
        if ($promo_data->journals == 'All' && $promo_data->ebooks == 'All' && $promo_data->country == 'All' && ($promo_data->area_type == 'country' && $promo_data->country == 'All')) {
            $Promo_Access = true;
            $cnt          = 0;
            foreach ($cartlist as $cart_item) {

                $discount                   = $promo_data->discount;
                $item_price                 = round(($discount / 100) * ($cart_item->item_price));
                $cartlist[$cnt]->item_price = round($cart_item->item_cost - $item_price);
                $cartlist[$cnt]->discount   = $discount;
                $cnt++;
            }

            return $cartlist;

        } else {

            $country_access_all = false;

            /*
             * Check if Promotion has been given on Country wise
             */
            if (($promo_data->area_type == 'country' && $promo_data->country == 'All')) {
                $country_access = true;
            } elseif (($promo_data->area_type == 'country' && $promo_data->country != 'All')) {

               
                $query        = "select * from ip2location_db5 where ip_from<='" . ip2long($userip) . "' and ip_to>='" . ip2long($userip) . "'";
                $user_country = DB::select($query);


                if ($user_country[0]->country_name != '-') {

                    $promo_country = explode(',', $promo_data->country);
                    $user_country  = $user_country[0]->country_code;
                    if (in_array($user_country, $promo_country)) {
                        $country_access = true;
                    }

                }

                /*
             * Check if Promotion has been given on IP range wise
             */
            } elseif ($promo_data->area_type == 'ip') {

                $q2            = "select * from campaign_ips where campaign_id='" . $promo_data->id . "' and  from_ip<='" . ip2long($userip) . "' and to_ip>='" . ip2long($userip) . "'";
                $user_ip_range = DB::select($q2);

                if ($user_ip_range) {
                    $country_access = true;
                }
            }

            $cnt = 0;
            foreach ($cartlist as $cart_item) {

                if ($cart_item->item_type == 'article') {
                    /*
                     * If $country_access true then check All journal access case
                     */
                    if ($promo_data->journals == 'All' && $country_access) {

                        $discount                   = $promo_data->discount;
                        $item_price                 = round(($discount / 100) * ($cart_item->item_price));
                        $cartlist[$cnt]->item_price = round($cart_item->item_price - $item_price);
                        $cartlist[$cnt]->discount   = $discount;
                        /*
                     * If $country_access true then check on selected journal access case
                     */
                    } elseif ($promo_data->journals != 'All' && $country_access) {

                        $journals = explode(',', $promo_data->journal_ids);
                        if (in_array($cart_item->promotion_content_id, $journals)) {

                            $discount                   = $promo_data->discount;
                            $item_price                 = round(($discount / 100) * ($cart_item->item_price));
                            $cartlist[$cnt]->item_price = round($cart_item->item_price - $item_price);
                            $cartlist[$cnt]->discount   = $discount;
                        }
                    }
                }if ($cart_item->item_type == 'chapter') {

                    /*
                     * If $country_access true then check All Ebook access case  for ebook chapters
                     */
                    if ($promo_data->ebooks == 'All' && $country_access) {

                        $discount                   = $promo_data->discount;
                        $item_price                 = round(($discount / 100) * ($cart_item->item_price));
                        $cartlist[$cnt]->item_price = round($cart_item->item_price - $item_price);
                        $cartlist[$cnt]->discount   = $discount;

                        /*
                     * If $country_access true then check on selected ebooks access case for ebook chapters
                     */
                    } elseif ($promo_data->ebooks != 'All' && $country_access) {
                        $ebooks = explode(',', $promo_data->ebook_ids);
                        if (in_array($cart_item->promotion_content_id, $ebooks)) {
                            $ebook_access = true;
                            $Promo_Access = true;

                            $discount                   = $promo_data->discount;
                            $item_price                 = round(($discount / 100) * ($cart_item->item_price));
                            $cartlist[$cnt]->item_price = round($cart_item->item_price - $item_price);
                            $cartlist[$cnt]->discount   = $discount;
                        }
                    }
                }if ($cart_item->item_type == 'ebook_volume') {

                    /*
                     * If $country_access true then check on All ebooks access case
                     */
                    if ($promo_data->ebooks == 'All' && $country_access) {

                        $discount                   = $promo_data->discount;
                        $item_price                 = round(($discount / 100) * ($cart_item->item_price));
                        $cartlist[$cnt]->item_price = round($cart_item->item_price - $item_price);
                        $cartlist[$cnt]->discount   = $discount;

                        /*
                     * If $country_access true then check on Selected ebooks access case
                     */
                    } elseif ($promo_data->ebooks != 'All' && $country_access) {
                        $ebooks = explode(',', $promo_data->ebook_ids);
                        if (in_array($cart_item->promotion_content_id, $ebooks)) {

                            $discount                   = $promo_data->discount;
                            $item_price                 = round(($discount / 100) * ($cart_item->item_price));
                            $cartlist[$cnt]->item_price = round($cart_item->item_price - $item_price);
                            $cartlist[$cnt]->discount   = $discount;

                        }
                    }
                }

                $cnt++;

            }

        }

        return $cartlist;
    } //end

    public function PromoCode(Request $request)
    {

        $code = trim($request->code);
        session(['code' => $code]);
        $single_code = strtoupper(substr($code, 0, 3));
        
        if ($code) {

            if (($single_code == 'BSP' && strlen($code) <= 15) || ($single_code == 'CAT' && strlen($code) == 6)) {


                session(['discount_type' => 'Single']);
                $param['code']            = trim($code);
                $param['type']            = 'Single';
                $param['campaign_status'] = 'Active';
                $result                   = Campaign::GetDiscountPromoCode($param);

                if (count($result) == 0) {

                    Session::flash('message', 'Enter Valid Code');
                    if (session()->has('promo_discount')) {
                        session()->forget('promo_discount');
                    }
                } else {

                    $flag = 1;

                    foreach ($result as $data) {

                        //if($this->CheckPromoAccess($request,$data)){

                        session(['campaign_id' => $data->id]);                        
                        $start_date   = date('Y-m-d', strtotime($data->start_date));
                        $expiry_date  = date('Y-m-d', strtotime($data->end_date));
                        $current_date = date('Y-m-d', strtotime('now'));
                        $discount     = $data->discount;
                        if ($current_date > $expiry_date && $current_date > $start_date) {
                            Session::flash('message', 'Promotion Code is Expired');
                            $flag = 0;
                            if (session()->has('promo_discount')) {
                                session()->forget('promo_discount');
                            }
                        } elseif ($current_date < $expiry_date && $current_date < $start_date) {
                            Session::flash('message', 'Campaign not started');
                            $flag = 0;
                            if (session()->has('promo_discount')) {
                                session()->forget('promo_discount');
                            }
                        } elseif ($flag == 1) {
                            session(['promo_discount' => $discount]);

                        }
                        //}
                    }
                }
            } else {

                session(['discount_type' => 'Multi']);

                $param['code']            = trim($code);
                $param['type']            = 'Multi';
                $param['status']          = 0;
                $param['campaign_status'] = 'Active';
                $result                   = Campaign::GetDiscountPromoCode($param);

                if (count($result) == 0) {

                    Session::flash('message', 'Enter Valid Code');
                    if (session()->has('promo_discount')) {
                        session()->forget('promo_discount');
                    }

                } else {
                    $flag = 1;
                    foreach ($result as $data) {
                        //if($this->CheckPromoAccess($request,$data)){
                        session(['campaign_id' => $data->id]);
                        if ($data->status == 'U') {
                            $flag = 0;
                            Session::flash('message', $code . ' is already used');
                            if (session()->has('promo_discount')) {
                                session()->forget('promo_discount');
                                session()->forget('code');
                            }

                        } else {
                            $start_date   = date('Y-m-d', strtotime($data->start_date));
                            $expiry_date  = date('Y-m-d', strtotime($data->end_date));
                            $current_date = date('Y-m-d', strtotime('now'));
                            $discount     = $data->discount;
                            if ($current_date > $expiry_date && $current_date > $start_date) {

                                Session::flash('message', 'Promotion Code is Expired');
                                $flag = 0;
                                if (session()->has('promo_discount')) {
                                    session()->forget('promo_discount');
                                    session()->forget('code');
                                }

                            } elseif ($current_date < $expiry_date && $current_date < $start_date) {

                                Session::flash('message', 'Campaign not started');
                                $flag = 0;
                                if (session()->has('promo_discount')) {
                                    session()->forget('promo_discount');
                                    session()->forget('code');
                                }

                            } elseif ($flag = 1) {
                                session(['promo_discount' => $discount]);
                                session(['code' => trim($code)]);

                            }
                        }
                        //}
                    }

                }

            }
        } else {
            session()->forget('promo_discount');
            session()->forget('code');
        }

        //use here to return promode module
        if(isset($request->url))
        {
            return redirect()->back();
        }
        else
        {
            return Redirect::to('/cart');
        }
    }
    public function store(Request $request)
    {

        $nid       = Crypt::decrypt($request->param);
        $validator = Validator::make($request->all(), [
            'param' => 'required',
        ]);


        //$cid = session()->has('uc_cart_id') ? session()->get('uc_cart_id') : null;

        // process the login
        if ($validator->fails()) {
            $p['param'] = $request->get("param");
            return back()->with(with(['param' => $param]))->withInput()->withErrors($validator);
        } else {
                $cart_id = session()->get('uc_cart_id');

                $user = Auth::user();
                if ($user) {
                    $cdata['cart_id'] = $user->id;
                    Cart::UpdateCart($cart_id, $cdata);
                }
                $cid = $this->uc_cart_get_id();

              //  dd($cid);

            // If we didn't get a cid, return empty.
            if (!$cid) {
                return array('');
            }

            $data['cart_id'] = $cid;
            $data['nid']     = $nid;
            $data['qty']     = 1;
            $data['changed'] = time();
            $data['data']    = json_encode(array(0));

            if (Cart::AddtoCart($data)) {
                return Redirect::to('/cart');
            } else {
                Session::flash('message', " Item already exist");
                return Redirect::back();
            }

        }
        Session::flash('message', " Cart Validation Error!");
        return Redirect::back();

    }

    public function destroy($cart_item_id, Request $request)
    {
        $cart_item_id = Crypt::decrypt($cart_item_id);
        //try {
        // try transaction start here for data integrity

        //DB::beginTransaction();
        Cart::DeleteCartItem($cart_item_id);

        //} catch (Exception $e) {

        //DB::rollback();
        //Session::flash('error', 'Somthing wrong with this page. Please try again!');
        //return Redirect::to('/cart');
        //}
        return Redirect::to('/cart');
    }

    public function checkout(Request $request)
    {

        $user = Auth::user();
        if (!$user) {
            Session::flash('message', '<ul><li>You must login before you can proceed to checkout.</li>
                <li>If you do not have an account yet, you should <a href="/register">register now</a>.</li></ul>');
            return Redirect::guest('login');
        }

        $cid           = $this->uc_cart_get_id();
        $cartlist      = Cart::GetCartProducts($cid);
        $promodiscount = session()->has('promo_discount') ? session()->get('promo_discount') : false;
        $leastpricenid = $this->get_leastpricenid($request, $cartlist);

        if ($leastpricenid != null) {

            $cnt = 0;
            foreach ($cartlist as $item) {
                if ($item->item_type == 'ebook_volume') {
                    if ($item->nid == $leastpricenid) {

                        session()->forget('promo_discount');
                        session()->forget('discount_type');
                        session()->forget('campaign_id');

                        $ebook_discount = 50;
                        //$item->price = ($product->sell_price)/2;
                        $item_price = round(($ebook_discount / 100) * ($item->item_price));

                        session(['least_price_nid' => $leastpricenid]);
                        session(['least_price' => ($item_price) * $item->qty]);
                        session(['original_price' => ($item->item_cost) * $item->qty]);

                        $cartlist[$cnt]->item_price = round($item->item_cost - $item_price);
                        $cartlist[$cnt]->discount   = $ebook_discount;
                    }
                }

                $cnt++;
            }
        } elseif ($promodiscount) {
// if promotion code applicable

            session()->forget('least_price_nid');
            session()->forget('least_price');
            session()->forget('original_price');

            $cdata    = Campaign::GetCampaignById(session()->get('campaign_id'));
            $cartlist = $this->CheckPromoAccess($request, $cdata);            

        }
        if (session()->has('uc_cart_count_item')) {

            Session::flash('message', " if you buy a second ebook, or, more than one book, you will get a 50% discount on the lowest price book");
            session()->forget('uc_cart_count_item');
        }

        // try {// try transaction start here for data integrity

        //DB::beginTransaction();
        $data['uid']           = $user->id;
        $data['order_status']  = 'in_checkout';
        $data['primary_email'] = $user->email;
        $data['created']       = time();
        $data['host']          = $request->ip();
        $data['ip_address']    = ip2long($request->ip());
        $data['source']        = 'BSP';
        $data['source_val']    = 1;
        if (count($cartlist) > 0) {
            $order_id = Orders::CreateOrder($data);
        }

        $cnt   = 0;
        $total = 0;
        foreach ($cartlist as $row) {

            $uc_order_products[$cnt]['order_id'] = $order_id;
            $uc_order_products[$cnt]['nid']      = $row->nid;
            $uc_order_products[$cnt]['title']    = $row->item_title;
            $uc_order_products[$cnt]['qty']      = $row->qty;
            $uc_order_products[$cnt]['cost']     = $row->item_cost;
            $uc_order_products[$cnt]['price']    = $row->item_price;
            $uc_order_products[$cnt]['weight']   = 0;
            $uc_order_products[$cnt]['data']     = '';

            $total = ($row->item_price * $row->qty) + $total;
            $cnt++;
        }
        if (session()->has('promo_discount')) {
            $promodiscount  = session()->get('promo_discount');
            //$discount_total = ($promodiscount / 100) * $total;            
            //$total          = round($total - $discount_total);
        }
        
        Orders::AddProducts($uc_order_products);

        $order_data['order_total']   = round($total, 4);
        $order_data['product_count'] = $cnt + 1;
        $order_data['modified']      = time();

        Orders::UpdateOrder($order_id, $order_data);

        //} catch (Exception $e) {

        //DB::rollback();
        //Session::flash('error', 'Somthing wrong with this page. Please try again!');
        //return Redirect::to('/cart');
        //}

        $orderlist = Orders::GetOrderDetail($order_id);

        $promodiscount = session()->has('promo_discount') ? session()->get('promo_discount') : false;

        return View::make('cart.checkout')->with('orderlist', $orderlist)->with('order_id', $order_id)->with('promodiscount', $promodiscount);
    }

    public function PaymentProceed(Request $request)
    {
        if ($request->back) {
            $ptype = $request->back;
        }if ($request->paypal) {
            $ptype = $request->paypal;
        }if ($request->migs) {
            $ptype = $request->migs;
        }
        $order_id = Crypt::decrypt($request->param);

        if(empty($order_id)) { return Redirect::to('/cart');}

        switch ($ptype) {
            case 'back':
                return Redirect::to('/cart');
                break;
            case 'paypal':

                $order_products = Orders::GetOrderProducts($order_id);
                $order          = Orders::GetOrder($order_id);

                $paypal['paypalEnv']          = env('paypalEnv');
                $paypal['paypalURL']          = env('paypalURL');
                $paypal['invoice']            = $order->order_id;
                $paypal['amount']             = round($order->order_total);
                $paypal['currency_code']      = 'USD';
                $paypal['paypalClientID']     = env('paypalClientID');
                $paypal['return']             = url("/cart/paypal/complete/$order->order_id");


                return view('cart.paypal', with(['order' => $order, 'order_products' => $order_products, 'paypal' => $paypal]));
                break;
            case 'migs':

                $order = Orders::GetOrder($order_id);

                $migs['merchat_id']         = env('migs_id');
                $migs['order_id']           = $order->order_id;
                $migs['amount']             = $order->order_total;
                $migs['currency_code']      = 'USD';
                $migs['return_url']         = url("/cart/migs/complete/" . $order_id);   
                $migs['cancel_url']         = url("/cart");   

                $migs_obj = new MigsController;
                $responseCheck = $migs_obj->RequestMigsResponse($migs['order_id']);
                $migs['session_id']         = $responseCheck->session->id;

                return view('migs', with(['migs' => $migs]));

                exit;
                break;

            default:
                return Redirect::to('/cart');
                break;
        }

    }

    /*
    Author: Arshad
    Date: 23-11-2018
    Description : this fucntion will get the payment after redirect from gatway page
     */
    public function MigsReturn(Request $request)
    {
        $eGate            = 'migs';
        $order_id        = $request->order_id;

        $order          = Orders::GetOrder($order_id);
        $order_products = Orders::GetOrderProducts($order_id);

        $migs_obj = new MigsController;
        $apiResponse = $migs_obj->TransactionMigsResponse($order_id);
      
        $payment_gateway['order_id'] = $request->order_id;
        $payment_gateway['response'] = json_encode($apiResponse);
        $payment_gateway['domain'] = env('APP_NAME');
        Log::AddPaymentGatewayResponse($payment_gateway);        

        if ($apiResponse->result == "SUCCESS" && $apiResponse->transaction[0]->result != "FAILURE")
        {
            for($i=0;$i<sizeof($apiResponse->transaction);$i++)
            {
            if(isset($apiResponse->transaction[$i]->response->acquirerCode)){

                  $txnResponseCode = html_entity_decode($apiResponse->transaction[$i]->response->acquirerCode, ENT_QUOTES, 'UTF-8');
              if($txnResponseCode==00)
              {
            // Standard Receipt Data / Reponse of migs
                    $amount          = $apiResponse->transaction[$i]->transaction->amount;
                    $batchNo         = $apiResponse->transaction[$i]->transaction->acquirer->batch;
                    $message         = $apiResponse->transaction[$i]->response->acquirerMessage;
                    $version         = $apiResponse->transaction[$i]->version;
                    $cardType        = $apiResponse->sourceOfFunds->type;
                    $orderInfo       = $apiResponse->transaction[$i]->order->id;
                    $receiptNo       = $apiResponse->transaction[$i]->transaction->receipt;
                    $merchantID      = $apiResponse->transaction[$i]->transaction->acquirer->merchantId;
                    $authorizeID     = $apiResponse->transaction[$i]->transaction->authorizationCode;
                    $merchTxnRef     = $apiResponse->transaction[$i]->order->id;
                    $transactionNo   = $apiResponse->transaction[$i]->transaction->acquirer->transactionId;
                    $acqResponseCode = $apiResponse->transaction[$i]->transaction->acquirer->id;
                    $txnResponseCode = html_entity_decode($apiResponse->transaction[$i]->response->acquirerCode, ENT_QUOTES, 'UTF-8');
                    $plain_message   = html_entity_decode($apiResponse->transaction[$i]->response->acquirerMessage, ENT_QUOTES, 'UTF-8');
            $result          = $apiResponse->result;
            $status          = $apiResponse->status;

                $targs = array(
                    '@order'   => $orderInfo,
                    '@receipt' => $receiptNo,
                    '@trans'   => $transactionNo,
                    '@amount'  => round($amount),
                );
                $comment = 'A payment of ' . ($amount) . ' for order #' . $orderInfo . ' was made via MIGS by credit card with receipt number: ' . $receiptNo . ' and transaction number: ' . $transactionNo;
                Orders::uc_payment_enter($order->order_id, 'uc_migs', $amount, 0, null, $comment);
                // we also attach the MIGS receipt number to the order so we can
                // use it in an order token. Some MIGS banks require this number
                // be displayed to the purchaser in order to more readily process
                // complaints.
                $data_data['migs_receiptno'] = $receiptNo;
                $order->data                 = $data_data;
                $order->transactionNo        = $transactionNo;
                $order->payment_method       = 'migs';   
                Orders::uc_order_save($order);

                // Empty the cart...
                $cart_id = $this->uc_cart_get_id();
                Cart::uc_cart_empty($cart_id);

                // Add a comment to let sales team know this came in through the site.
                Orders::uc_order_comment_save($order->order_id, 0, 'A payment has been accepted.', 'admin');

                $nids    = DB::table('uc_order_products')->select('nid')->where('order_id', '=', $order_id)->get()->toArray();
                $user_id = $order->uid;

                $dataArray = array();
                $index     = 0;

                if ($nids) {
                    foreach ($nids as $data) {
                        $nid = $data->nid;

                        $DownloadType = Node::GetNode($nid)->type;

                        if ($DownloadType == "chapter") {
                            $chapter                     = Chapter::GetChapterByNID($nid);
                            $dataArray[$index]           = $chapter;
                            $dataArray[$index]->chapter  = 'chapter';
                            $dataArray[$index]->order_id = $order_id;
                            $cdata['user_id']            = $user_id;
                            $cdata['chapter_id']         = $chapter->chapter_id;
                            $cdata['order_id']           = $order_id;
                            DB::table('perpetual_chapter_access')->insert($cdata);

                        } else if ($DownloadType == "article") {
                            $article                     = Article::GetArticleByNID($nid);
                            $dataArray[$index]           = $article;
                            $dataArray[$index]->article  = 'article';
                            $dataArray[$index]->order_id = $order_id;
                            $adata['user_id']            = $user_id;
                            $adata['article_id']         = $article->article_id;
                            $adata['order_id']           = $order_id;
                            DB::table('perpetual_article_access')->insert($adata);

                        } else if ($DownloadType == "ebook_volume") {
                            $ebook_volume                = EbookVolume::GetEbookVolumeByNID($nid);
                            $dataArray[$index]           = $ebook_volume;
                            $dataArray[$index]->volume   = 'volume';
                            $dataArray[$index]->order_id = $order_id;
                            $vdata['user_id']            = $user_id;
                            $vdata['volume_id']          = $ebook_volume->ebook_volume_id;
                            $vdata['order_id']           = $order_id;
                            DB::table('perpetual_volume_access')->insert($vdata);

                        }
                        $index++;
                    }
                    
                    session(['PurchasedItems' => $dataArray]);
                    Orders::UpdateOrder($merchTxnRef, array('order_status' => 'completed'));
                }

                if (session()->has('promo_discount') && session()->get('discount_type') == 'Single') {
                    $order_type                      = session()->get('discount_type');
                    $campaign_id                     = session()->get('campaign_id');
                    $code                            = session()->get('code');
                    $campaign_data['campaign_id']    = $campaign_id;
                    $campaign_data['discount_codes'] = $code;
                    $campaign_data['user_id']        = $order->uid;
                    $campaign_data['order_id']       = $order->order_id;
                    $campaign_data['order_type']     = 'PPV';
                    $campaign_data['used_on']        = date('Y-m-d H:m:s');
                    $campaign_data['status']         = 'U';

                    Campaign::AddCampaignSingleDiscountCodes($campaign_data);

                     // if comes from preorder 
                     if (session()->has('pre_order_id'))
                     {
                        $update_pre_order = "update tbl_ebook_preorders SET status = 'C', order_id=".$order->order_id."
                        WHERE oid=".base64_decode(session()->get('pre_order_id'))."";
                        DB::statement($update_pre_order);
                     }
                }

                if (session()->has('promo_discount') && session()->get('discount_type') == 'Multi') {

                    $order_type                       = session()->get('discount_type');
                    $campaign_id                      = session()->get('campaign_id');
                    $code                             = session()->get('code');
                    $multicampaign_data['user_id']    = $order->uid;
                    $multicampaign_data['order_id']   = $order->order_id;
                    $multicampaign_data['order_type'] = 'PPV';
                    $multicampaign_data['used_on']    = date('Y-m-d H:m:s');
                    $multicampaign_data['status']     = 'U';

                    //Campaign::UpdateCampaignMultiDiscountCodes($campaign_id, $multicampaign_data);
                    $update_multi_promotion = "update campaign_multi_discount_codes SET user_id='$order->uid', order_id='$order->order_id',
                                               order_type='PPV', used_on=now(), status='U' WHERE campaign_id='$campaign_id' and discount_codes='$code'";
                    DB::statement($update_multi_promotion);

                     // if comes from preorder 
                     if (session()->has('pre_order_id'))
                     {
                        $update_pre_order = "update tbl_ebook_preorders SET status = 'C',  order_id=".$order->order_id."
                        WHERE oid=".base64_decode(session()->get('pre_order_id'))."";
                        DB::statement($update_pre_order);
                }

                }

                session()->forget('pre_order_id');
                session()->forget('code');
                session()->forget('campaign_id');
                session()->forget('discount_type');
                session()->forget('promo_discount');
                session()->forget('subtotal');

                $odetails=$this->GetOrderDetails($order->order_id);

                $invoice_html= View::make('admin.orders.template.invoice')
                ->with('order', $odetails['order'])
                ->with('user', $odetails['user'])
                ->with('payments', $odetails['payments'])
                ->with('balance', $odetails['balance'])
                ->with('products', $odetails['products'])
                ->with('comments', $odetails['comments'])
                ->with('admin_comments', $odetails['admin_comments'])
                ->with('order_logs', $odetails['order_logs'])
                ->with('ord_status', $odetails['ord_status']);
                
                $detail['payerName']    = $apiResponse->customer->firstName;
                $detail['orderInfo']    = $orderInfo;
                $detail['invoice']      = $invoice_html;

                $to      = $odetails['order']->primary_email;
                $from    = env('email_admin', '');
                $cc      = env('email_xolva_2').','.env('email_support_2');
                $subject = "Your Order at BenthamScience # " . $orderInfo;

                SendSmtpMail('email_template.paypal_order_successfull', $detail, $to, $from, $subject, 'Admin', $cc);
                
                Session::flash('success_msg', 'The Payment process was successfully completed');
                return view('cart.complete', with(['response_message' => $plain_message, 'orderInfo' => $orderInfo, 'receiptNo' => $receiptNo, 'order' => $order, 'order_products' => $order_products, 'eGate' => $eGate]));

			   }
			}
		   }
        }    
    }

    /*
    Author: Arshad
    Date: 23-01-2019
    Description : this fucntion will get the payment after redirect from gatway page
     */
    public function PaypalReturn(Request $request)
    {
        /*reponses payment_status Paypal

        Canceled_Reversal:  A reversal has been canceled. For example, you won a dispute with the customer, and the funds for the transaction that was reversed have been returned to you.
        Completed:          The payment has been completed, and the funds have been added successfully to your account balance.
        Created:            A German ELV payment is made using Express Checkout.
        Denied:             You denied the payment. This happens only if the payment was previously pending because of possible reasons described for the pending_reason variable or the Fraud_Management_Filters_x variable.
        Expired:            This authorization has expired and cannot be captured.
        Failed:             The payment has failed. This happens only if the payment was made from your customer’s bank account.
        Pending:            The payment is pending. See pending_reason for more information.
        Refunded:           You refunded the payment.
        Reversed:           A payment was reversed due to a chargeback or other type of reversal. The funds have been removed from your account balance and returned to the buyer. The reason for the reversal is specified in the ReasonCode element.
        Processed:          A payment has been accepted.
        Voided:             This authorization has been voided.

         */
        $eGate  = 'paypal';
        // $custom = $request->custom;
        //list($Txn_Secure_Hash, $oid, $order_amount) = decrypt($custom);
        $errorExists = false;

/*        if (strlen(config('constants.admin.token')) == 0) {
            // Secure Hash was not validated, none there to validate
            Session::flash('danger_msg', 'The Secure Hash Secret for this site has not been configured. Please contact the site administrator.');
            return view('cart.error');
        }
*/
        // Standard Receipt Data
        $paypal_obj = new PaypalExpress;

        $paymentID = $request->paymentID;
        $token = $request->token;
        $payerID = $request->payerID;
        $productID = $request->invoice;
        // Validate transaction via PayPal API
        $paymentCheck = $paypal_obj->PaypalValidate($paymentID, $token, $payerID, $productID);

        $payment_gateway['order_id'] = $request->invoice;
        $payment_gateway['response'] = json_encode($paymentCheck);
        $payment_gateway['domain'] = env('APP_NAME');
        Log::AddPaymentGatewayResponse($payment_gateway);      
		
        //dd($paymentCheck);
        $amount           = $paymentCheck->transactions[0]->amount->details->subtotal;
        // $item_name        = $request->item_name;
        // $mc_currency      = $request->mc_currency;
        $receiptNo        = $paymentID;
        // $custom           = $request->custom;
        $order_id         = $orderInfo         = $productID;
        // $receiver_id      = $payerID;
        $payment_status   = $paymentCheck->state;
        $response_message = $paymentCheck->state;
        $transactionNo    = $paymentCheck->transactions[0]->related_resources[0]->sale->id;
        $payer_email      = $paymentCheck->payer->payer_info->email;

        $order          = Orders::GetOrder($order_id);
        $order_products = Orders::GetOrderProducts($order_id);

/*        $param = base64_encode(md5(config('constants.admin.token')) . '||' . $orderInfo . '||' . $amount);

        if ($param == $request->custom) {
            // Secure Hash validation failed
            Session::flash('danger_msg', 'Transaction failed validation.');
            return view('cart.error', with(['response_message' => $response_message, 'orderInfo' => $orderInfo, 'receiptNo' => $receiptNo, 'order' => $order, 'order_products' => $order_products, 'eGate' => $eGate]));
        }
*/
        if ($payment_status == "approved") 
        {
            $txnResponseCode = 0;
        } 
        else 
        {
            // Secure Hash was not validated, none there to validate
            Session::flash('danger_msg', 'Payment gateway response could not be processed.');
            return view('cart.error', with(['response_message' => $response_message, 'orderInfo' => $orderInfo, 'receiptNo' => $receiptNo, 'order' => $order, 'order_products' => $order_products, 'eGate' => $eGate]));
        }

        if ($order === false) {
            Session::flash('danger_msg', 'No order found');
            return view('cart.error', with(['response_message' => $response_message, 'orderInfo' => $orderInfo, 'receiptNo' => $receiptNo, 'order' => $order, 'order_products' => $order_products, 'eGate' => $eGate]));
        }

        if ($txnResponseCode != "0" && $txnResponseCode != "C") {

            Session::flash('danger_msg', 'Attempted unverified Paypal completion for this order.');
            return view('cart.error', with(['response_message' => $response_message, 'orderInfo' => $orderInfo, 'receiptNo' => $receiptNo, 'order' => $order, 'order_products' => $order_products, 'eGate' => $eGate]));

        } else {
            if ($txnResponseCode == 0) {

                $targs = array(
                    '@order'   => $orderInfo,
                    '@receipt' => $receiptNo,
                    '@trans'   => $transactionNo,
                    '@amount'  => round($amount),
                );
                $comment = 'A payment of ' . ($amount) . ' for order #' . $orderInfo . ' was made via Paypal by credit card with receipt number: ' . $receiptNo . ' and transaction number: ' . $transactionNo;
                Orders::uc_payment_enter($order->order_id, 'Other', $amount, 0, null, $comment);
                // we also attach the MIGS receipt number to the order so we can
                // use it in an order token. Some MIGS banks require this number
                // be displayed to the purchaser in order to more readily process
                // complaints.
                $data_data['paypal_receiptno'] = $receiptNo;
                $order->data                   = $data_data;
                $order->transactionNo          = $transactionNo;
                $order->payment_method         = 'paypal';   
                Orders::uc_order_save($order);

                // Empty the cart...
                $cart_id = $this->uc_cart_get_id();
                Cart::uc_cart_empty($cart_id);

                // Add a comment to let sales team know this came in through the site.
                Orders::uc_order_comment_save($order->order_id, 0, 'A payment has been accepted.', 'admin');

                $nids    = DB::table('uc_order_products')->select('nid')->where('order_id', '=', $order_id)->get()->toArray();
                $user_id = $order->uid;

                $dataArray = array();
                $index     = 0;

                if ($nids) {
                    foreach ($nids as $data) {
                        $nid = $data->nid;

                        $DownloadType = Node::GetNode($nid)->type;
                        
                        if ($DownloadType == "chapter") {
                            $chapter                     = Chapter::GetChapterByNID($nid);
                            $dataArray[$index]           = $chapter;
                            $dataArray[$index]->chapter  = 'chapter';
                            $dataArray[$index]->order_id = $order_id;
                            $cdata['user_id']            = $user_id;
                            $cdata['chapter_id']         = $chapter->chapter_id;
                            $cdata['order_id']           = $order_id;
                            DB::table('perpetual_chapter_access')->insert($cdata);

                        } else if ($DownloadType == "article") {
                            $article                     = Article::GetArticleByNID($nid);
                            $dataArray[$index]           = $article;
                            $dataArray[$index]->article  = 'article';
                            $dataArray[$index]->order_id = $order_id;
                            $adata['user_id']            = $user_id;
                            $adata['article_id']         = $article->article_id;
                            $adata['order_id']           = $order_id;
                            DB::table('perpetual_article_access')->insert($adata);

                        } else if ($DownloadType == "ebook_volume") {
                            $ebook_volume                = EbookVolume::GetEbookVolumeByNID($nid);
                            $dataArray[$index]           = $ebook_volume;
                            $dataArray[$index]->volume   = 'volume';
                            $dataArray[$index]->order_id = $order_id;
                            $cdata['user_id']            = $user_id;
                            $cdata['volume_id']          = $ebook_volume->ebook_volume_id;
                            $cdata['order_id']           = $order_id;
                            DB::table('perpetual_volume_access')->insert($cdata);

                        }
                        $index++;
                    }

                    session(['PurchasedItems' => $dataArray]);
                    Orders::UpdateOrder($order_id, array('order_status' => 'completed'));

                }

            }

            if ($txnResponseCode == 0) {

                if (session()->has('promo_discount') && session()->get('discount_type') == 'Single') {
                    $order_type                      = session()->get('discount_type');
                    $campaign_id                     = session()->get('campaign_id');
                    $code                            = session()->get('code');
                    $campaign_data['campaign_id']    = $campaign_id;
                    $campaign_data['discount_codes'] = $code;
                    $campaign_data['user_id']        = $order->uid;
                    $campaign_data['order_id']       = $order->order_id;
                    $campaign_data['order_type']     = 'PPV';
                    $campaign_data['used_on']        = date('Y-m-d H:m:s');
                    $campaign_data['status']         = 'U';

                    Campaign::AddCampaignSingleDiscountCodes($campaign_data);
                }

                if (session()->has('promo_discount') && session()->get('discount_type') == 'Multi') {

                    $order_type                       = session()->get('discount_type');
                    $campaign_id                      = session()->get('campaign_id');
                    $code                             = session()->get('code');
                    $multicampaign_data['user_id']    = $order->uid;
                    $multicampaign_data['order_id']   = $order->order_id;
                    $multicampaign_data['order_type'] = 'PPV';
                    $multicampaign_data['used_on']    = date('Y-m-d H:m:s');
                    $multicampaign_data['status']     = 'U';

                    //Campaign::UpdateCampaignMultiDiscountCodes($campaign_id, $multicampaign_data);
                    $update_multi_promotion = "update campaign_multi_discount_codes SET user_id='$order->uid', order_id='$order->order_id',
                                               order_type='PPV', used_on=now(), status='U' WHERE campaign_id='$campaign_id' and discount_codes='$code'";
                    DB::statement($update_multi_promotion);

                }

                session()->forget('code');
                session()->forget('campaign_id');
                session()->forget('discount_type');
                session()->forget('promo_discount');
                session()->forget('subtotal');

                $response_message = $payment_status;

                $payerFirstName = $paymentCheck->payer->payer_info->first_name;
                $payerLastName = $paymentCheck->payer->payer_info->last_name;

                $odetails=$this->GetOrderDetails($order->order_id);

                $invoice_html= View::make('admin.orders.template.invoice')
                ->with('order', $odetails['order'])
                ->with('user', $odetails['user'])
                ->with('payments', $odetails['payments'])
                ->with('balance', $odetails['balance'])
                ->with('products', $odetails['products'])
                ->with('comments', $odetails['comments'])
                ->with('admin_comments', $odetails['admin_comments'])
                ->with('order_logs', $odetails['order_logs'])
                ->with('ord_status', $odetails['ord_status']);
                
                $detail['payerName']    = $payerFirstName.' '.$payerLastName;
                $detail['orderInfo']    = $orderInfo;
                $detail['invoice']      = $invoice_html;

                $to      = $payer_email;
                $from    = env('email_admin', '');
                $cc      = env('email_xolva_2').','.env('email_support_2');
                $subject = "Your Order at BenthamScience # " . $orderInfo;

                SendSmtpMail('email_template.paypal_order_successfull', $detail, $to, $from, $subject, 'Admin', $cc);


/*                $to               = env('email_xolva_2');                
                $subject          = "Paypal Payment Successful # " . $orderInfo;
                $html             = "Order#" . $orderInfo . " Paid successfully.";
                $data             = array('name' => "administer");
                $fromEmail        = $payer_email;
                $fromName         = "PPV Order";
                Mail::raw($html, function ($message) use ($html, $to, $subject, $fromEmail, $fromName) {
                    $message->from($fromEmail, $fromName);
                    $message->to($to);
                    $message->subject($subject);
                    $message->setBody($html, 'text/html'); // dont miss the '<html></html>' if the email dont contains it to decrease your spam score !!
                    //$message->addPart($plain, 'text/plain');
                });
*/
                Session::flash('success_msg', 'The Payment process was successfully completed');
                $PurchasedItems = session()->get('PurchasedItems');
                return view('cart.complete', with(['PurchasedItems' => $PurchasedItems, 'response_message' => $response_message, 'orderInfo' => $orderInfo, 'receiptNo' => $receiptNo, 'order' => $order, 'order_products' => $order_products, 'eGate' => $eGate]));

            }
        }

    }
    public function GetOrderDetails($order_id)
     {
        $balance=0;
        $paid_amounts=0;
        $order = Orders::GetOrder($order_id);
        $user = User::getUserById($order->uid);
        $products = Orders::GetOrderProducts($order_id);
        $payments = Orders::GetOrderPaymentReceipts($order_id);
        if($payments)
        {
          foreach($payments as $paid)
          {
            $paid_amounts=$paid_amounts+$paid->amount;
          }
          $balance=$order->order_total-$paid_amounts;
        }
        $comments = Orders::GetOrderComments($order_id);
        $admin_comments = Orders::GetOrderAdminComments($order_id);
        $order_logs = Orders::GetOrderLogs($order_id);
        $ord_status = Orders::GetOrderStatus();

        return with(['order' => $order,
                    'user' => $user,
                    'payments' => $payments,
                    'balance' => $balance,
                    'products' => $products,
                    'comments' => $comments,
                    'admin_comments' => $admin_comments,
                    'order_logs' => $order_logs,
                    'ord_status' => $ord_status]);
     }

    public function uc_cart_get_id($create = true)
    {

        $user = Auth::user();

        if ($user) {
            return $user->id;
        } elseif (!session()->has('uc_cart_id') && $create) {
            session(['uc_cart_id' => md5(uniqid(rand(), true))]);
        }
        
        return session()->has('uc_cart_id') ? session()->get('uc_cart_id') : false;

    }

    public function getuserdiscountcountrybyip()
    {
        $userip = $request->ip();
        //$userip='16779264';
        $query = "select * from ip2location_db5 where ip_from<='" . $userip . "' and ip_to>='" . $userip . "'";
        //echo $query;die;
        $result = db_query($query);
        $row    = db_fetch_object($result);

        if ($row->country_name != '-') {

            $user_country = $row->country_name;
            $query_coun   = "select * from country_discount where country='" . $user_country . "'";
            //echo $query_coun;die;
            $result_coun = db_query($query_coun);
            $row_coun    = db_fetch_object($result_coun);

            return $row_coun->dis_percentage;
        }

    }

    public function DownloadPurchasedItem(Request $request)
    {
        $index = $request->index;
        $supp  = $request->supp;

        if (isset($request->download_error)) {
            Session::flash('message', 'File does not exist at location');
        }

        $PurchasedItems = session()->get('PurchasedItems');
        
        return view('cart.downloadpurchaseditem', with(['PurchasedItems' => $PurchasedItems]));

    }

    public function Rating(Request $request)
    {

        $validator = Validator::make($request->all(),
            [
                'param'          => 'required',
                'rating'         => 'required',
                'ratingComments' => 'required',
            ]);

        if ($validator->fails()) {

            return array(false, $validator);
        } else {
            // try transaction start here for data integrity
            try
            {
                DB::beginTransaction();
                $order_id     = Crypt::decrypt($request->param);
                $order_id     = intval($order_id);
                $add_comments = array(
                    'order_id' => $order_id,
                    'rating'   => intval($request->get("rating")),
                    'comments' => $request->get("ratingComments"),
                    'added_on' => time(),
                    'added_by' => Auth::user()->id,
                );
                $count = DB::table('uc_order_rating_comments')->select('*')->where('order_id',$order_id)->where('added_by',Auth::user()->id)->count();
                if($count>0){
                    //Session::flash('message', 'You have already posted!');
                    //return Redirect::to('/download-purchased-items');
                }else{
                    Cart::AddOrderRatingComments($add_comments);
                    DB::commit();
                }
                

                Session::flash('message', 'Thank you for your feedback!');
                return Redirect::to('/download-purchased-items');

            } catch (Exception $e) {
                DB::rollback();
                Session::flash('message', 'Somthing wrong with this page. Please try again!');
                return Redirect::to('/download-purchased-items');
            }
        }
    }
}
