<?php

namespace App\Http\Controllers;

use App\Http\Controllers\MigsController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\PaypalExpress;
use App\Models\BundleOffer;
use App\Models\Log;
use App\Models\Country;
use App\Rules\Captcha;
use App\User;
use Auth;
use Cookie;
use DB;
use Hash;
use File;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Str;

class BundleOfferController extends BenthamController
{
    public function index(Request $request)
    {	
        $editPermission   = false;
        $deletePermission = false;

        $param['bundle_id']   				= $request->get('bundle_id');
        $param['bundle_name']   			= $request->get('bundle_name');
        $param['article_download_allow']   	= $request->get('article_download_allow');
        $param['ebook_download_allow']   	= $request->get('ebook_download_allow');
        $param['chapter_download_allow']   	= $request->get('chapter_download_allow');
        $param['price']   					= $request->get('price');
        $param['expiry']   					= $request->get('expiry');
        $param['paginate']					= true;

        $bundle_search = BundleOffer::GetBundleList($param);
        $bundles = BundleOffer::GetBundleList();
        if (checkPermission('bundle', 'edit')) {
            $editPermission = true;
        }if (checkPermission('bundle', 'delete')) {
            $deletePermission = true;
        }

        return View::make('admin.orders.bundle_offer_list', with(['bundle_search' => $bundle_search, 'bundles' => $bundles, 'param' => $param, 'editPermission' => $editPermission, 'deletePermission' => $deletePermission]));
    }

    public function create()
    {
        return View::make('admin.orders.bundle_form');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'bundle_name'   => 'required',
            'bundle_description'    => 'required',
            'article_download_allow'   => 'required',
            'ebook_download_allow'        => 'required',
            'chapter_download_allow' => 'required',
            'price'   => 'required',
            'expiry'    => 'required',
        ]);

        if (isset($validator)) 
        {
            if ($validator->fails())
            {
                return back()->withInput()->withErrors($validator); 
            }
        }
        // try transaction start here for data integrity
        try
        {
            DB::beginTransaction();

            $user=Auth::user();

            $add_bundle['bundle_name']				= $request->bundle_name;
            $add_bundle['bundle_description']		= $request->bundle_description;
            $add_bundle['article_download_allow']	= $request->article_download_allow;
            $add_bundle['ebook_download_allow']		= $request->ebook_download_allow;
            $add_bundle['chapter_download_allow']	= $request->chapter_download_allow;
            $add_bundle['price']					= $request->price;
            $add_bundle['expiry']           		= $request->expiry;
            $add_bundle['created_by']           	= $user->id;
            $add_bundle['created_on']          		= time();
            $add_bundle['updated_by']       		= $user->id;
            $add_bundle['updated_on']       		= time();
            $add_bundle['bundle_ip']				= ip2long($request->ip());


            $bundle_id = BundleOffer::AddBundleOffer($add_bundle);

            $add_log = array(
                'content_id'      => $bundle_id,
                'content_type_id' => config('constants.log_content_types.Bundle_Offer'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($add_bundle),
                'created_dated'   => time(),
                'created_by'      => $user->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);
            
            DB::commit();
        } catch (Exception $e) {

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

        return Redirect::to('admin/bundle_offer')->with('success', 'Bundle Offer has been added.');
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
		$param['bundle_id']=$id;
		$selected_bundle = BundleOffer::GetBundleList($param);
		$selected_bundle        = $selected_bundle[0];
        return View::make('admin.orders.bundle_form', with(['selected_bundle' => $selected_bundle]));
    }

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'bundle_name'   => 'required',
            'bundle_description'    => 'required',
            'article_download_allow'   => 'required',
            'ebook_download_allow'        => 'required',
            'chapter_download_allow' => 'required',
            'price'   => 'required',
            'expiry'    => 'required',
        ]);

        if (isset($validator)) 
        {
            if ($validator->fails())
            {
                return back()->withInput()->withErrors($validator); 
            }
        }
        // try transaction start here for data integrity
        try
        {
            DB::beginTransaction();

            $user=Auth::user();

            $update_bundle['bundle_name']				= $request->bundle_name;
            $update_bundle['bundle_description']		= $request->bundle_description;
            $update_bundle['article_download_allow']	= $request->article_download_allow;
            $update_bundle['ebook_download_allow']		= $request->ebook_download_allow;
            $update_bundle['chapter_download_allow']	= $request->chapter_download_allow;
            $update_bundle['price']						= $request->price;
            $update_bundle['expiry']           			= $request->expiry;
            $update_bundle['updated_by']       			= $user->id;
            $update_bundle['updated_on']       			= time();
            $update_bundle['bundle_ip']					= ip2long($request->ip());

            BundleOffer::UpdateBundleOffer($id,$update_bundle);

            $add_log = array(
                'content_id'      => $id,
                'content_type_id' => config('constants.log_content_types.Bundle_Offer'),
                'action'          => config('constants.log_action_types.update'),
                'log_data'        => json_encode($update_bundle),
                'created_dated'   => time(),
                'created_by'      => $user->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);
            
            DB::commit();
        } catch (Exception $e) {

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

        return Redirect::to('admin/bundle_offer')->with('success', 'Bundle Offer has been updated.');

    }

    public function destroy($id, Request $request)
    {
        try
        {
            DB::beginTransaction();

            $user=Auth::user();

            $update_bundle['bundle_status']          	= 'D';
            $update_bundle['updated_by']       			= $user->id;
            $update_bundle['updated_on']       			= time();
            $update_bundle['bundle_ip']					= ip2long($request->ip());

			$param['bundle_id']=$id;
			$selected_bundle = BundleOffer::GetBundleList($param);
			$selected_bundle        = $selected_bundle[0];

            BundleOffer::UpdateBundleOffer($id,$update_bundle);

            $add_log = array(
                'content_id'      => $id,
                'content_type_id' => config('constants.log_content_types.Bundle_Offer'),
                'action'          => config('constants.log_action_types.delete'),
                'log_data'        => json_encode($selected_bundle),
                'created_dated'   => time(),
                'created_by'      => $user->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);
            
            DB::commit();
        } catch (Exception $e) {

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

        return Redirect::to('admin/bundle_offer')->with('danger', 'Bundle Offer has been deleted.');
    }

	public function BundleOfferOrder(Request $request)
    {  
		if ($request->action == 'form')
		{
			return $this->BundleOfferOrderForm($request);
		}
		else if ($request->action == 'preview')
		{
			return $this->BundleOfferPreview($request);
		}
		else if ($request->action == 'submit')
		{
			return $this->BundleOfferSubmit($request);
		}
		else if ($request->action == 'migs-response')
		{
			return $this->BundleOfferOrderMigsResponse($request);
		}
        else if ($request->action == 'paypal-response')
        {
            return $this->BundleOfferOrderPaypalResponse($request);
        }
        else if ($request->action == 'reports')
        {
            return $this->BundleOfferOrderReports($request);
        }
        else if ($request->action == 'promotions')
        {
            return $this->BundleOfferPromotions($request);
        }

    }

	public function BundleOfferOrderForm(Request $request, $validator = null)
    {  	
		$param['bundle_id']=$request->bundle_id;
		$bundle = BundleOffer::GetBundleList($param);
		$bundle        = $bundle[0];

        $user = Auth::user();
        
        if (isset(Auth::user()->id)) 
        {    $session_detail = $request->session()->get('session_detail');
            $detail['display_name'] = isset($user->display_name) ? $user->display_name : '';
            $detail['email']    = isset($user->email) ? $user->email : '';
            $detail['country']  = isset($user->country) ? $user->country : '';
        } 
       elseif ($request->session()->has('session_detail')) {
            
            $session_detail = $request->session()->get('session_detail');
            
            $detail['display_name']  = isset($session_detail['display_name']) ? $session_detail['display_name'] : '';
            $detail['email']      = isset($session_detail['email']) ? $session_detail['email'] : '';
            $detail['country']      = isset($session_detail['country']) ? $session_detail['country'] : '';
            
        }
      else {
            $detail['display_name'] = '';
            $detail['email']   = '';
            $detail['user_type']='';
            $detail['password']='';
            $detail['password_confirmation']='';
            $detail['country']='';
        }

        $country        	= Country::GetCountryList();

        if (!empty($validator) && $validator->fails()) {
            return view('form.bundle_offer_order', with(['bundle' => $bundle, 'detail' => $detail, 'country' => $country]))->withErrors($validator);
        }
        else
        {
            return view('form.bundle_offer_order', with(['bundle' => $bundle, 'detail' => $detail, 'country' => $country]));
        }
    }

    public function BundleOfferPreview(Request $request)
    {   

		$param['bundle_id']=$request->bundle_id;
		$bundle = BundleOffer::GetBundleList($param);
		$bundle        = $bundle[0];

        $detail = array();
        if ($request->session()->has('session_detail')) {
            $session_detail = $request->session()->get('session_detail');
            $detail['display_name']  = isset($request->display_name) ? $request->display_name : $session_detail['display_name'];
            $detail['email']      = isset($request->email) ? $request->email : $session_detail['email'];
            $detail['country']      = isset($request->country) ? $request->country : $session_detail['country'];
            $country        = Country::GetCountryList("",$request->country);
            $detail['country_name']=ucfirst(strtolower($country->name));

        }else{
            $detail['display_name']  = isset($request->display_name) ? $request->display_name : '';
            $detail['email']      = isset($request->email) ? $request->email : '';
            $detail['country']      = isset($request->country) ? $request->country : '';
            $country        = Country::GetCountryList("",$request->country);
            $detail['country_name']=ucfirst(strtolower($country->name));

        }       
       
        $request->session()->forget('session_detail');        
        if(!empty($detail))
            session(['session_detail' => $detail]);

        return view('form.bundle_offer_preview', with(['bundle' => $bundle, 'detail' => $detail, 'country' => $country]));
    }
    
    public function BundleOfferSubmit(Request $request)
    {  
        
        $detail = array();
        $validator = Validator::make($request->all(),
            [
                'email'                => 'required|string|email|max:255',
                'g-recaptcha-response' => new Captcha(),
            ]);
        $user=Auth::user();
        $validator->after(function ($validator) use ($user) {
            $p['email'] = $user->email;
            $p['order_status']='C';
            $p['bundle_order_status']='C';
            $p['bundle_offer_expiry']=time();
            $order_exist     = BundleOffer::GetBundleOfferOrderDetail($p);

                $bundle_content = BundleOfferController::BundleOfferUserAccess($user->id);
                if(!empty($bundle_content))
                {
                    if ($bundle_content->article!=0 || $bundle_content->chapter!=0 || $bundle_content->ebook!=0) 
                    {
                        $validator->errors()->add('title', 'Bundle Already Exist');
                    }
                }


        });

        if (isset($validator)) 
        {
            if ($validator->fails())
            {   return $this->BundleOfferOrderForm($request, $validator);
                //return back()->withInput()->withErrors($validator); 
            }
        }


        try {// try transaction start here for data integrity
                DB::beginTransaction();


				$param['bundle_id']=$request->bundle_id;
				$bundle = BundleOffer::GetBundleList($param);
				$bundle        = $bundle[0];

                //-------------------Insert into rental order Table---------------
                $add_details['bundle_id']          			= $bundle->bundle_id;
                $add_details['article_download_allow']		= $bundle->article_download_allow;
                $add_details['ebook_download_allow']		= $bundle->ebook_download_allow;
                $add_details['chapter_download_allow']		= $bundle->chapter_download_allow;
                $add_details['price']          				= $bundle->price;
                $add_details['expiry']          			= $bundle->expiry;
                $add_details['user_name']           		= $user->display_name;
                $add_details['user_email']          		= $user->email;
                $add_details['user_country']        		= $user->country;
                $add_details['user_id']             		= $user->id;
                $add_details['guest']               		= $user->name;
                $add_details['created_on']          		= time();
                $add_details['last_modified']       		= time();
                $add_details['order_status']        		= 'I';
                $add_details['ip']                  		= ip2long(\Request::ip());
                $add_details['bundle_order_status']       		= 'I';

                $bundle_offer_order_id = BundleOffer::AddBundleOfferOrder($add_details);

                    $add_log = array(
                        'content_id'      => $bundle_offer_order_id,
                        'content_type_id' => config('constants.log_content_types.Bundle_Offer_Order'),
                        'action'          => config('constants.log_action_types.insert'),
                        'log_data'        => json_encode($add_details),
                        'created_dated'   => time(),
                        'created_by'      => $user->id,
                        'ip'              => ip2long($request->ip()),
                    );
                    $log = Log::AddLog($add_log);
        
                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }
//----------------------------MIGS Payment (Block Temparay)---------------------------------------
      $migs['merchat_id']         = env('migs_id');
        $migs['order_id']           = 'BO:' . $bundle_offer_order_id;
        $migs['amount']             = $bundle->price;
        $migs['currency_code']      = 'USD';
        $migs['return_url']         = "http://".$_SERVER['HTTP_HOST']."/bundle-offer-order/migs-response/". $migs['order_id'];   
        $migs['cancel_url']         = "http://".$_SERVER['HTTP_HOST']."/bundle-offer-order/migs-response/".$migs['order_id'];   

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

        return view('migs', with(['migs' => $migs]));
//-----------------------------------MIGS End-------------------------------
    //--------------------------Paypal Payment - Temparary Add Here-------------------------------
    /*     $paypal['paypalEnv']           = env('paypalEnv');
        $paypal['paypalURL']           = env('paypalURL');
        $paypal['invoice']            = 'BO:'. $bundle_offer_order_id;
        $paypal['item_name']          = 'Order# BUNDLE OFFER ORDER' . $bundle_offer_order_id;
        $paypal['amount']             = $bundle->price;
        $paypal['currency_code']      = 'USD';
        $paypal['paypalClientID']     = env('paypalClientID');
        $paypal['return']             = url("/bundle-offer-order/paypal-response/");
        
        return view('paypal', with(['paypal' => $paypal]));
     */
	 //--------------------------Paypal Payment - End Here-------------------------------
    } 

//-----------------------------------MIGS Payment Response---------------------------------------
    public function BundleOfferOrderMigsResponse(Request $request)
    {   
        $bundle_offer_order_id = substr($request->bundle_id, 3, strlen($request->bundle_id));

        $param['bundle_offer_order_id'] 	= $bundle_offer_order_id;
        $bundle_offer_order                 = BundleOffer::GetBundleOfferOrderDetail($param);
        $bundle=$bundle_offer_order         = $bundle_offer_order[0];

        $detail['order_id']             	= $bundle_offer_order->bundle_offer_order_id;
        $detail['display_name']         	= $bundle_offer_order->user_name;
        $detail['email']                	= $bundle_offer_order->user_email;
        $detail['country']              	= $bundle_offer_order->user_country;
        $detail['bundle_name']				= $bundle_offer_order->bundle_name;
        $detail['bundle_description']		= $bundle_offer_order->bundle_description;
        $detail['article_download_allow']	= $bundle_offer_order->article_download_allow;
        $detail['ebook_download_allow']		= $bundle_offer_order->ebook_download_allow;
        $detail['chapter_download_allow']	= $bundle_offer_order->chapter_download_allow;
        $detail['price']					= $bundle_offer_order->price;
        $detail['expiry']					= $bundle_offer_order->expiry;

        //-----------------migs reponse check---------------------------
        if($bundle_offer_order->order_status == 'C')
        {   
                return Redirect::to('/');
        }
        
        $migs_obj = new MigsController;
        $apiResponse = $migs_obj->TransactionMigsResponse($request->bundle_id);
        if($apiResponse->result=="SUCCESS")
        {
            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;
            
            try {// try transaction start here for data integrity
                    DB::beginTransaction();

                    $user=Auth::user();
                    $username = '';
                    $user_id=0;
                    if ($user)
                    {
                      $username = $user->name;  
                      $user_id = $user->id; 
                    }
                    else
                    {    
                        //if Doesnot exist than check/create new User
                        $user_details = (array) UserController::CheckAddUserDetails($bundle_offer_order);
                        $user_id = $user_details['id'];
                        if (isset($user_details['password_text']))
                        {
                            $detail['name'] = $user_details['name'];
                            $detail['password'] = $user_details['password_text'];

                            $user_data = array(
                                'name'  => $detail['name'],
                                'password' => $detail['password']
                            );

                            if(!Auth::attempt($user_data)){

                               return redirect()->back();
                            }

                            if ( Auth::check() ) {
                               // return redirect('users/details');
                            }                        
                        }
                        else
                        {
                            $detail['name'] = $user_details['name'];
                        }

                        $detail['display_name'] = $user_details['display_name'];
                        $detail['email'] = $user_details['email'];

                    }

                    $to      = $detail['email'];
                    $from    = env('email_admin', '');
                    $cc      = env('email_xolva_2').','.env('email_support_2');
                    $subject = "Bundle Offer Order Number # " . $bundle_offer_order_id . "";

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

                    $migs_transaction   = 'Success';
                    $update_bundle_offer_order['user_id'] = $user_id;
                    $update_bundle_offer_order['response_code'] = $txnResponseCode;
                    $update_bundle_offer_order['response_message'] = $plain_message;
                    $update_bundle_offer_order['transaction_no'] = $transactionNo;
                    $update_bundle_offer_order['email_status'] = 1;
                    $update_bundle_offer_order['order_status'] = "C";
                    $update_bundle_offer_order['bundle_order_status'] = "C";
                    $update_bundle_offer_order['last_modified'] = time();
                    $update_bundle_offer_order['bundle_offer_expiry'] = strtotime(date("Y-M-d h:i:s",+strtotime("+".$bundle_offer_order->expiry." month")));


                    BundleOffer::UpdateBundleOfferOrder($bundle_offer_order_id, $update_bundle_offer_order);
            
                    DB::commit();
                } catch (Exception $e) {

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

			return view('form.bundle_offer_preview', with(['bundle' => $bundle, 'detail' => $detail, 'migs_transaction' => $migs_transaction]));

                }
            } 
			}
        }
        elseif($apiResponse->result=="ERROR")
            {  
	            $migs_transaction = 'Cancel';
	            $update_bundle_offer_order['order_status'] = 'N';
	            $update_bundle_offer_order['bundle_order_status']       = 'N';
	            
	            BundleOffer::UpdateBundleOfferOrder($bundle_offer_order_id, $update_bundle_offer_order);

                $paypal['paypalEnv']           = env('paypalEnv');
                $paypal['paypalURL']           = env('paypalURL');
                $paypal['invoice']            = 'BO:'. $bundle_offer_order_id;
                $paypal['item_name']          = 'Order# BUNDLE OFFER ORDER' . $bundle_offer_order_id;
                $paypal['amount']             = $bundle_offer_order->price;
                $paypal['currency_code']      = 'USD';
                $paypal['paypalClientID']     = env('paypalClientID');
                $paypal['return']             = url("/bundle-offer-order/paypal-response/");


			return view('form.bundle_offer_preview', with(['bundle' => $bundle, 'detail' => $detail,'migs_transaction' => $migs_transaction, 'paypal' => $paypal]));
        }    
    }

    public function BundleOfferOrderPaypalResponse(Request $request)
    {  
    try {// try transaction start here for data integrity
        $paypal=array();

        DB::beginTransaction();

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

        // If the payment is valid and approved
        if($paymentCheck && $paymentCheck->state == 'approved')
        {

            $param['bundle_offer_order_id'] = $bundle_offer_order_id = substr($request->invoice, 3, strlen($request->invoice));
            $bundle_offer_order                 = BundleOffer::GetBundleOfferOrderDetail($param);
            $bundle=$bundle_offer_order         = $bundle_offer_order[0];

            $detail['order_id']             	= $bundle_offer_order->bundle_offer_order_id;
            $detail['display_name']         	= $bundle_offer_order->user_name;
            $detail['email']                	= $bundle_offer_order->user_email;
            $detail['country']              	= $bundle_offer_order->user_country;
            $detail['bundle_name']				= $bundle_offer_order->bundle_name;
            $detail['bundle_description']		= $bundle_offer_order->bundle_description;
            $detail['article_download_allow']	= $bundle_offer_order->article_download_allow;
            $detail['ebook_download_allow']		= $bundle_offer_order->ebook_download_allow;
            $detail['chapter_download_allow']	= $bundle_offer_order->chapter_download_allow;
            $detail['price']					= $bundle_offer_order->price;
            $detail['expiry']					= $bundle_offer_order->expiry;

            $user=Auth::user();
            $username = '';
            $user_id=0;

            if ($user)
            {
              $username = $user->name;  
              $user_id = $user->id;  
            }

            // Paypal Payment Done Successfully

            $to      = $detail['email'];
            $from    = env('email_admin', '');
            $cc      = env('email_xolva_2').','.env('email_support_2');
            $subject = "Bundle Offer Order Number # " . $bundle_offer_order_id . "";

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

            $paypal_transaction = 'Success';
            $update_bundle_offer_order['transaction_no'] = $paymentCheck->transactions[0]->related_resources[0]->sale->id;
            $update_bundle_offer_order['response_message']  =  $paymentCheck->state;
            $update_bundle_offer_order['response_code'] = 0;
            $update_bundle_offer_order['order_status']        = "C";
            $update_bundle_offer_order['bundle_order_status']        = "C";
            $update_bundle_offer_order['user_id'] = $user_id;
            $update_bundle_offer_order['bundle_offer_expiry'] = strtotime(date("Y-M-d h:i:s",+strtotime("+".$bundle_offer_order->expiry." month")));

        } else {
            $update_bundle_offer_order['response_code'] = "C";
            $update_bundle_offer_order['order_status']        = "F";
            $update_bundle_offer_order['bundle_order_status']        = "N";

            $update_bundle_offer_order['response_message']  =  'Transaction Failed with Paypal';
            $paypal_transaction = 'Failed';

        }
        
        BundleOffer::UpdateBundleOfferOrder($bundle_offer_order_id, $update_bundle_offer_order);
                
                DB::commit();
            } catch (Exception $e) {

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

	  return view('form.bundle_offer_preview', with(['bundle' => $bundle, 'detail' => $detail, 'paypal' => $paypal, 'paypal_transaction' => $paypal_transaction]));
    } 

    public function BundleOfferOrderReports(Request $request)
    {   
        $param['bundle_id']                 = $request->get('bundle_id');
        $param['bundle_name']               = $request->get('bundle_name');
        $param['article_download_allow']    = $request->get('article_download_allow');
        $param['ebook_download_allow']      = $request->get('ebook_download_allow');
        $param['chapter_download_allow']    = $request->get('chapter_download_allow');
        $param['price']                     = $request->get('price');
        $param['expiry']                    = $request->get('expiry');
        $param['user_name']                 = $request->get('user_name');
        $param['order_status']              = $request->get('order_status');
        $param['paginate']                  = true;

        $bundles = BundleOffer::GetBundleList();
        $bundle_order = BundleOffer::GetBundleOfferOrderDetail($param);
        
        if(!empty($bundles))
        {   $a=0;
            foreach($bundle_order as $bo)
            {
                $bundle['bundle_offer_order_id'] = $bo->bundle_offer_order_id;
                $bundle_count = BundleOffer::GetBundleOfferContentCount($bundle);
                
                $bundle_order->items()[$a]->article = $bundle_count[0]->article;
                $bundle_order->items()[$a]->chapter = $bundle_count[0]->chapter;
                $bundle_order->items()[$a]->ebook = $bundle_count[0]->ebook;
                $a++;
            }
        }

        if($request->ajx_search == true)
        {
            $param['bundle_offer_order_id'] = $request->get('bundle_offer_order_id');
            $bundle_content= BundleOffer::GetBundleOfferOrderContent($param);
            if(count($bundle_content) > 0)
            {
                return response()->json($bundle_content, 200);
            }
            else
            {
                return response()->json(false, 200);
            }
        }

        //$bundle_content= BundleOffer::GetBundleOfferOrderContent();
        //dd($bundle_content);
        return View::make('admin.orders.bundle_offer_order_list', with(['bundles' => $bundles, 'bundle_order' => $bundle_order, 'param' => $param]));
    }

    public function BundleOfferPromotions(Request $request)
    {   
        $bundle_offers   = BundleOffer::GetBundleList();
        return View::make('promotions', with(['bundle_offers' => $bundle_offers]));
    }
            //--------------User Bundle Access Check-----------------------
    public static function BundleOfferUserAccess($user_id)
    {   
        $sparam['user_id']      = $user_id;
        $sparam['order_status']      = 'C';
        $sparam['bundle_order_status']='C';
        $sparam['bundle_offer_expiry']=time();

        $bundle_offer_detail = BundleOffer::GetBundleOfferOrderDetail($sparam);
		$bundle_content['article']=0;
        $bundle_content['chapter']=0;
        $bundle_content['ebook']=0;

        if(isset($bundle_offer_detail[0]))
        { 
           $bundle_offer_detail = $bundle_offer_detail[0]; 

           $bundle['bundle_offer_order_id'] = $bundle_offer_detail->bundle_offer_order_id;
           $bundle['article_download_allow'] = $bundle_offer_detail->article_download_allow;
           $bundle['ebook_download_allow'] = $bundle_offer_detail->ebook_download_allow;
           $bundle['chapter_download_allow'] = $bundle_offer_detail->chapter_download_allow;
           
           $bundle_count = BundleOffer::GetBundleOfferContentCount($bundle);

           if($bundle_count[0]->article < $bundle['article_download_allow'])
                $bundle_content['article']=1;
           
           if($bundle_count[0]->chapter < $bundle['chapter_download_allow'])
                $bundle_content['chapter']=1;

           if($bundle_count[0]->ebook < $bundle['ebook_download_allow'])
                $bundle_content['ebook']=1; 
            $bundle_content['bundle_offer_order_id']=$bundle['bundle_offer_order_id'];
            $bundle_content['content_download_type']='B';
            $bundle_content=(object)$bundle_content;
            
            return $bundle_content;
        }else{
            $bundle_content=(object)$bundle_content;      
            return $bundle_content;
        }
    }
 }