<?php

use Rush\Transformers\BusinessTransformer;
use Rush\Transformers\ActiveOrderTransformer;
use Carbon\Carbon;
use Rush\Services\SmartFreight as SmartFreight;
use Rush\Services\MailChimpSerivce as MailChimpSerivce;
use Rush\Services\MandrillService as MandrillService;
use Rush\Services\WaybillTrackingService as WaybillTrackingService;
//use Rush\Services\NucleusService as NucleusService;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Illuminate\Http\Request;

class BusinessController extends ApiController {

    /**
     * @var Rush\Transformers\BusinessTransformer
     */
    protected $businessTransformer;

    /**
     * @var Rush\Newsletters\NewsletterList
     */
// protected $newsletterList;

    /**
     * Construct Function.
     *
     * @param AccountTransformer $businessTransformer
     */
// function __construct(AccountTransformer $businessTransformer, NewsletterListServiceProvider $newsletterList)
    function __construct(BusinessTransformer $businessTransformer) {
        $this->businessTransformer = $businessTransformer;
// $this->newsletterList 		= $newsletterList;
    }

    public function login() {
//Declare the rules for the form validation
        $rules = array(
            'email' => 'required|email',
            'password' => 'required|between:3,32',
        );

// Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $rules);

// If validation fails, we'll exit the operation now.
        if ($validator->fails()) {
// Ooops.. something went wrong
            return $this->respondWithUnauthorized('You email or password are not valid.');
        }

        try {
            $userdata = array(
                'email' => Input::get('email'),
                'password' => Input::get('password')
            );

// Try to log the user in
            Sentry::authenticate($userdata, false);

            $user = Sentry::getUser();
            $acc = Sentry::findGroupByName('Accounts');
            $cookie = Cookie::make('name', 'value', 60);

// Talhah Testing
// Log::info('USER: '.json_encode($user));
// Log::info('ACCOUNT: '.json_encode($acc));
// Log::info('USER IN GROUP: '.json_encode($user->inGroup($acc)));

            if ($user->inGroup($acc)) {
                $user->account = Account::userbyid($user->id)->get()->toArray();
                $user->accountService = AccountService::AccountId($user->account[0]['id'])->get()->toArray();
                $user->business = Business::Accountbyid($user->account[0]['id'])->get()->toArray();

                if (sizeof($user->business) > 0) {
                    $token = Token::create([
                                'user_id' => $user->id,
                                'api_token' => hash('sha256', Str::random(10), false),
                                'client' => BrowserDetect::toString(),
                                'expires_on' => Carbon::now()->addHours(10)->toDateTimeString(),
                    ]);

                    return $this->respond([
                                'data' => [
                                    'token' => $token['api_token'],
                                    'user' => Sentry::getUser()
                                ]
                    ]);
                } else {
                    Sentry::logout();
                    return $this->respondWithUnauthorized('Unauthorized');
                }
            } else {
                Sentry::logout();
                return $this->respondWithUnauthorized('Unauthorized');
            }
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {

            return $this->respondWithUnauthorized('Username or password is incorrect.');
        } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) {

            return $this->respondWithUnauthorized('User account is not activated. Please check your inbox for activation email.');
        } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) {

            return $this->respondWithUnauthorized('User has been suspended.');
        } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) {

            return $this->respondWithUnauthorized('User has been banned.');
        }

//something went wrong
        return $this->respondInternalError('Internal error, something has gone wrong when trying to login');
    }

    public function forgot_password() {

    }

    /**
     * Logout of CMS and for Account System
     *
     * @return json
     */
    public function logout() {
        $user = Sentry::getUser();
        $affectedRows = Token::where('user_id', '=', $user->id)->delete();
        Sentry::logout();

        if (!Sentry::check())
            return $this->respond([
                        'data' => [
                            'message' => 'User successfully logged out.'
                        ]
            ]);

//something went wrong
        return $this->respondInternalError('Internal error, something has gone wrong when trying to logout');
    }

    public function registration() {
        $rules = [
            'title' => ['required', 'min:2'],
            'name' => ['required', 'min:2'],
            'surname' => ['required', 'min:2'],
            'email' => ['required', 'email'],
//            'id_number' => ['required', 'min:1'],
            'mobile' => ['required', 'min:1'],
            'province' => ['required', 'min:2'],
            'password_1' => ['required', 'min:1'],
            'accept_terms' => ['required'],
            'notify' => ['required']
//            ,
//            'lineOne' => ['required'],
//            'suburb' => ['required'],
//            'state' => ['required'],
//            'postcode' => ['required']
// 'company'			=> ['min:1'],
// 'jobTitle' 			=> ['min:1'],
// 'companyAddress'	=> ['min:10'],
// 'companyVat' 		=> ['regex:/((19|20)[\d]{2}/[\d]{6}/[\d]{2})/'],
// 'company_int_code' 	=> ['min:2'],
// 'companyNumber'	 	=> ['regex:/(0)[1-9]{2}(\d{7})/'],
        ];

        $postData = Input::all();

        $validator = Validator::make($postData, $rules);

        if ($validator->fails()) {

            Log::info($validator->messages());
// return $this->respondWithUnpro cessable($validator->messages());
            return $this->respondWithUnprocessable('Account could not be created. As your details failed validation rules.');
        }

        if (!isset($postData["int_code_mobile"])) {
            $postData["int_code_mobile"] = array("value" => "+27 (0)");
        }
        if (!isset($postData["int_code_landline"])) {
            $postData["int_code_landline"] = array("value" => "+27 (0)");
        }
        if (!isset($postData["company_int_code"])) {
            $postData["company_int_code"] = array("value" => "+27 (0)");
        }

        /** Create account user using sentry */
        $userCreated = $this->registerUser($postData);

        if (isset($userCreated['data']['user_id']) && is_numeric($userCreated['data']['user_id'])) {

            try {
                // Create user in the accounts table
                $data = $this->createAccountArray($postData, $userCreated['data']['user_id']);
                $account = Account::create($data);

                if (isset($postData['vodacom']) && $postData['vodacom'] == 'vodacom') {

                    $account->vodacom_user = 1;
                    $account->margin_mgmnt_groups_id = 6;
                    $account->save();

                    if (isset($postData['promocode'])) {
                          //update promocode - one time use .
                          $promocode = PromoCode::find($postData['promocode']);

                          if (!$promocode) {
                              return $this->respondNotFound('Promo code does not exist.');
                          }

                          $promocode->status = 1;
                          $promocode->email = $postData['email'];
                          $promocode->date_used =  Carbon::now()->toDateTimeString();
                          $promocode->save();

                          $account->margin_mgmnt_groups_id = 1;
                          $account->save();

                          Log::info('Promo code entry for user id '.  $userCreated['data']['user_id'].  'with promocode'.$promocode['promo_code']);

                      }
                }

                if (isset($postData['vodacom']) && $postData['vodacom'] == 'cbre') {
                    $account->cbre_customer_number = $postData['cbre'];
                    $account->save();
                }


// Create user in the business table
                $business = Business::create($this->createBusinessArray($postData, $account->id));

                $data['notify'] ? $this->newsletterSubscription('website_account_user', $data['notify'], $postData['email']) : '';

                $registration_log = new Logger('WebsiteRegistration');
                $registration_log->pushHandler(new StreamHandler(storage_path() . '/logs/users_website_registration.log', Logger::INFO));
                $registration_log->addInfo("Website User Registration. Account: " . $account);

                return $this->respond([
                            'data' => $this->businessTransformer->transform($account),
                          'message' =>  "<p style='font-weight:bold;'>Thank you for registering with us!</p>
                                          <p style='font-size: medium;'>Please check your inbox for an email containing a link to validate your registration.
                                          You&apos;ll be able to log in after activation.</p>
                                          <p style='font-size: medium;'>Be sure to check your spam or junk mail folders and if you haven&apos;t received your email within 30 minutes, please contact <b><a href='mailto:help@rush.co.za' style='text-decoration: underline;'>help@rush.co.za</a></b> for assistance.</p>
                                         "
                    ]);
            } catch (PDOException $e) {
// Need to log this error somewhere.
                Bugsnag::notifyException(new Exception("Create Account: " . $e->getMessage()));
                Log::info($e->getMessage());
                return $this->respondInternalError('Internal Error. Could not create account.');
// return $this->respondInternalError([$e->getMessage(),$data]);
            }
        }

        return $this->respondWithUnprocessable($userCreated['error']['message']);
    }

    /**
     * [registerUser description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    private function registerUser($data) {
        try {
            /** Accounts Group */
            $userGroup = Sentry::getGroupProvider()->findByName('Accounts');

// Let's register a user.
            $user = Sentry::register($this->createUserArray($data));

            /** Add Accounts group to user */
            $user->addGroup($userGroup);
            $activationCode = $user->getActivationCode();
            $mandrill = new MandrillService();
            $sendActivationEmail = $mandrill->sendActivationEmail($data, $activationCode, $user->id);
            $sendRegistrationEmail = $mandrill->sendRegistrationEmail($data);

// Return a success
            return [
                'data' => [
                    'user_id' => $user->id,
                    'message' => 'Successfully created user.'
                ]
            ];
        } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) {
            return [
                'error' => [
                    'message' => 'Login field is required.'
                ]
            ];
        } catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) {
            return [
                'error' => [
                    'message' => 'Password field is required.'
                ]
            ];
        } catch (Cartalyst\Sentry\Users\UserExistsException $e) {
            return [
                'error' => [
                    'message' => 'User with this login already exists.'
                ]
            ];
        }
    }

    /**
     * [createUserArray description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    private function createUserArray($data) {
        $user = [
            'email' => $data['email'],
            'password' => $data['password_1'],
            'first_name' => $data['name'],
            'last_name' => $data['surname'],
            'activated' => 0
        ];

        return $user;
    }

    /**
     * [createAccountArray description]
     * @param  [type] $data    [description]
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    private function createAccountArray($data, $user_id) {
// echo "<pre>".print_r($data, true)."</pre>";
        $account = [
            'user_id' => $user_id,
            'title' => $data['title']['value'],
            'name' => $data['name'],
            'surname' => $data['surname'],
            'id_number' => isset($data['id_number']) ? $data['id_number'] : '' ,
            'province' => $data['province']['value'],
            'mobile_number' => $data['int_code_mobile']['value'] . ltrim($data['mobile'], '0'),
            'landline' => isset($data['landline']) ? $data['int_code_landline']['value'] . ltrim($data['landline'], '0') : '',
            'company' => isset($data['company']) ? $data['company'] : '',
            'job_title' => isset($data['jobTitle']) ? $data['jobTitle'] : '',
            'physical_address' => isset($data['companyAddress']) ? $data['companyAddress'] : '',
            'company_vat' => isset($data['companyVat']) ? $data['companyVat'] : '',
            'company_landline' => isset($data['companyNumber']) ? $data['company_int_code']['value'] . ltrim($data['companyNumber'], '0') : '',
            'notify' => (boolean) $data["notify"],
            'accept_terms' => (boolean) $data["accept_terms"],
            'store_payment' => (boolean) $data["store_payment"],
            'user_type' => 3,
            'otherTitle' => isset($data['otherTitle']) ? $data['otherTitle'] : '',
            'hearAboutUs' => isset($data['aboutUs']['value']) ? $data['aboutUs']['value'] : '',
            'OtherHearAboutUs' => isset($data['otherAboutUs']) ? $data['otherAboutUs'] : '',
            'lineOne' => isset($data['lineOne']) ? $data['lineOne'] : '',
            'lineTwo' => isset($data['lineTwo']) ? $data['lineTwo'] : '',
            'suburb' => isset($data['suburb']) ? $data['suburb'] : '',
            'state' => isset($data['state']) ? $data['state'] : '',
            'postcode' => isset($data['postcode']) ? $data['postcode'] : ''
        ];
// dd($account);
        return $account;
    }

    /**
     * [createBusinessArray description]
     * @param  [type] $data       [description]
     * @param  [type] $account_id [description]
     * @return [type]             [description]
     */
    private function createBusinessArray($data, $account_id) {
        $business = [
            "account_id" => $account_id,
        ];
        return $business;
    }

    /**
     * [newsletterSubscription description]
     * @param  [type] $listName [description]
     * @param  [type] $notify   [description]
     * @param  [type] $email    [description]
     * @return [type]           [description]
     */
    private function newsletterSubscription($listName, $notify, $email) {
// $method = $notify? 'subscribeTo': 'unsubscribeFrom';
// $this->newsletterList->{$method}($listName, $email);
// Send activation code to the user so he can activate the account
// Intiate Mandrill Service & send email
        $mailchimp = new MailChimpSerivce();
        if ($notify) {
            $subscribe = $mailchimp->subscribeTo($listName, $email);
        } else {
            $unsubscribe = $mailchimp->unsubscribeFrom($listName, $email);
        }
    }

    /**
     * Create a Reset password Code and email it to the user with instructions and a link.
     *
     * @return json
     */
    public function createResetPasswordCode() {
//Declare the rules for the form validation
        $rules = array(
            'email' => 'required|email'
        );

// Create a new validator instance from our validation rules
        $postData = Input::all();
        $validator = Validator::make($postData, $rules);

// If validation fails, we'll exit the operation now.
        if ($validator->fails()) {
// Ooops.. something went wrong
            return $this->respondWithUnprocessable('Your are required to have user a valid email address.');
        }

        try {
// Find the user using the user email address
            $user = Sentry::findUserByLogin($postData['email']);
            $postData['name'] = $user->first_name;

// Get the password reset code
            $resetCode = $user->getResetPasswordCode();

// Send Email with reset password and password page link.
// Check if this has been sent.
            $mandrill = new MandrillService();
            $sendActivationEmail = $mandrill->sendResetPasswordEmailForBusinessUser($postData, $resetCode, $user->id);

            return $this->respond([
                        'data' => [
                            'message' => 'Check your email, reset password email has been sent to you.'
                        ]
            ]);

// Now you can send this code to your user via email for example.
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
            return $this->respondWithUnprocessable('User was not found.');
        }

//something went wrong
        return $this->respondInternalError('Internal error, something has gone wrong when trying to send you a reset password.');
    }


        /**
         * Create a Reset password Code for mobile and email it to the user with instructions and a link.
         *
         * @return json
         */
        public function createMobileResetPasswordCode() {
    //Declare the rules for the form validation
            $rules = array(
                'email' => 'required|email'
            );

    // Create a new validator instance from our validation rules
            $postData = Input::all();
            $validator = Validator::make($postData, $rules);

    // If validation fails, we'll exit the operation now.
            if ($validator->fails()) {
    // Ooops.. something went wrong
                return $this->respondWithUnprocessable('Your are required to have user a valid email address.');
            }

            try {
    // Find the user using the user email address
                $user = Sentry::findUserByLogin($postData['email']);
                $username = $user->first_name;

    // Get the password reset code
                //$resetCode = $user->getResetPasswordCode();
                $string = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $string_shuffled = str_shuffle($string);
                $resetCode = substr($string_shuffled, 1, 7);

                $user->reset_password_code = $resetCode;
                $user->save();

    // Send Email with reset password and password page link.
    // Check if this has been sent.
                $mandrill = new MandrillService();
                $sendActivationEmail = $mandrill->sendResetPasswordEmailForMobileUser($postData,$username, $resetCode, $user->id);

                return $this->respond([
                            'data' => [
                                'message' => 'Check your email, reset password email has been sent to you.'
                            ]
                ]);

    // Now you can send this code to your user via email for example.
            } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
                return $this->respondWithUnprocessable('User was not found.');
            }

    //something went wrong
            return $this->respondInternalError('Internal error, something has gone wrong when trying to send you a reset password.');
        }

    /**
     * Reset account Password
     *
     * @return json
     */
    public function resetAccountPassword() {

//Declare the rules for the form validation
        $rules = array(
            'id' => 'required',
            'reset_code' => 'required',
            'password_1' => 'required',
            'password_2' => 'required'
        );

// Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $rules);

// If validation fails, we'll exit the operation now.
        if ($validator->fails()) {
// Ooops.. something went wrong
            return $this->respondNotFound('Your are required to have user id, reset code and new password.');
        }

        try {
// Find the user using the user id
            $user = Sentry::findUserById(Input::get('id'));

// Check if the reset password code is valid
            if ($user->checkResetPasswordCode(Input::get('reset_code'))) {
// Attempt to reset the user password
                if ($user->attemptResetPassword(Input::get('reset_code'), Input::get('password_1'))) {
                    return $this->respond([
                                'data' => [
                                    'user_id' => Input::get('id'),
                                    'message' => 'Account password has been reset.'
                                ]
                    ]);
                } else {
                    return $this->respondWithUnprocessable('Password reset failed.');
                }
            } else {
                return $this->respondWithUnprocessable('The provided password reset code is Invalid.'); //
            }
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
            return $this->respondWithUnprocessable('User was not found.');
        }

//something went wrong
        return $this->respondInternalError('Internal error, something has gone wrong when trying to reset your account password.');
    }

    /**
     * Reset Mobile account Password
     *
     * @return json
     */
    public function resetMobileAccountPassword() {

//Declare the rules for the form validation
        $rules = array(
            'email' => 'required',
            'reset_code' => 'required',
            'password_1' => 'required'

        );

// Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $rules);

// If validation fails, we'll exit the operation now.
        if ($validator->fails()) {
// Ooops.. something went wrong
            return $this->respondNotFound('Your are required to have an email, reset code and new password.');
        }

        try {
// Find the user using the user id
            $user = Sentry::findUserByLogin(Input::get('email'));
            $user_id = $user->id;

// Check if the reset password code is valid
            if ($user->checkResetPasswordCode(Input::get('reset_code'))) {
// Attempt to reset the user password
                if ($user->attemptResetPassword(Input::get('reset_code'), Input::get('password_1'))) {
                    return $this->respond([
                                'data' => [
                                    'user_id' => $user_id,
                                    'message' => 'Account password has been reset.'
                                ]
                    ]);
                } else {
                    return $this->respondWithUnprocessable('Password reset failed.');
                }
            } else {
                return $this->respondWithUnprocessable('The provided password reset code is Invalid.'); //
            }
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
            return $this->respondWithUnprocessable('User was not found.');
        }

//something went wrong
        return $this->respondInternalError('Internal error, something has gone wrong when trying to reset your account password.');
    }


    /**
     * [getUsers description]
     * @return [type] [description]
     */
    /*public function getBusinessUsers() {

        $accounts = DB::table('accounts')
                ->join('users', 'users.id', '=', 'accounts.user_id')
                ->select(DB::raw("accounts.id, accounts.user_id, accounts.name AS first_name, accounts.surname AS last_name, users.email, users.activated AS active_account, (CASE WHEN(accounts.user_type = 4) THEN 'true' ELSE 'false' END) as active_businessplus, accounts.eligible_voucher, accounts.active_ecommerce"))
                ->get();

        return $accounts;
    }*/
    public function getbuisnessusers()
    {
        //datatable request variables 
        $start      = Input::get('start');
        $length     = Input::get('length');
        $order_arr  = Input::get('order');
        $order_col  = $order_arr[0]['column'];
        $order_val  = $order_arr[0]['dir'];
        $search_arr = Input::get('search');
        $search_text  = $search_arr['value'];

        switch($order_col)
        {
            case 0:
                $order_col = 'id';
                break;
            case 0:
                $order_col = 'first_name';
                break;
            case 0:
                $order_col = 'last_name';
                break;
            case 0:
                $order_col = 'email';
                break;
            default:
                $order_col = 'id';
                break; 
        }        

        $accounts = Account::with('user')
            ->select('accounts.*')
            ->whereIn('user_type',['3','4'])
            ->join('users', 'users.id', '=', 'accounts.user_id');

        if($search_text){
            $accounts = $accounts->Where('users.id', 'like', '%'.$search_text.'%')
                            ->orWhere('users.first_name', 'like', '%'.$search_text.'%')
                            ->orWhere('users.last_name', 'like', '%'.$search_text.'%')
                            ->orWhere('users.email', 'like', '%'.$search_text.'%')
                            ->skip($start)
                            ->take($length)
                            ->get();
        } else {
            $accounts = $accounts->orderBy('users.'.$order_col, $order_val)
                                ->skip($start)
                                ->take($length)
                                ->get();
        }
            
        

        return $this->respond([
            "data" => $this->businessTransformer->transformCollection($accounts->toArray())
        ]);
    }

    public function getUsers() {

        $accounts = Account::with('user')->where('user_type', '=', '3')
                ->orWhere('user_type', '=', '4')
                ->get();
        $data = $this->businessTransformer->transformCollection($accounts->toArray());

        $tst = new Excel();
        $tst::create('Rush_users', function($excel) use($data) {
            $excel->sheet('Rush_users', function($sheet) use($data) {
                // $lastRownum = count($items) + 1;
                // $totalWalletAmountCell = $lastRownum + 1;

                $sheet->fromArray($data);
                // $sheet->setCellValue('H' . $totalWalletAmountCell, '=SUM(H2:H' . $lastRownum . ')');
            });
        })->store('xls');

        return "Rush_users";
//        return $this->respond([
//                    "data" => $this->businessTransformer->transformCollection($accounts->toArray())
//        ]);
    }

    public function payUCancelOrder() {
        $postData = Input::all();

        $id = $postData['orderId'];
        $payUReference = $postData['payUReference'];
        Log::info("[BusinessController: payUCancelOrder] Process: cancelling for orderId=" . $id . " and payUReference=" . $payUReference);

// Make sure id is not blank
        if (!$id) {
            return $this->respondNotFound('Missing order id');
        }

        $orders = Order::find($id);
        $payulog = PayULog::OrderId($id)->get()->toArray();

        if (!$payulog && !$orders) {
            return $this->respondNotFound('No payulog can be found.');
        } else {
//Log::info("[BusinessController: payUCancelOrder] Process: checking match from PayULog for orderId = " . $payulog['0']['order_id'] . " and payUReference = " . $payulog['0']['payu_reference']);
//Log::info("[BusinessController: payUCancelOrder] Process: PayULog_Reference(" . $payulog['0']['payu_reference'] . ") equals PayU_ReferencePost (" . $payUReference . ")");
            if ($payulog['0']['payu_reference'] != $payUReference) {
                return $this->respondNotFound('Order details do not matched.');
            }
        }

        try {
// Change order status to cancelled
            $orders->status = Order::$statusTypes['Cancelled'];
            $orders->save();
            $orders_updated = Order::find($id);

// Check it has changed
            if ($orders_updated->status == Order::$statusTypes['Cancelled']) {
                Log::info("[BusinessController: payUCancelOrder] Result: cancelled orderId=" . $id);
                return $this->respond([
                            'id' => $id,
                            'msg' => 'Successfully cancelled order id: ' . $orders_updated->id,
                            'order' => $orders_updated,
                ]);
            } else {
                Log::info("[BusinessController: payUCancelOrder] Result: failed to cancel orderId = " . $id . ". Status: " . $orders_updated->status);
                return $this->respondWithError([
                            'id' => $id,
                            'msg' => 'Failed to cancel order id: ' . $orders_updated->id . ". Status: " . $orders_updated->status,
                ]);
            }
        } catch (Exception $e) {
// If has not changed the throw internal error
//Log::info($e->messages());
            return $this->respondInternalError('Internal Error. Could not continue with cancellation of order.');
        }
    }

    public function trackConnoteNumber() {



        $rules = array(
            'connoteId' => 'required',
            'carrier' => 'required'
        );

// Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $rules);

// If validation fails, we'll exit the operation now.
        if ($validator->fails()) {
// Ooops.. something went wrong
            return $this->respondNotFound([
                        'message' => 'Your are required to have waybill number and carrier name.'
            ]);
        }

        $track = new WaybillTrackingService();
        $postData = Input::all();

        $connoteNumber = $postData["connoteId"];

        if ($connoteNumber) {
            //$order = Order::getRushWaybill($connoteNumber)->get()->toArray();
//            if (!$order) {
//                return $this->respondInternalError([
//                            'message' => "Your connote/ waybill number is invalid."]);
//            } else {
            $carrier = $postData["carrier"];

            $carrier_logo = DB::table('partners')
                    ->select('logo')
                    ->where('id', '=', $carrier)
                    ->get();

            switch ($carrier) {
                case 1 :
                case 'THE COURIER GUY':
                    $response = $track->Track(1, $connoteNumber, false);
                    break;
                case 5 :
                case 'GLOBE FLIGHT':
                    $response = $track->Track(2, $connoteNumber, false);
                    break;
                case 10 :
                case 'DSV Road':
                    $response = $track->Track(3, $connoteNumber, false);
                    break;
                case 9 :
                case 'DCB LOGISTICS':
                    $response = $track->Track(4, $connoteNumber, false);
                    break;
                case 3 :
                case 'COURIER IT':
                    $response = $track->Track(5, $connoteNumber, false);
                    break;
                case 4 :
                case 'SKYNET':
                    $response = $track->Track(6, $connoteNumber, false);
                    break;
                case 7 :
                case 'ROAD TRIP':
                    $response = $this->trackRoadTrip($connoteNumber);
                    break;
                default:
                    echo 'None';
            }


            if (isset($response['Status']) && $response['Status'] == 3) {
                return $this->respondInternalError(array('message' => 'Your Carrier Service Cannot be reached. Please try again later.', 'Status' => 3));
            } elseif (isset($response['Tracking_Code'])) {
                return $this->respond(['Response' => $response, 'Carrier' => $carrier, 'Carrier_logo' => $carrier_logo, 'Status' => 5, 'Url' => "http://www.smartfreight.com/tracking/" . $response['Tracking_Code']]);
            } elseif (isset($response['Error'])) {
                return $this->respondInternalError(array('message' => $response['Error']));
            } else {
                return $this->respond(['Response' => $response, 'Carrier' => $carrier, 'Carrier_logo' => $carrier_logo]);
            }
//                return $this->respond(['Response' => $response, 'Carrier' => $carrier, 'Carrier_logo' => $carrier_logo]);
//
//                $trackingCode = $order['0']['tracking_code'];
        }
//        }
        return $this->respondInternalError([
                    'message' => "Your connote/ waybill number is empty."]);
    }

    public function trackRoadTrip($waybill) {
        $order = Order::getRushWaybill($waybill)->get()->toArray();
        if ($order) {
            $trackingCode = $order[0]['tracking_code'];

            return array('Tracking_Code' => $trackingCode);
        } else {
            return array('Error' => 'Not a Rush Waybill.');
        }
    }

    public function setWalletPayU() {
        $postData = Input::all();
        $account_id = $postData['accountId'];
        $wallet_transaction_id = $postData['walletTransactionId'];

        $account = Account::find($account_id);
        if (!($account->store_payment) || $account->store_payment === 'undefined' || $account->store_payment == 0) {
            return $this->setWalletRPPPayU($account_id, $wallet_transaction_id);
        } else if ($account->store_payment == 1) {
            return $this->setWalletRTRRPPPayU($account_id, $wallet_transaction_id);
        }
    }

    private function setWalletRPPPayU($account_id, $wallet_transaction_id) {
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        ob_start();

        /** Start Configuration */
        $baseUrl = Config::get('payuConfig.wallet_payu_rpp.baseUrl'); //environment URL
        $soapWdslUrl = Config::get('payuConfig.wallet_payu_rpp.wsdlUrl');
        $payuRppUrl = Config::get('payuConfig.wallet_payu_rpp.redirectUrl');
        $apiVersion = Config::get('payuConfig.wallet_payu_rpp.apiVersion');
        $doAutoRedirectToPaymentPage = Config::get('payuConfig.wallet_payu_rpp.redirect'); //set value != 1 if you dont want to auto redirect topayment page

        /** Store config details */
        $safeKey = Config::get('payuConfig.wallet_payu_rpp.safeKey');
        $soapUsername = Config::get('payuConfig.wallet_payu_rpp.username');
        $soapPassword = Config::get('payuConfig.wallet_payu_rpp.password');
        /** End Store config details */
        $cancelUrl = Config::get('payuConfig.wallet_payu_rpp.cancelUrl');
        $returnUrl = Config::get('payuConfig.wallet_payu_rpp.returnUrl');
        $transaction_type = Config::get('payuConfig.wallet_payu_rpp.transactionType');
        $supported_payment_methods = Config::get('payuConfig.wallet_payu_rpp.supportedPaymentMethods');

        $managedBy = Config::get('payuConfig.wallet_payu_rpp.managedBy');
        $redirectUrl = Config::get('payuConfig.wallet_payu_rpp.redirectUrl');
        /**  End Configuration  */
        $account = Account::with('user')->find($account_id);
        $walletTransaction = WalletTransactions::find($wallet_transaction_id);
        if (!$walletTransaction) {
            return $this->respondInternalError([
                        'message' => "Your Refill Wallet could not proceed. Please try again.",
                        'response_error' => 'Error: PayU failure!'
            ]);
        }

        /** Start Customer & Basket */
        $current_user_id = $account['user_id'];
        $strEmail = $account['user']['email'];
        $strFirstname = $account['name'];
        $strLastname = $account['surname'];
        $strMobile = $account['mobile_number'];

        $description = "Rush Wallet";

        $total_amountInCents = $walletTransaction->amount * 100;
        $currencyCode = 'ZAR';
        /** End Customer & Basket */
        try {
// 1. Building the Soap array  of data to send
            $setTransactionArray = array();
            $setTransactionArray['Api'] = $apiVersion;
            $setTransactionArray['Safekey'] = $safeKey;
            $setTransactionArray['TransactionType'] = $transaction_type;

            $setTransactionArray['AdditionalInformation']['merchantReference'] = $wallet_transaction_id;
            $setTransactionArray['AdditionalInformation']['cancelUrl'] = $cancelUrl;
            $setTransactionArray['AdditionalInformation']['returnUrl'] = $returnUrl;
            $setTransactionArray['AdditionalInformation']['secure3d'] = 'False';
            $setTransactionArray['AdditionalInformation']['supportedPaymentMethods'] = $supported_payment_methods;
            $setTransactionArray['AdditionalInformation']['RedirectChannel'] = Config::get('payuConfig.wallet_payu_rpp.redirectChannel');

            $setTransactionArray ['Basket'] ['description'] = $description;
            $setTransactionArray ['Basket'] ['amountInCents'] = $total_amountInCents;
            $setTransactionArray ['Basket'] ['currencyCode'] = $currencyCode;

            $setTransactionArray['TransactionRecord']['managedBy'] = $managedBy;

            $setTransactionArray ['Customer'] ['merchantUserId'] = $current_user_id;
            $setTransactionArray ['Customer'] ['email'] = $strEmail;
            $setTransactionArray ['Customer'] ['firstName'] = $strFirstname;
            $setTransactionArray ['Customer'] ['lastName'] = $strLastname;
            $setTransactionArray ['Customer'] ['mobile'] = $strMobile;

// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
            $headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
            $headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
            $headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
            $headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
            $headerXml .= '</wsse:UsernameToken>';
            $headerXml .= '</wsse:Security>';
            $headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

// 3. Create Soap Header.
            $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
            $header = new SOAPHeader($ns, 'Security', $headerbody, true);

// 4. Make new instance of the PHP Soap client
            $soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

// 5. Set the Headers of soap client.
            $soap_client->__setSoapHeaders($header);

// 6. Do the setTransaction soap call to PayU
            $soapCallResult = $soap_client->setTransaction($setTransactionArray);

// 7. Decode the Soap Call Result
            $returnData = json_decode(json_encode($soapCallResult), true);

            $request = $soap_client->__getLastRequest();
            $response = $soap_client->__getLastResponse();

            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
            $payu_setTransaction_log->addInfo("[BusinessController:setWalletRPPPayU] Info: PayU SetTransaction for Wallet Transaction Id=" . $wallet_transaction_id . ", Request: " . $request);
            $payu_setTransaction_log->addInfo("[BusinessController:setWalletRPPPayU] Info: PayU SetTransaction for Wallet Transaction Id=" . $wallet_transaction_id . ", Response: " . $response);

            if (isset($doAutoRedirectToPaymentPage) && ($doAutoRedirectToPaymentPage == 1)) {
                if (
                        (isset($returnData['return']['successful']) &&
                        ($returnData['return']['successful'] === true) &&
                        isset($returnData['return']['payUReference']))
                ) {

                    $walletTransaction = WalletTransactions::find($wallet_transaction_id);
                    $walletTransaction->transaction_reference = $returnData['return']['payUReference'];
                    $walletTransaction->save();

                    $log = PayULog::create([
                                "order_id" => 0,
                                "user_id" => $current_user_id,
                                "payu_reference" => $returnData['return']['payUReference'],
                                "api_method" => "set wallet transaction",
                                "input_from_user" => "Wallet Transaction Id=" . $wallet_transaction_id,
                                "api_post" => $request,
                                "api_response" => $response,
                    ]);

                    return $this->respond(['redirectUrl' => $redirectUrl . $returnData['return']['payUReference']]);
                }
                return $this->respondInternalError([
                            'message' => "Couldn't get a success response from PayU. Please try again later.",
                            'response_error' => 'Refill Wallet Failed'
                ]);
            }
        } catch (Exception $ex) {
            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addWarning("[BusinessController:setWalletRPPPayU] Error: Internal PayU Gateway Error: " . $ex->getMessage());
            return $this->respondInternalError([
                        'message' => "Your Refill Wallet could not proceed. Please try again.",
                        'response_error' => '[BusinessController:setWalletRPPPayU] Error: Payu Failure. ' . $ex->getMessage()
            ]);
        }

        $payu_setTransaction_log = new Logger('SetTransaction');
        $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::ERROR));
        $payu_setTransaction_log->addError("[BusinessController:setWalletRPPPayU] Error: Refill Wallet could not proceed for Wallet Transaction Id=" . $wallet_transaction_id);
        return $this->respondInternalError([
                    'message' => "Your Refill Wallet could not proceed. Please try again.",
                    'response_error' => 'Error: PayU failure!'
        ]);
    }

    private function setWalletRTRRPPPayU($account_id, $wallet_transaction_id) {
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        ob_start();


        /** Start Configuration */
        $baseUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.baseUrl'); //environment URL
        $soapWdslUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.wsdlUrl');
        $payuRppUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.redirectUrl');
        $apiVersion = Config::get('payuConfig.wallet_payu_rtr_rpp.apiVersion');
        $doAutoRedirectToPaymentPage = Config::get('payuConfig.wallet_payu_rtr_rpp.redirect'); //set value != 1 if you dont want to auto redirect topayment page

        /** Store config details */
        $safeKey = Config::get('payuConfig.wallet_payu_rtr_rpp.safeKey');
        $soapUsername = Config::get('payuConfig.wallet_payu_rtr_rpp.username');
        $soapPassword = Config::get('payuConfig.wallet_payu_rtr_rpp.password');
        /** End Store config details */
        $cancelUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.cancelUrl');
        $returnUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.returnUrl');
        $transaction_type = Config::get('payuConfig.wallet_payu_rtr_rpp.transactionType');
        $supported_payment_methods = Config::get('payuConfig.wallet_payu_rtr_rpp.supportedPaymentMethods');

        $managedBy = Config::get('payuConfig.wallet_payu_rtr_rpp.managedBy');
        $redirectUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.redirectUrl');
        /**  End Configuration  */
        $account = Account::with('user')->find($account_id);
        $walletTransaction = WalletTransactions::find($wallet_transaction_id);
        if (!$walletTransaction) {
            return $this->respondInternalError([
                        'message' => "Your Refill Wallet could not proceed. Please try again.",
                        'response_error' => 'Error: PayU failure!'
            ]);
        }
//Unique identifier on the merchant system to identify the customer. This ID must be sent into PayU to identify that the card was tokenised.
        $merchant_customer_user_id = Config::get('payuConfig.wallet_payu_rtr_rpp.platform') . $account['user_id'] . "_" . $account_id;

        /** Start Customer & Basket */
        $current_user_id = $account['user_id'];
        $strEmail = $account['user']['email'];
        $strFirstname = $account['name'];
        $strLastname = $account['surname'];
        $strMobile = $account['mobile_number'];

        $basket_description = "Rush Wallet";

        $total_amountInCents = $walletTransaction->amount * 100;
        $currencyCode = 'ZAR';
        /** End Customer & Basket */
        try {
// 1. Building the Soap array  of data to send
            $setTransactionArray = array();
            $setTransactionArray['Api'] = $apiVersion;
            $setTransactionArray['Safekey'] = $safeKey;
            $setTransactionArray['TransactionType'] = $transaction_type;

            $setTransactionArray['AdditionalInformation']['merchantReference'] = $wallet_transaction_id;
            $setTransactionArray['AdditionalInformation']['secure3d'] = 'False';
            $setTransactionArray['AdditionalInformation']['cancelUrl'] = $cancelUrl;
            $setTransactionArray['AdditionalInformation']['returnUrl'] = $returnUrl;
            $setTransactionArray['AdditionalInformation']['supportedPaymentMethods'] = $supported_payment_methods;
            $setTransactionArray['AdditionalInformation']['RedirectChannel'] = Config::get('payuConfig.wallet_payu_rtr_rpp.redirectChannel');

            $setTransactionArray ['Basket'] ['description'] = $basket_description;
            $setTransactionArray ['Basket'] ['amountInCents'] = $total_amountInCents;
            $setTransactionArray ['Basket'] ['currencyCode'] = $currencyCode;

            $setTransactionArray['TransactionRecord']['managedBy'] = $managedBy;

            $setTransactionArray ['Customer'] ['merchantUserId'] = $merchant_customer_user_id;
            $setTransactionArray ['Customer'] ['email'] = $strEmail;
            $setTransactionArray ['Customer'] ['firstName'] = $strFirstname;
            $setTransactionArray ['Customer'] ['lastName'] = $strLastname;
            $setTransactionArray ['Customer'] ['mobile'] = $strMobile;

            $setTransactionArray['Customfield']['key'] = 'processingType';
            $setTransactionArray['Customfield']['value'] = 'REAL_TIME_RECURRING';

// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
            $headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
            $headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
            $headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
            $headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
            $headerXml .= '</wsse:UsernameToken>';
            $headerXml .= '</wsse:Security>';
            $headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

// 3. Create Soap Header.
            $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
            $header = new SOAPHeader($ns, 'Security', $headerbody, true);

// 4. Make new instance of the PHP Soap client
            $soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

// 5. Set the Headers of soap client.
            $soap_client->__setSoapHeaders($header);

// 6. Do the setTransaction soap call to PayU
            $soapCallResult = $soap_client->setTransaction($setTransactionArray);

// 7. Decode the Soap Call Result
            $returnData = json_decode(json_encode($soapCallResult), true);

            $request = $soap_client->__getLastRequest();
            $response = $soap_client->__getLastResponse();

            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
            $payu_setTransaction_log->addInfo("[BusinessController:setWalletRTRRPPPayU] Info: PayU SetTransaction for Wallet Transaction Id==" . $wallet_transaction_id . ", Request: " . $request);
            $payu_setTransaction_log->addInfo("[BusinessController:setWalletRTRRPPPayU] Info: PayU SetTransaction for Wallet Transaction Id==" . $wallet_transaction_id . ", Response: " . $response);

            if (isset($doAutoRedirectToPaymentPage) && ($doAutoRedirectToPaymentPage == 1)) {
                if (
                        (isset($returnData['return']['successful']) &&
                        ($returnData['return']['successful'] === true) &&
                        isset($returnData['return']['payUReference']))
                ) {

                    $walletTransaction = WalletTransactions::find($wallet_transaction_id);
                    $walletTransaction->transaction_reference = $returnData['return']['payUReference'];
                    $walletTransaction->save();

                    $log = PayULog::create([
                                "order_id" => 0,
                                "user_id" => $current_user_id,
                                "payu_reference" => $returnData['return']['payUReference'],
                                "api_method" => "set wallet transaction",
                                "input_from_user" => "Wallet Transaction Id=" . $wallet_transaction_id,
                                "api_post" => $request,
                                "api_response" => $response,
                    ]);

                    return $this->respond(['redirectUrl' => $redirectUrl . $returnData['return']['payUReference']]);
                }
                return $this->respondInternalError([
                            'message' => "Couldn't get a success response from PayU. Please try again later.",
                            'response_error' => 'Refill Wallet Failed!'
                ]);
            }
        } catch (Exception $ex) {
            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addWarning("[BusinessController:setWalletRTRRPPPayU] Error: Internal PayU Gateway Error: " . $ex->getMessage());
            return $this->respondInternalError([
                        'message' => "Your Refill Wallet could not proceed. Please try again.",
                        'response_error' => '[BusinessController:setWalletRTRRPPPayU] Error: Payu Failure. ' . $ex->getMessage()
            ]);
        }

        $payu_setTransaction_log = new Logger('SetTransaction');
        $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::ERROR));
        $payu_setTransaction_log->addError("[BusinessController:setWalletRTRRPPPayU] Error: Payment could not proceed for Wallet Transaction Id=" . $wallet_transaction_id);
        return $this->respondInternalError([
                    'message' => "Your Refill Wallet could not proceed. Please try again.",
                    'response_error' => 'Error: PayU failure!'
        ]);
    }

    public function getRefillWalletPayUStatus() {
        $postData = Input::all();
        $payu_reference = $postData['PayUReference'];

        $existingTransactions = WalletTransactions::where('transaction_reference', '=', $payu_reference)->where('status', '=', 'SUCCESS')->get();
        if (!$existingTransactions->isEmpty()) {
            return $this->respondInternalError([
                        'message' => "Your transaction has already been processed.",
                        'response_error' => "Your transaction has already been processed.",
                        'redirectUrl' => Config::get('payuConfig.wallet_payu_rpp.refreshRedirectUrl')
            ]);
        }

        $walletTransactions = WalletTransactions::byPayuReference($payu_reference)->get()->toArray();
        $walletId = $walletTransactions[0]['wallet_id'];
        $wallet = Wallet::find($walletId);
        $account = Account::with('user')->find($wallet->account_id);

        $payu_setTransaction_log = new Logger('GetTransaction');
        $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
        $payu_setTransaction_log->addInfo("[BusinessController:getRefillWalletPayUStatus] Process: getPayU Refill Wallet Status for payURef=" . $payu_reference);

        /** Start Configuration  */
        $environment = null;
        $baseUrl = null;
        $soapWdslUrl = null;
        $payuRppUrl = null;
        $apiVersion = null;
        $safeKey = null;
        $soapUsername = null;
        $soapPassword = null;
        if (!($account->store_payment) || $account->store_payment == 0 || $account->store_payment === 'undefined' || $account->store_payment == null || $account->store_payment === '') {

            $environment = Config::get('payuConfig.wallet_payu_rpp.environment');
            $baseUrl = Config::get('payuConfig.wallet_payu_rpp.baseUrl');
            $soapWdslUrl = Config::get('payuConfig.wallet_payu_rpp.wsdlUrl');
            $payuRppUrl = Config::get('payuConfig.wallet_payu_rpp.redirectUrl');
            $apiVersion = Config::get('payuConfig.wallet_payu_rpp.apiVersion');
            $safeKey = Config::get('payuConfig.wallet_payu_rpp.safeKey');
            $soapUsername = Config::get('payuConfig.wallet_payu_rpp.username');
            $soapPassword = Config::get('payuConfig.wallet_payu_rpp.password');
        } else if ($account->store_payment == 1) {
            $environment = Config::get('payuConfig.wallet_payu_rtr_rpp.environment');
            $baseUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.baseUrl');
            $soapWdslUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.wsdlUrl');
            $payuRppUrl = Config::get('payuConfig.wallet_payu_rtr_rpp.redirectUrl');
            $apiVersion = Config::get('payuConfig.wallet_payu_rtr_rpp.apiVersion');
            $safeKey = Config::get('payuConfig.wallet_payu_rtr_rpp.safeKey');
            $soapUsername = Config::get('payuConfig.wallet_payu_rtr_rpp.username');
            $soapPassword = Config::get('payuConfig.wallet_payu_rtr_rpp.password');
        }

        /** End Configuration  */
        try {

// 1. Building the Soap array  of data to send
            $soapDataArray = array();
            $soapDataArray['Api'] = $apiVersion;
            $soapDataArray['Safekey'] = $safeKey;
            $soapDataArray['AdditionalInformation']['payUReference'] = $payu_reference;

// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
            $headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
            $headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
            $headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
            $headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
            $headerXml .= '</wsse:UsernameToken>';
            $headerXml .= '</wsse:Security>';
            $headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

// 3. Create Soap Header.
            $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
            $header = new SOAPHeader($ns, 'Security', $headerbody, true);

// 4. Make new instance of the PHP Soap client
            $soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

// 5. Set the Headers of soap client.
            $soap_client->__setSoapHeaders($header);

// 6. Do the setTransaction soap call to PayU
            $soapCallResult = $soap_client->getTransaction($soapDataArray);

// 7. Decode the Soap Call Result
            $returnData = json_decode(json_encode($soapCallResult), true);

            if (is_object($soap_client)) {
                $request = $soap_client->__getLastRequest();
                $response = $soap_client->__getLastResponse();

                $payu_setTransaction_log = new Logger('GetTransaction');
                $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
                $payu_setTransaction_log->addInfo("[BusinessController:getRefillWalletPayUStatus] Info: Refill Wallet GetTransaction for Wallet Transaction Id=" . $walletTransactions[0]['id'] . ", Request: " . $request);
                $payu_setTransaction_log->addInfo("[BusinessController:getRefillWalletPayUStatus] Info: Refill Wallet GetTransaction for Wallet Transaction Id=" . $walletTransactions[0]['id'] . ", Response: " . $response);

                $methodType = "";
                if ($returnData['return']['resultCode'] === '00' && (isset($returnData['return']['transactionState']) && $returnData['return']['transactionState'] === 'SUCCESSFUL')) {
                    $methodType = "Payment Successful";

                    $payu_payment_passed_log = new Logger('Refill Wallet Passed');
                    $payu_payment_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_payments_passed.log', Logger::INFO));
                    $payu_payment_passed_log->addInfo("[BusinessController:getRefillWalletPayUStatus] Info: Refill Wallet Status for Wallet Transaction Id=" . $walletTransactions[0]['id'] . " is: " . $methodType);

                    $transaction = WalletTransactions::find($walletTransactions[0]['id']);
                    $transaction->status = WalletTransactions::$SUCCESS;
                    $transaction->save();

                    /**
                     * Update Wallet
                     */
                    $updateAmount = floatval($wallet->amount) + $transaction->amount;
                    $newAmount = round($updateAmount, 2);
                    $wallet->amount = $newAmount;
                    $wallet->save();

//Log::info($account);
                    try {
                        $mandrill = new MandrillService();
                        $mandrill->sendWalletDepositReceipt(
                                $account->user->email, $account->title . " " . $account->name . " " . $account->surname, $wallet->amount, $transaction->amount);
                    } catch (Exception $e) {
                        Log::info("Failed to send reminder email. Error message: " . $e->getMessage());
                    }

                    $PayUPassedLog = PaymentLog::create([
                                "order_id" => 0,
                                "method_type" => $methodType,
                                "config_data" => "",
                                "post_data" => $request,
                                "result_data" => $response,
                    ]);

                    return $this->respond([
                                'returnData' => $returnData,
                                'environment' => $environment,
                    ]);
                } else {
                    $methodType = $returnData['return']['resultMessage'];

                    $payu_payment_failed_log = new Logger('PayU Payment Failed');
                    $payu_payment_failed_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_payments_failed.log', Logger::INFO));
                    $payu_payment_failed_log->addInfo("[BusinessController:getRefillWalletPayUStatus] Info: Refill Wallet Status for Wallet Transaction Id=" . $walletTransactions[0]['id'] . " is: " . $methodType);

                    $msg = "Payment is being processed.";
                    if ("Invalid PayUReference" == $methodType ||
                            (isset($returnData['return']['transactionState']) &&
                            ($returnData['return']['transactionState'] === 'FAILED' || $returnData['return']['transactionState'] === 'NEW'))) {
                        $transaction = WalletTransactions::find($walletTransactions[0]['id']);
                        $transaction->status = "FAILED";
                        $transaction->save();
                        $msg = "Payment failed. Wallet has not been credited.";
                    }
//                    elseif ($returnData['return']['transactionState'] === 'NEW')
//                    {
//                        $transaction = WalletTransactions::find($walletTransactions[0]['id']);
//                        $transaction->status = "INCOMPLETE";
//                        $transaction->save();
//                        $msg = "Payment process has not been completed. Wallet has not been credited.";
//                    }


                    $PayUPassedLog = PaymentLog::create([
                                "order_id" => 0,
                                "method_type" => $methodType,
                                "config_data" => "",
                                "post_data" => $request,
                                "result_data" => $response,
                    ]);

                    return $this->respondInternalError([
                                'message' => $msg,
                                'response_error' => "[BusinessController:getRefillWalletPayUStatus] " . $msg,
                                'returnData' => $returnData,
                    ]);
                }
            }

            return $this->respondInternalError([
                        'message' => "Could not check payment status for Wallet Transaction Id=" . $walletTransactions[0]['id'],
                        'response_error' => "[BusinessController:getRefillWalletPayUStatus] Internal Error: Could not check payment status for Wallet Transaction Id=" . $walletTransactions[0]['id']
            ]);
        } catch (Exception $e) {
            $payu_setTransaction_log = new Logger('GetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addWarning("[BusinessController:getRefillWalletPayUStatus] Internal Error: " . $e->getMessage());
            return $this->respondInternalError([
                        'message' => "Internal Error: Your confirmation order could not proceed.",
                        'response_error' => "[BusinessController:getRefillWalletPayUStatus] Internal Error: " . $e->getMessage()
            ]);
        }
    }

    public function setPayU() {
        $postData = Input::all();
        $orderGroupRef = $postData['orderGroupRef'];

        $orders = Order::ordergrouprefnotpaid($orderGroupRef)->get()->toArray();
        $account = Account::find($orders[0]['account_id']); //accountId same for all orders.

        if (!($account->store_payment) || $account->store_payment === 'undefined' || $account->store_payment == 0) {
            return $this->setRPPPayU($orderGroupRef);
        } else if ($account->store_payment == 1) {
            return $this->setRTRRPPPayU($orderGroupRef);
        }
    }

    private function setRPPPayU($orderGroupRef) {
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        ob_start();

//        $postData = Input::all();
//        $orderGroupRef = $postData['orderGroupRef'];

        /** Start Configuration */
        $baseUrl = Config::get('payuConfig.payu_rpp.baseUrl'); //environment URL
        $soapWdslUrl = Config::get('payuConfig.payu_rpp.wsdlUrl');
        $payuRppUrl = Config::get('payuConfig.payu_rpp.redirectUrl');
        $apiVersion = Config::get('payuConfig.payu_rpp.apiVersion');
        $doAutoRedirectToPaymentPage = Config::get('payuConfig.payu_rpp.redirect'); //set value != 1 if you dont want to auto redirect topayment page

        /** Store config details */
        $safeKey = Config::get('payuConfig.payu_rpp.safeKey');
        $soapUsername = Config::get('payuConfig.payu_rpp.username');
        $soapPassword = Config::get('payuConfig.payu_rpp.password');
        /** End Store config details */
        $cancelUrl = Config::get('payuConfig.payu_rpp.cancelUrl');
        $returnUrl = Config::get('payuConfig.payu_rpp.returnUrl') . $orderGroupRef;
        $transaction_type = Config::get('payuConfig.payu_rpp.transactionType');
        $supported_payment_methods = Config::get('payuConfig.payu_rpp.supportedPaymentMethods');

        $merchant_reference = $orderGroupRef;
        $managedBy = Config::get('payuConfig.payu_rpp.managedBy');
        $redirectUrl = Config::get('payuConfig.payu_rpp.redirectUrl');
        /**  End Configuration  */
        $basket_orders = Order::ordergrouprefnotpaid($orderGroupRef)->get()->toArray();
        $account = Account::with('user')->find($basket_orders[0]['account_id']); //accountId same for all orders.

        /** Start Customer & Basket */
        $current_user_id = $account['user_id'];
        $strEmail = $account['user']['email'];
        $strFirstname = $account['name'];
        $strLastname = $account['surname'];
        $strMobile = $account['mobile_number'];

        $basket_description = "Rush Basket";

        $order_group = OrderGroup::ordergroupref($orderGroupRef)->get()->toArray();
        if (!$order_group || empty($order_group) || $order_group[0]['total_price'] && $order_group[0]['order_group_ref'] !== $orderGroupRef) {
            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addError("[BusinessController:setRPPPayU] Error: Payment could not proceed for OrderGroupRef=" . $orderGroupRef . ". Pricing details are missing.");
            return $this->respondInternalError([
                        'message' => "Your payment could not proceed. Please try again.",
                        'order_group_ref' => $orderGroupRef,
                        'response_error' => 'Error: PayU failure!'
            ]);
        }

        $basket_total_amountInCents = $order_group[0]['total_price'] * 100;
        $basket_currencyCode = 'ZAR';
        /** End Customer & Basket */
        try {
// 1. Building the Soap array  of data to send
            $setTransactionArray = array();
            $setTransactionArray['Api'] = $apiVersion;
            $setTransactionArray['Safekey'] = $safeKey;
            $setTransactionArray['TransactionType'] = $transaction_type;

            $setTransactionArray['AdditionalInformation']['merchantReference'] = $merchant_reference;
            $setTransactionArray['AdditionalInformation']['cancelUrl'] = $cancelUrl;
            $setTransactionArray['AdditionalInformation']['returnUrl'] = $returnUrl;
            $setTransactionArray['AdditionalInformation']['secure3d'] = 'False';
            $setTransactionArray['AdditionalInformation']['supportedPaymentMethods'] = $supported_payment_methods;
            $setTransactionArray['AdditionalInformation']['RedirectChannel'] = Config::get('payuConfig.payu_rpp.redirectChannel');

            $setTransactionArray ['Basket'] ['description'] = $basket_description;
            $setTransactionArray ['Basket'] ['amountInCents'] = $basket_total_amountInCents;
            $setTransactionArray ['Basket'] ['currencyCode'] = $basket_currencyCode;

            $setTransactionArray['TransactionRecord']['managedBy'] = $managedBy;

            $setTransactionArray ['Customer'] ['merchantUserId'] = $orderGroupRef;
            $setTransactionArray ['Customer'] ['email'] = $strEmail;
            $setTransactionArray ['Customer'] ['firstName'] = $strFirstname;
            $setTransactionArray ['Customer'] ['lastName'] = $strLastname;
            $setTransactionArray ['Customer'] ['mobile'] = $strMobile;

// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
            $headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
            $headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
            $headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
            $headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
            $headerXml .= '</wsse:UsernameToken>';
            $headerXml .= '</wsse:Security>';
            $headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

// 3. Create Soap Header.
            $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
            $header = new SOAPHeader($ns, 'Security', $headerbody, true);

// 4. Make new instance of the PHP Soap client
            $soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

// 5. Set the Headers of soap client.
            $soap_client->__setSoapHeaders($header);

// 6. Do the setTransaction soap call to PayU
            $soapCallResult = $soap_client->setTransaction($setTransactionArray);

// 7. Decode the Soap Call Result
            $returnData = json_decode(json_encode($soapCallResult), true);

            $request = $soap_client->__getLastRequest();
            $response = $soap_client->__getLastResponse();

            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
            $payu_setTransaction_log->addInfo("[BusinessController:setRPPPayU] Info: PayU SetTransaction for OrderGroupRef=" . $orderGroupRef . ", Request: " . $request);
            $payu_setTransaction_log->addInfo("[BusinessController:setRPPPayU] Info: PayU SetTransaction for OrderGroupRef=" . $orderGroupRef . ", Response: " . $response);

            if (isset($doAutoRedirectToPaymentPage) && ($doAutoRedirectToPaymentPage == 1)) {
                if (
                        (isset($returnData['return']['successful']) &&
                        ($returnData['return']['successful'] === true) &&
                        isset($returnData['return']['payUReference']))
                ) {

                    for ($i = 0; $i < sizeof($basket_orders); $i++) {
                        $log = PayULog::create([
                                    "order_id" => $basket_orders[$i]['id'],
                                    "user_id" => $current_user_id,
                                    "payu_reference" => $returnData['return']['payUReference'],
                                    "api_method" => "set transaction",
                                    "input_from_user" => json_encode($basket_orders[$i]),
                                    "api_post" => $request,
                                    "api_response" => $response,
                        ]);
                    }
                    return $this->respond(['redirectUrl' => $redirectUrl . $returnData['return']['payUReference']]);
                }
                return $this->respondInternalError([
                            'message' => "Couldn't get a success response from PayU. Please try again later.",
                            'order_group_ref' => $orderGroupRef,
                            'response_error' => 'PayU failure!'
                ]);
            }
        } catch (Exception $ex) {
            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addWarning("[BusinessController:setRPPPayU] Error: Internal PayU Gateway Error: " . $ex->getMessage());
            return $this->respondInternalError([
                        'message' => "Your payment could not proceed. Please try again.",
                        'order_group_ref' => $orderGroupRef,
                        'response_error' => '[BusinessController:setRPPPayU] Error: Payu Failure. ' . $ex->getMessage()
            ]);
        }

        $payu_setTransaction_log = new Logger('SetTransaction');
        $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::ERROR));
        $payu_setTransaction_log->addError("[BusinessController:setRPPPayU] Error: Payment could not proceed for OrderGroupRef=" . $orderGroupRef);
        return $this->respondInternalError([
                    'message' => "Your payment could not proceed. Please try again.",
                    'order_group_ref' => $orderGroupRef,
                    'response_error' => 'Error: PayU failure!'
        ]);
    }

    private function setRTRRPPPayU($orderGroupRef) {
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        ob_start();

//        $postData = Input::all();
//        $orderGroupRef = $postData['orderGroupRef'];

        /** Start Configuration */
        $baseUrl = Config::get('payuConfig.payu_rtr_rpp.baseUrl'); //environment URL
        $soapWdslUrl = Config::get('payuConfig.payu_rtr_rpp.wsdlUrl');
        $payuRppUrl = Config::get('payuConfig.payu_rtr_rpp.redirectUrl');
        $apiVersion = Config::get('payuConfig.payu_rtr_rpp.apiVersion');
        $doAutoRedirectToPaymentPage = Config::get('payuConfig.payu_rtr_rpp.redirect'); //set value != 1 if you dont want to auto redirect topayment page

        /** Store config details */
        $safeKey = Config::get('payuConfig.payu_rtr_rpp.safeKey');
        $soapUsername = Config::get('payuConfig.payu_rtr_rpp.username');
        $soapPassword = Config::get('payuConfig.payu_rtr_rpp.password');
        /** End Store config details */
        $cancelUrl = Config::get('payuConfig.payu_rtr_rpp.cancelUrl');
        $returnUrl = Config::get('payuConfig.payu_rtr_rpp.returnUrl') . $orderGroupRef;
        $transaction_type = Config::get('payuConfig.payu_rtr_rpp.transactionType');
        $supported_payment_methods = Config::get('payuConfig.payu_rtr_rpp.supportedPaymentMethods');

        $merchant_reference = $orderGroupRef;
        $managedBy = Config::get('payuConfig.payu_rtr_rpp.managedBy');
        $redirectUrl = Config::get('payuConfig.payu_rtr_rpp.redirectUrl');
        /**  End Configuration  */
        $basket_orders = Order::ordergrouprefnotpaid($orderGroupRef)->get()->toArray();
        $account = Account::with('user')->find($basket_orders[0]['account_id']); //accountId same for all orders.
//Unique identifier on the merchant system to identify the customer. This ID must be sent into PayU to identify that the card was tokenised.
        $merchant_customer_user_id = Config::get('payuConfig.payu_rtr_rpp.platform') . $account['user_id'] . "_" . $basket_orders[0]['account_id'];

        /** Start Customer & Basket */
        $current_user_id = $account['user_id'];
        $strEmail = $account['user']['email'];
        $strFirstname = $account['name'];
        $strLastname = $account['surname'];
        $strMobile = $account['mobile_number'];

        $basket_description = "Rush RTR Store";

        $order_group = OrderGroup::ordergroupref($orderGroupRef)->get()->toArray();
        if (!$order_group || empty($order_group) || $order_group[0]['total_price'] && $order_group[0]['order_group_ref'] !== $orderGroupRef) {
            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addError("[BusinessController:setRPPPayU] Error: Payment could not proceed for OrderGroupRef=" . $orderGroupRef . ". Pricing details are missing.");
            return $this->respondInternalError([
                        'message' => "Your payment could not proceed. Please try again.",
                        'order_group_ref' => $orderGroupRef,
                        'response_error' => 'Error: PayU failure!'
            ]);
        }

        $basket_total_amountInCents = $order_group[0]['total_price'] * 100;
        $basket_currencyCode = 'ZAR';
        /** End Customer & Basket */
        try {
// 1. Building the Soap array  of data to send
            $setTransactionArray = array();
            $setTransactionArray['Api'] = $apiVersion;
            $setTransactionArray['Safekey'] = $safeKey;
            $setTransactionArray['TransactionType'] = $transaction_type;

            $setTransactionArray['AdditionalInformation']['merchantReference'] = $merchant_reference;
            $setTransactionArray['AdditionalInformation']['secure3d'] = 'False';
            $setTransactionArray['AdditionalInformation']['cancelUrl'] = $cancelUrl;
            $setTransactionArray['AdditionalInformation']['returnUrl'] = $returnUrl;
            $setTransactionArray['AdditionalInformation']['supportedPaymentMethods'] = $supported_payment_methods;
            $setTransactionArray['AdditionalInformation']['RedirectChannel'] = Config::get('payuConfig.payu_rtr_rpp.redirectChannel');

            $setTransactionArray ['Basket'] ['description'] = $basket_description;
            $setTransactionArray ['Basket'] ['amountInCents'] = $basket_total_amountInCents;
            $setTransactionArray ['Basket'] ['currencyCode'] = $basket_currencyCode;

            $setTransactionArray['TransactionRecord']['managedBy'] = $managedBy;

            $setTransactionArray ['Customer'] ['merchantUserId'] = $merchant_customer_user_id;
            $setTransactionArray ['Customer'] ['email'] = $strEmail;
            $setTransactionArray ['Customer'] ['firstName'] = $strFirstname;
            $setTransactionArray ['Customer'] ['lastName'] = $strLastname;
            $setTransactionArray ['Customer'] ['mobile'] = $strMobile;

            $setTransactionArray['Customfield']['key'] = 'processingType';
            $setTransactionArray['Customfield']['value'] = 'REAL_TIME_RECURRING';

// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
            $headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
            $headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
            $headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
            $headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
            $headerXml .= '</wsse:UsernameToken>';
            $headerXml .= '</wsse:Security>';
            $headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

// 3. Create Soap Header.
            $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
            $header = new SOAPHeader($ns, 'Security', $headerbody, true);

// 4. Make new instance of the PHP Soap client
            $soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

// 5. Set the Headers of soap client.
            $soap_client->__setSoapHeaders($header);

// 6. Do the setTransaction soap call to PayU
            $soapCallResult = $soap_client->setTransaction($setTransactionArray);

// 7. Decode the Soap Call Result
            $returnData = json_decode(json_encode($soapCallResult), true);

            $request = $soap_client->__getLastRequest();
            $response = $soap_client->__getLastResponse();

            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
            $payu_setTransaction_log->addInfo("[BusinessController:setRTRRPPPayU] Info: PayU SetTransaction for OrderGroupRef=" . $orderGroupRef . ", Request: " . $request);
            $payu_setTransaction_log->addInfo("[BusinessController:setRTRRPPPayU] Info: PayU SetTransaction for OrderGroupRef=" . $orderGroupRef . ", Response: " . $response);

            if (isset($doAutoRedirectToPaymentPage) && ($doAutoRedirectToPaymentPage == 1)) {
                if (
                        (isset($returnData['return']['successful']) &&
                        ($returnData['return']['successful'] === true) &&
                        isset($returnData['return']['payUReference']))
                ) {

                    for ($i = 0; $i < sizeof($basket_orders); $i++) {
                        $log = PayULog::create([
                                    "order_id" => $basket_orders[$i]['id'],
                                    "user_id" => $current_user_id,
                                    "payu_reference" => $returnData['return']['payUReference'],
                                    "api_method" => "set transaction",
                                    "input_from_user" => json_encode($basket_orders[$i]),
                                    "api_post" => $request,
                                    "api_response" => $response,
                        ]);
                    }
                    return $this->respond(['redirectUrl' => $redirectUrl . $returnData['return']['payUReference']]);
                }
                return $this->respondInternalError([
                            'message' => "Couldn't get a success response from PayU. Please try again later.",
                            'order_group_ref' => $orderGroupRef,
                            'response_error' => 'PayU failure!'
                ]);
            }
        } catch (Exception $ex) {
            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addWarning("[BusinessController:setRPPPayU] Error: Internal PayU Gateway Error: " . $ex->getMessage());
            return $this->respondInternalError([
                        'message' => "Your payment could not proceed. Please try again.",
                        'order_group_ref' => $orderGroupRef,
                        'response_error' => '[BusinessController:setRTRRPPPayU] Error: Payu Failure. ' . $ex->getMessage()
            ]);
        }

        $payu_setTransaction_log = new Logger('SetTransaction');
        $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::ERROR));
        $payu_setTransaction_log->addError("[BusinessController:setRTRRPPPayU] Error: Payment could not proceed for OrderGroupRef=" . $orderGroupRef);
        return $this->respondInternalError([
                    'message' => "Your payment could not proceed. Please try again.",
                    'order_group_ref' => $orderGroupRef,
                    'response_error' => 'Error: PayU failure!'
        ]);
    }

    public function checkBasketOrdersConfirmed() {

        $postData = Input::all();
        $order_group_ref = $postData['OrderGroupRef'];
        if (!isset($postData['isdebtor'])) {
            $isdebtor = true;
        } else {
            $isdebtor = false;
        }


        if (!isset($postData['PayUReference'])) {
            $payu_payment_failed_log = new Logger('PayU Payment Failed');
            $payu_payment_failed_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_payments_failed.log', Logger::INFO));
            $payu_payment_failed_log->addInfo("[BusinessController:checkBasketOrdersConfirmed] Info: PayU Payment Failure for OrderGroupRef=" . $order_group_ref);

            try {
                $order = Order::ordergroupref($order_group_ref)->get()->toArray();
                $account_id = $order[0]['account_id'];
                $errorMessage = "[BusinessController:checkBasketOrdersConfirmed] Error: PayU Payment Failure for OrderGroupRef=" . $order_group_ref . ", PayUReference is missing";
                $this->warnSupportTeamOnConfirmOrderFailure($account_id, $errorMessage);
            } catch (Exception $ex) {
                Log::info('[BusinessController: checkOrderConfirmation] Internal Error: ' . $ex->getMessage());
            }

            return $this->respondInternalError([
                        'message' => "Your payment is still processing. You will receive your waybill soon.",
                        'locked' => 1,
                        'error_message' => "Unable to process your payment.",
                        'redirectUrl' => Config::get('payuConfig.payu_rpp.redirectToBasket')
            ]);
        }

        $payu_reference = $postData['PayUReference'];
        Log::info("[BusinessController:checkBasketOrderConfirmation] Process: checking status of OrderGroupRef=" . $order_group_ref);
        try {
            $orders = Order::ordergroupref($order_group_ref)->get()->toArray();

            if (!$orders) {
                return $this->respondInternalError([
                            'message' => "Your OrderGroupRef = " . $order_group_ref . " cannot be found.",
                            'locked' => 1,
                            'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')]);
            } else {
                $basket_order_ids_pending = array();
                for ($countf = 0; $countf < sizeof($orders); $countf++) {
                    if (
                            (empty($orders[$countf]['tracking_count']) || strlen($orders[$countf]['tracking_count']) == 0) &&
                            (empty($orders[$countf]['waybill']) || strlen($orders[$countf]['waybill']) == 0) &&
                            $orders[$countf]['status'] == 2 &&
                            $orders[$countf]['order_group_ref'] === $order_group_ref
                    ) {
                        array_push($basket_order_ids_pending, $orders[$countf]['id']);
                    } else if ($orders[$countf]['order_group_ref'] === $order_group_ref && $isdebtor == true) {
                        array_push($basket_order_ids_pending, $orders[$countf]['id']);
                    }
                }

                if (sizeof($basket_order_ids_pending) > 0) {
                    $payULog = PayULog::OrderId($basket_order_ids_pending[0])->where('payu_reference', '=', $payu_reference)->get()->toArray();
                    if ($payULog[0]['payu_reference'] !== $payu_reference) {
                        return $this->respondInternalError([
                                    'message' => "Your PayU Reference for your basket order(s) with OrderGroupRef=" . $order_group_ref . " does not match.",
                                    'locked' => 1,
                                    'error_message' => "Your PayU Reference for your basket order(s) with OrderGroupRef=" . $order_group_ref . " does not match.",
                                    'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
                        ]);
                    }

                    return $this->respond([
                                'message' => "Checking basket order(s) status before completion. Success.",
                                'locked' => 0,
                                'OrderGroupRef' => $order_group_ref,
                                'BasketOrderIds' => $basket_order_ids_pending,
                                'PayUReference' => $payULog[0]['payu_reference']
                    ]);
                } else {
                    return $this->respondInternalError([
                                'message' => "Your basket order(s) with OrderGroupRef=" . $order_group_ref . " is empty.",
                                'locked' => 1,
                                'error_message' => "Your basket order(s) with OrderGroupRef=" . $order_group_ref . " is empty.",
                                'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
                    ]);
                }
            }
        } catch (Exception $ex) {
            Log::info('[BusinessController: checkOrderConfirmation] Internal Error: ' . $ex->getMessage());
            return $this->respondInternalError([
                        'message' => "Could not proceed with your order(s). Please contact our support.",
                        'locked' => 1,
                        'error_message' => "Could not proceed with your order(s). OrderGroupRef=" . $order_group_ref . ". Error:" . $ex->getMessage(),
                        'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
            ]);
        }
        Log::info('[BusinessController: checkOrderConfirmation] Internal Error: Could not proceed with your order(s). Please contact our support.');
        return $this->respondInternalError([
                    'message' => "Could not proceed with your order(s). Please contact our support.",
                    'locked' => 1,
                    'error_message' => "Could not proceed with your order(s). OrderGroupRef=" . $order_group_ref,
                    'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
        ]);
    }

    public function checkPaymentConfirmed() {

        $postData = Input::all();
        $order_group_ref = $postData['OrderGroupRef'];

        if (!isset($postData['PayUReference'])) {
            $payu_payment_failed_log = new Logger('PayU Payment Failed');
            $payu_payment_failed_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_payments_failed.log', Logger::INFO));
            $payu_payment_failed_log->addInfo("[BusinessController:checkBasketOrdersConfirmed] Info: PayU Payment Failure for OrderGroupRef=" . $order_group_ref);

            try {
                $order = Order::ordergroupref($order_group_ref)->get()->toArray();
                $account_id = $order[0]['account_id'];
                $errorMessage = "[BusinessController:checkBasketOrdersConfirmed] Error: PayU Payment Failure for OrderGroupRef=" . $order_group_ref . ", PayUReference is missing";
                $this->warnSupportTeamOnConfirmOrderFailure($account_id, $errorMessage);
            } catch (Exception $ex) {
                Log::info('[BusinessController: checkOrderConfirmation] Internal Error: ' . $ex->getMessage());
            }

            return $this->respondInternalError([
                        'message' => "Your payment is still processing. You will receive your waybill soon.",
                        'locked' => 1,
                        'error_message' => "Unable to process your payment.",
                        'redirectUrl' => Config::get('payuConfig.payu_rpp.redirectToBasket')
            ]);
        }

        $payu_reference = $postData['PayUReference'];
        Log::info("[BusinessController:checkBasketOrderConfirmation] Process: checking status of OrderGroupRef=" . $order_group_ref);
        try {
            $orders = Order::ordergroupref($order_group_ref)->get()->toArray();

            if (!$orders) {
                return $this->respondInternalError([
                            'message' => "Your OrderGroupRef = " . $order_group_ref . " cannot be found.",
                            'locked' => 1,
                            'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')]);
            } else {
                $basket_order_ids_pending = array();
                for ($countf = 0; $countf < sizeof($orders); $countf++) {
                    if (
                            (empty($orders[$countf]['tracking_count']) || strlen($orders[$countf]['tracking_count']) == 0) &&
                            (empty($orders[$countf]['waybill']) || strlen($orders[$countf]['waybill']) == 0) &&
                            $orders[$countf]['status'] == 2 &&
                            $orders[$countf]['order_group_ref'] === $order_group_ref
                    ) {
                        array_push($basket_order_ids_pending, $orders[$countf]['id']);
                    }
                }

                if (sizeof($basket_order_ids_pending) > 0) {
                    $payULog = PayULog::OrderId($basket_order_ids_pending[0])->get()->toArray();
                    if ($payULog[0]['payu_reference'] !== $payu_reference) {
                        return $this->respondInternalError([
                                    'message' => "Your PayU Reference for your basket order(s) with OrderGroupRef=" . $order_group_ref . " does not match.",
                                    'locked' => 1,
                                    'error_message' => "Your PayU Reference for your basket order(s) with OrderGroupRef=" . $order_group_ref . " does not match.",
                                    'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
                        ]);
                    }

                    return $this->respond([
                                'message' => "Checking basket order(s) status before completion. Success.",
                                'locked' => 0,
                                'OrderGroupRef' => $order_group_ref,
                                'BasketOrderIds' => $basket_order_ids_pending,
                                'PayUReference' => $payULog[0]['payu_reference']
                    ]);
                } else {
                    return $this->respondInternalError([
                                'message' => "Your basket order(s) with OrderGroupRef=" . $order_group_ref . " is empty.",
                                'locked' => 1,
                                'error_message' => "Your basket order(s) with OrderGroupRef=" . $order_group_ref . " is empty.",
                                'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
                    ]);
                }
            }
        } catch (Exception $ex) {
            Log::info('[BusinessController: checkOrderConfirmation] Internal Error: ' . $ex->getMessage());
            return $this->respondInternalError([
                        'message' => "Could not proceed with your order(s). Please contact our support.",
                        'locked' => 1,
                        'error_message' => "Could not proceed with your order(s). OrderGroupRef=" . $order_group_ref . ". Error:" . $ex->getMessage(),
                        'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
            ]);
        }
        Log::info('[BusinessController: checkOrderConfirmation] Internal Error: Could not proceed with your order(s). Please contact our support.');
        return $this->respondInternalError([
                    'message' => "Could not proceed with your order(s). Please contact our support.",
                    'locked' => 1,
                    'error_message' => "Could not proceed with your order(s). OrderGroupRef=" . $order_group_ref,
                    'redirectUrl' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
        ]);
    }

    public function getPayUPaymentStatus() {
        $postData = Input::all();
        $order_group_ref = $postData['OrderGroupRef'];
        $basket_order_ids = $postData['BasketOrderIds'];
        $payu_reference = $postData['PayUReference'];

        $order = Order::ordergroupref($order_group_ref)->get()->toArray();
        $account_id = $order[0]['account_id'];

        $account = Account::find($account_id);

        $payu_setTransaction_log = new Logger('GetTransaction');
        $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
        $payu_setTransaction_log->addInfo("[BusinessController:getPayUPaymentStatus] Process: getPayU Payment Status for payURef=" . $payu_reference . " and OrderGroupRef=" . $order_group_ref);

        /** Start Configuration  */
        $environment = null;
        $baseUrl = null;
        $soapWdslUrl = null;
        $payuRppUrl = null;
        $apiVersion = null;
        $safeKey = null;
        $soapUsername = null;
        $soapPassword = null;
        if (!($account->store_payment) || $account->store_payment == 0 || $account->store_payment === 'undefined' || $account->store_payment == null || $account->store_payment === '') {

            $environment = Config::get('payuConfig.payu_rpp.environment');
            $baseUrl = Config::get('payuConfig.payu_rpp.baseUrl');
            $soapWdslUrl = Config::get('payuConfig.payu_rpp.wsdlUrl');
            $payuRppUrl = Config::get('payuConfig.payu_rpp.redirectUrl');
            $apiVersion = Config::get('payuConfig.payu_rpp.apiVersion');
            $safeKey = Config::get('payuConfig.payu_rpp.safeKey');
            $soapUsername = Config::get('payuConfig.payu_rpp.username');
            $soapPassword = Config::get('payuConfig.payu_rpp.password');
        } else if ($account->store_payment == 1) {
            $environment = Config::get('payuConfig.payu_rtr_rpp.environment');
            $baseUrl = Config::get('payuConfig.payu_rtr_rpp.baseUrl');
            $soapWdslUrl = Config::get('payuConfig.payu_rtr_rpp.wsdlUrl');
            $payuRppUrl = Config::get('payuConfig.payu_rtr_rpp.redirectUrl');
            $apiVersion = Config::get('payuConfig.payu_rtr_rpp.apiVersion');
            $safeKey = Config::get('payuConfig.payu_rtr_rpp.safeKey');
            $soapUsername = Config::get('payuConfig.payu_rtr_rpp.username');
            $soapPassword = Config::get('payuConfig.payu_rtr_rpp.password');
        }

        $merchant_reference = $order_group_ref;

        /** End Configuration  */
        try {

// 1. Building the Soap array  of data to send
            $soapDataArray = array();
            $soapDataArray['Api'] = $apiVersion;
            $soapDataArray['Safekey'] = $safeKey;
            $soapDataArray['AdditionalInformation']['payUReference'] = $payu_reference;

// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
            $headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
            $headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
            $headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
            $headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
            $headerXml .= '</wsse:UsernameToken>';
            $headerXml .= '</wsse:Security>';
            $headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

// 3. Create Soap Header.
            $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
            $header = new SOAPHeader($ns, 'Security', $headerbody, true);

// 4. Make new instance of the PHP Soap client
            $soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

// 5. Set the Headers of soap client.
            $soap_client->__setSoapHeaders($header);

// 6. Do the setTransaction soap call to PayU
            $soapCallResult = $soap_client->getTransaction($soapDataArray);

// 7. Decode the Soap Call Result
            $returnData = json_decode(json_encode($soapCallResult), true);

            if (is_object($soap_client)) {
                $request = $soap_client->__getLastRequest();
                $response = $soap_client->__getLastResponse();

                $payu_setTransaction_log = new Logger('GetTransaction');
                $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
                $payu_setTransaction_log->addInfo("[BusinessController:getPayUPaymentStatus] Info: PayU GetTransaction for OrderGroupRef=" . $order_group_ref . ", Request: " . $request);
                $payu_setTransaction_log->addInfo("[BusinessController:getPayUPaymentStatus] Info: PayU GetTransaction for OrderGroupRef=" . $order_group_ref . ", Response: " . $response);

                $methodType = "";
                if ($returnData['return']['resultCode'] === '00' && $returnData['return']['transactionState'] === 'SUCCESSFUL') {
                    $methodType = "Payment Successful";

                    $payu_payment_passed_log = new Logger('PayU Payment Passed');
                    $payu_payment_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_payments_passed.log', Logger::INFO));
                    $payu_payment_passed_log->addInfo("[BusinessController:getPayUPaymentStatus] Info: PayU Payment Status for OrderGroupRef=" . $order_group_ref . " is: " . $methodType);

                    for ($countp = 0; $countp < sizeof($basket_order_ids); $countp++) {
                        $PayUPassedLog = PaymentLog::create([
                                    "order_id" => $basket_order_ids[$countp],
                                    "method_type" => $methodType,
                                    "config_data" => "",
                                    "post_data" => $request,
                                    "result_data" => $response,
                        ]);
                    }

                    /**
                     * Update debts if any to CLEARED.
                     */
                    $debtors = Debtors::OrderGroupRef($order_group_ref)->get()->toArray();
                    if ($debtors && sizeof($debtors) > 0) {

//                        $debt_amount = 0;

                        for ($i = 0; $i < sizeof($debtors); $i++) {
                            $debt = Debtors::find($debtors[$i]['id']);
//                            $debt_amount = $debt_amount + $debt['amount'];
//                            Log::info($debt_amount);
                            $debt->status = "CLEARED";
                            $debt->payu_reference = $payu_reference;
                            $debt->save();
                        }

//                        $orders = Order::OrderGroupRef($order_group_ref)->get();
//                        for ($i = 0; $i < sizeof($orders); $i++) {
//                            $update_order = $orders[$i];
//                            $total_order_price = $update_order['total_order_price'];
//                            $update_order->total_order_price = $total_order_price + ($debt_amount * 1.14);
//                            $update_order->save();
//                        }
                    }

                    $basketDel = Basket::with('basketItem')->accountbyid($account_id)->get();
                    foreach ($basketDel as $basketD) {
                        $basketD->delete();
                    }

                    return $this->respond([
                                'returnData' => $returnData,
                                'environment' => $environment,
                                'orderGroupRef' => $order_group_ref
                    ]);
                } else {
                    $methodType = $returnData['return']['resultMessage'];

                    $payu_payment_failed_log = new Logger('PayU Payment Failed');
                    $payu_payment_failed_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_payments_failed.log', Logger::INFO));
                    $payu_payment_failed_log->addInfo("[BusinessController:getPayUPaymentStatus] Info: PayU Payment Status for OrderGroupRef=" . $order_group_ref . " is: " . $methodType);

                    for ($countp = 0; $countp < sizeof($basket_order_ids); $countp++) {
                        $PayUPassedLog = PaymentLog::create([
                                    "order_id" => $basket_order_ids[$countp],
                                    "method_type" => $methodType,
                                    "config_data" => "",
                                    "post_data" => $request,
                                    "result_data" => $response,
                        ]);
                    }

                    /**
                     * Revert Vouchers.
                     */
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    if ($vouchers && sizeof($vouchers) > 0) {
                        for ($i = 0; $i < sizeof($vouchers); $i++) {

                            $voucher = Vouchers::find($vouchers[$i]["id"]);
                            $voucher->available = 1;
                            $voucher->save();
                        }
                    }

                    return $this->respondInternalError([
                                'message' => "PayU Payment Failed.",
                                'response_error' => "[BusinessController:getPayUPaymentStatus] PayU Payment Failed.",
                                'returnData' => $returnData,
                                'order_group_ref' => $order_group_ref
                    ]);
                }
            }

            return $this->respondInternalError([
                        'message' => "Internal Error: Could not check payment status for OrderGroupRef=" . $order_group_ref,
                        'response_error' => "[BusinessController:getPayUPaymentStatus] Internal Error: Could not check payment status for OrderGroupRef=" . $order_group_ref,
                        'order_group_ref' => $order_group_ref]);
        } catch (Exception $e) {
            $payu_setTransaction_log = new Logger('GetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addWarning("[BusinessController:getPayUPaymentStatus] Internal Error: " . $e->getMessage());
            return $this->respondInternalError([
                        'message' => "Internal Error: Your confirmation order could not proceed.",
                        'response_error' => "[BusinessController:getPayUPaymentStatus] Internal Error: " . $e->getMessage(),
                        'order_group_ref' => $order_group_ref]);
        }
    }

    public function completeBasketOrders() {
        $postData = Input::all();
        $order_group_ref = $postData['OrderGroupRef'];
        $status = $postData['status'];
        Log::info("[BusinessController:completeBasketOrders] Process: complete basket order(s) for OrderGroupRef=" . $order_group_ref);

        /**
         * Step1: Update order status for each order in basket.
         */
        $basket_orders = Order::ordergrouprefnotpaid($order_group_ref)->get()->toArray();
        if (!$basket_orders) {
            return $this->respondInternalError([
                        'message' => "Could not continue with your order confirmation. Your basket order(s) with OrderGroupRef=" . $order_group_ref . " cannot be found.",
                        'response_error' => "Could not continue with your order confirmation. Your basket order(s) with OrderGroupRef=" . $order_group_ref . " cannot be found.",
                        'order_group_ref' => $order_group_ref]);
        } else {
            $order_to_confirmation = array();
            for ($countOrder = 0; $countOrder < sizeof($basket_orders); $countOrder++) {
                $order = Order::find($basket_orders[$countOrder]['id']);
                if ($order->status == 2) {
                    $order->status = Order::$statusTypes[$status];
                    $order->save();
                    Log::info("[BusinessController:completeBasketOrders] Result: Order Number=" . $order->id . " updated to 'Active' with OrderGroupRef=" . $order_group_ref);
                    array_push($order_to_confirmation, $order);
                }
            }

            $mainuser = array();

            /**
             * Step2: Checking if order is of amrod ou normal rush. Calling respective smartfreight webservices
             */
            $basket_orders_to_mandrill_activation = array();
            for ($count_confirm = 0; $count_confirm < sizeof($order_to_confirmation); $count_confirm++) {
                $order = Order::with('orderItem', 'account')->find($order_to_confirmation[$count_confirm]['id']);
                $account = Account::with('user')->find($order->account_id);

                $sharedWallets = DB::table('shared_wallets')->where('account_id', '=', $account->id)->get();

                if ($sharedWallets && count($sharedWallets) > 0) {
                    $wallets = DB::table('wallets')
                        ->select('users.email', 'accounts.name')
                        ->join('accounts', 'accounts.id', '=', 'wallets.account_id')
                        ->join('users', 'users.id', '=', 'accounts.user_id')
                        ->where('wallets.id', '=', $sharedWallets[0]->wallet_id)
                        ->get();

                    if ($wallets && count($wallets) > 0) {
                        $mainuser['email'] = $wallets[0]->email;
                        $mainuser['name']  = $wallets[0]->name;
                    }
                }

                try {
                    $result = null;
                    $courier = new SmartFreight($order->id);
                    if ($order->linked_service === "AMROD") {
                        try {
                            Log::info("Updating loyalty - will fail silenty");
                            $orderLoyalty = AmrodLoyaltyController::getAmrodOrderLoyalty($order->id);
                            $orderLoyalty->valid = true;
                            $orderLoyalty->save();
                        } catch (Exception $e) {
                            Log::info("Failed to add loyalty for order id : " . $order->id);
                            Log::info("Exception error message: " . $e->getMessage());
                        }

                        Log::info("[BusinessController:completeBasketOrders] Info: Order=" . $order->id . " is AMROD.");
                        $result = $courier->ImportForAmrod($order->toArray());
// Log::info($result);
                    } else if ($order->linked_service === "TOGSA") {
                        Log::info("[BusinessController:completeBasketOrders] Info: Order=" . $order->id . " is TOGSA.");
                        $result = $courier->ImportForTogsa($order->toArray());
                    } else {
                        $result = $courier->Import($order->toArray());
                    }

                    $xml_import_response = str_replace('&gt;', '>', $result['xml_response']);
                    $xml_import_response = str_replace('&lt;', '<', $xml_import_response);

// Log Api Response
                    $log = SmartFreightLog::create([
                                "order_id" => $order->id,
                                "ref" => $order->id,
                                "api_method" => "Import",
                                "input_from_user" => json_encode($postData),
                                "api_post" => $result['api_post'],
                                "api_response" => $xml_import_response
                    ]);

                    $dataInput = [
                        'account' => json_encode($account),
                        'order' => json_encode($order),
                        'orderInfo' => $order->toArray()
                    ];

                    $info = [
                        'type' => "confirmation_email",
                        'order_id' => $order->id,
                        'data' => json_encode($dataInput),
                        'result' => json_encode($result),
                        'status' => QueueLog::$statusTypes['Queued'],
                    ];

                    $queue = QueueLog::create($info);

                    if (!empty($result) && $result['api_response']['ImportResult']['Connote']['trackingid'] != "undefined" && !empty($result['api_response']['ImportResult']['Connote']['trackingid']) && $result['api_response']['ImportResult']['Connote']['connotenumber'] != "undefined" && !empty($result['api_response']['ImportResult']['Connote']['connotenumber'])) {

                        $tracking_code = $result['api_response']['ImportResult']['Connote']['trackingid'];
                        $waybill = $result['api_response']['ImportResult']['Connote']['connotenumber'];

                        $order->tracking_code = $tracking_code;
                        $order->waybill = $waybill;
                        $order->save();

                        if ($order->linked_service === "AMROD") {

                            $amrod_orders = $order->toArray();
//Log::info("inside Amrod");
//Log::info($amrod_orders);
                            $document_numbers = array();
                            if (!empty($amrod_orders["order_item"]) && sizeof($amrod_orders["order_item"]) > 0) {
                                for ($i = 0; $i < sizeof($amrod_orders["order_item"]); $i ++) {
//Log::info("Amrod Order Item: ".$amrod_orders["order_item"][$i]["linked_service_order_ref"]);
                                    if ($amrod_orders["order_item"][$i]["linked_service_order_ref"] !== "N/A") {
//$document_numbers = $document_numbers . $amrod_orders["order_item"][$i]["linked_service_order_ref"];
                                        array_push($document_numbers, $amrod_orders["order_item"][$i]["linked_service_order_ref"]);
                                    }
                                }
                            }

                            try {
                                Log::info("[BusinessController:completeBasketOrders] AMROD - preparing doCreateWaybillRequest");
                                $reference = Carbon::now()->timestamp;
                                $amrodService = new Rush\Services\AmrodService($reference);
                                $body = array(
                                    "WaybillNumber" => $order->waybill,
                                    "CourierName" => $order->carrier_name,
                                    "Service" => $order->carrier_service,
                                    "CollectionDate" => date('d-m-Y', strtotime($order->created_at)),
                                    "DocumentNumbers" => $document_numbers
                                );

                                $amrod_accountId = $this->getProfileTokenByAccountId($order->account_id, $this->getAmrodServiceId());
                                $result = $amrodService->doCreateWaybill($amrod_accountId, $body);

                                if (!isset($result['api_response']) || !($result['api_response']->success)) {
                                    $this->warnSupportTeamOnConfirmOrderFailure($order->account_id, "[BusinessController:completeBasketOrders] Amrod doCreateWayBill failed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref);
                                }

                                $amrod_waybill_log = new Logger("AmrodWayBill");
                                $amrod_waybill_log->pushHandler(new StreamHandler(storage_path() . '/logs/amrod_waybill.log', Logger::INFO));
                                $amrod_waybill_log->addInfo("[BusinessController:completeBasketOrders] Amrod Waybill. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Tracking Code is " . $tracking_code . ", Waybill is " . $waybill . ". Amrod api post/response:");
                                $amrod_waybill_log->addInfo("Request: " . json_encode($body));
                                $amrod_waybill_log->addInfo("Response: " . json_encode($result));
                                $amrod_waybill_log->addInfo("-------------------------------------");
                            } catch (Exception $e) {
                                Log::info("[BusinessController:completeBasketOrders] Error: doCreateWayBill. Message=" . $e->getMessage());
                                $this->warnSupportTeamOnConfirmOrderFailure($order->account_id, "[BusinessController:completeBasketOrders] Amrod doCreateWayBill failed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Reason: " . $e->getMessage(), $e);
                            }
                        }

                        if ($order->linked_service === "TOGSA") {

                            $togsa_orders = $order->toArray();
//Log::info("inside TOGSA");
//Log::info($togsa_orders);
                            $document_numbers = array();
                            if (!empty($togsa_orders["order_item"]) && sizeof($togsa_orders["order_item"]) > 0) {
                                for ($i = 0; $i < sizeof($togsa_orders["order_item"]); $i ++) {
//Log::info("TOGSA Order Item: ".$togsa_orders["order_item"][$i]["linked_service_order_ref"]);
                                    if ($togsa_orders["order_item"][$i]["linked_service_order_ref"] !== "N/A") {
//$document_numbers = $document_numbers . $togsa_orders["order_item"][$i]["linked_service_order_ref"];
                                        array_push($document_numbers, $togsa_orders["order_item"][$i]["linked_service_order_ref"]);
                                    }
                                }
                            }

                            try {
                                Log::info("[BusinessController:completeBasketOrders] TOGSA - preparing doCreateWaybillRequest");
                                $reference = Carbon::now()->timestamp;
                                $togsaService = new Rush\Services\TradeOnlyGiftService($reference);
                                $body = array(
                                    "WaybillNumber" => $order->waybill,
                                    "CourierName" => $order->carrier_name,
                                    "Service" => $order->carrier_service,
                                    "CollectionDate" => date('d-m-Y', strtotime($order->created_at)),
                                    "OrderNumbers" => $document_numbers
                                );

                                $togsa_accountId = $this->getProfileTokenByAccountId($order->account_id, $this->getTogsaServiceId());
                                $result = $togsaService->doCreateWaybill($togsa_accountId, $body);

                                if (!isset($result['api_response']) || !($result['api_response']->success)) {
                                    $this->warnSupportTeamOnConfirmOrderFailure($order->account_id, "[BusinessController:completeBasketOrders] TOGSA doCreateWayBill failed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref);
                                }

                                $togsa_waybill_log = new Logger("TogsaWayBill");
                                $togsa_waybill_log->pushHandler(new StreamHandler(storage_path() . '/logs/togsa_waybill.log', Logger::INFO));
                                $togsa_waybill_log->addInfo("[BusinessController:completeBasketOrders] TOGSA Waybill. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Tracking Code is " . $tracking_code . ", Waybill is " . $waybill . ". TOGSA api post/response:");
                                $togsa_waybill_log->addInfo("Request: " . json_encode($body));
                                $togsa_waybill_log->addInfo("Response: " . json_encode($result));
                                $togsa_waybill_log->addInfo("-------------------------------------");
                            } catch (Exception $e) {
                                Log::info("[BusinessController:completeBasketOrders] Error: doCreateWayBill. Message=" . $e->getMessage());
                                $this->warnSupportTeamOnConfirmOrderFailure($order->account_id, "[BusinessController:completeBasketOrders] TOGSA doCreateWayBill failed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Reason: " . $e->getMessage(), $e);
                            }
                        }

                        //--- Call Nucleus Service to createwaybill
//                        $nucleus = new NucleusService();
//                        $nucleus_info = $nucleus->createWaybill($order);
                        //----------------------------------------------------------------------

                        $order_confirmation_passed_log = new Logger('BasketOrderConfirmation');
                        $order_confirmation_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_passed.log', Logger::INFO));
                        $order_confirmation_passed_log->addInfo("[BusinessController:completeBasketOrders] Order Confirmation Passed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Tracking Code is " . $tracking_code . ", Waybill is " . $waybill);
                        array_push($basket_orders_to_mandrill_activation, $order);
                    } else {
                        $order_confirmation_failed_log = new Logger('BasketOrderConfirmation');
                        $order_confirmation_failed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_failed.log', Logger::WARNING));
                        $order_confirmation_failed_log->addWarning("[BusinessController:completeBasketOrders] Order Confirmation Failed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Reason: Missing tracking code & waybill.");
                        $this->warnSupportTeamOnConfirmOrderFailure($order->account_id, "[BusinessController:completeBasketOrders] Order Confirmation Failed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Reason: Missing tracking code & waybill.");
                    }
                } catch (Exception $e) {
                    $order_confirmation_failed_log = new Logger('BasketOrderConfirmation');
                    $order_confirmation_failed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_failed.log', Logger::WARNING));
                    $order_confirmation_failed_log->addWarning("[BusinessController:completeBasketOrders] Order Confirmation Failed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Reason: " . $e->getMessage());
                    $this->warnSupportTeamOnConfirmOrderFailure($order->account_id, "[BusinessController:completeBasketOrders] Order Confirmation Failed. Order Number=" . $order->id . ", OrderGroupRef=" . $order_group_ref . ". Reason: " . $e->getMessage());
                }
            }

            if (sizeof($basket_orders_to_mandrill_activation) > 0) {
                $return_message = 'THANK YOU!  <br/> Your Payment was successful. <br/> Your invoice will be sent to you shortly.';
                //$return_message_1 = '';
                //$return_message_2 = '';
                try {
                    $account = $basket_orders_to_mandrill_activation[0]['account'];

                    if ($account->user_type == 4 || $account->user_type == 5 || $basket_orders_to_mandrill_activation[0]['total_order_price'] <= 0) {

                        $return_message = 'Your order was successfully processed. <br/> Your invoice will be sent to you shortly.';

//Delete basket for business plus users
                        $basketDel = Basket::with('basketItem')->accountbyid($account->id)->get();
                        foreach ($basketDel as $basketD) {
                            $basketD->delete();
                        }
                    }

                    $pdf_order_created_at = $basket_orders_to_mandrill_activation[0]['created_at'];
                    $pdf_order_group_ref = $basket_orders_to_mandrill_activation[0]['order_group_ref'];
                    $pdf_account_name = $basket_orders_to_mandrill_activation[0]['account']['name'];
                    $pdf_account_surname = $basket_orders_to_mandrill_activation[0]['account']['surname'];
                    $pdf_account_company = $basket_orders_to_mandrill_activation[0]['account']['company'];
                    $pdf_account_physical_address = $basket_orders_to_mandrill_activation[0]['account']['physical_address'];
                    $pdf_account_province = $basket_orders_to_mandrill_activation[0]['account']['province'];
                    $pdf_account_company_landline = $basket_orders_to_mandrill_activation[0]['account']['company_landline'];
                    $pdf_account_mobile_number = $basket_orders_to_mandrill_activation[0]['account']['mobile_number'];
                    $pdf_account_company_vat = $basket_orders_to_mandrill_activation[0]['account']['company_vat'];
                    $pdf_account_margin_mgmnt_groups_id = $basket_orders_to_mandrill_activation[0]['account']['margin_mgmnt_groups_id'];

                    $margin_group = DB::table('margin_mgmnt_groups')
                            ->select(DB::raw('discount_percentage,description'))
                            ->where('id', '=', $pdf_account_margin_mgmnt_groups_id)->get();

                    $get_discount_percentage =   array_map(function($o) { return $o->discount_percentage; }, $margin_group);
                    $get_discount_description =   array_map(function($o) { return $o->description; }, $margin_group);
                    $discount_percentage =$get_discount_percentage[0];
                    $discount_description =$get_discount_description[0];

                    $pdf_orders = array();
                    $pdf_payment_summary = array();
                    $grand_total = 0;
                    for ($taxCount = 0; $taxCount < sizeof($basket_orders_to_mandrill_activation); $taxCount++) {
                        $pdf_order['order_id'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_payment['order_number'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_order['sender_name'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_name'];
                        //$pdf_order['account_company'] = $pdf_account_company;
                        $pdf_order['account_company'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_company'];
                        $pdf_order['from_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['from_destination'];
                        $pdf_order['sender_email'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_email'];
                        $pdf_order['sender_tel'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_tel'];
                        $pdf_order['sender_mob'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_mob'];
                        $pdf_order['sender_ref'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_ref'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['receiver_name'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_name'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['to_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['to_destination'];
                        $pdf_order['receiver_email'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_email'];
                        $pdf_order['receiver_mobile'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_mobile'];
                        $pdf_order['receiver_phone'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_phone'];
                        $pdf_order['receiver_account_no'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_account_no'];
                        $pdf_order['waybill'] = $basket_orders_to_mandrill_activation[$taxCount]['waybill'];
                        $pdf_order['order_item'] = $basket_orders_to_mandrill_activation[$taxCount]['order_item'];
                        $pdf_order['carrier_name'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_name'];
                        $pdf_order['carrier_service'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_service'];
                        $pdf_order['description'] = $basket_orders_to_mandrill_activation[$taxCount]['item_desc_1'];
                        $pdf_order['document_numbers'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service_order_ref'];

                        //changes in costing from margin group
                        $pdf_order['net_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['gross_selling_price'];
                        $pdf_order['discount_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['discount_cost'];
                        $pdf_order['net_selling_price'] = $basket_orders_to_mandrill_activation[$taxCount]['net_selling_price'];
                        $pdf_order['vat_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['vat_cost'];
                        $pdf_order['total_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['total_cost_plus_vat'];
                        $pdf_order['courier_fee_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['courier_fee_plus_markup_cost'];
                        $pdf_order['insurance_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['insurance_plus_markup_cost'];
                        $pdf_order['discount_percentage'] = $discount_percentage;
                        $pdf_order['discount_description'] = $discount_description;

                        $pdf_order['net_cost'] = number_format((float) $pdf_order['net_cost'], 2, '.', '');
                        $pdf_order['vat_cost'] = number_format((float) $pdf_order['vat_cost'], 2, '.', '');
                        $pdf_order['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');
                        $pdf_order['courier_fee_plus_markup_cost'] = number_format((float) $pdf_order['courier_fee_plus_markup_cost'], 2, '.', '');
                        $pdf_order['insurance_plus_markup_cost'] = number_format((float) $pdf_order['insurance_plus_markup_cost'], 2, '.', '');

                        $pdf_payment['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');

                        $insurance = $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'];
                        if ($insurance === 'no items') {
                            $pdf_order['insurance'] = "(Insurance not included)";
                            $pdf_order['insurance_value'] = 0;
                        } else {
                            $pdf_order['insurance'] = "(incl. insurance for " . $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'] . " valued at R" . $basket_orders_to_mandrill_activation[$taxCount]['insurance_value'] . ")";
                            $pdf_order['insurance_value'] =  $basket_orders_to_mandrill_activation[$taxCount]['insurance_value']  ;
                        }

                        $pdf_order['order_service_type'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service'];

                        $user_email_ = DB::table('users')
                                ->select('email')
                                ->join('accounts', 'users.id', '=', 'accounts.user_id')
                                ->where('accounts.user_id', '=', $basket_orders_to_mandrill_activation[0]['account']['user_id'])
                                ->get();

                        $user_email = array_map(function($user_email_) {
                            return (array) $user_email_;
                        }, $user_email_);



                        if ($pdf_order['order_service_type'] == "RUSH") {
                            if ($user_email[0]['email'] == $pdf_order['sender_email']) {
                                $return_message = 'Your payment was successful. <br/> To complete your order, please print the waybill which has been emailed to you';
                                //$return_message = 'Your payment was successful.';
                                //$return_message_1 = 'To complete your order, please print the waybill which has been emailed to you';
                            } else {
                                $return_message = 'Your payment was successful. <br/> To complete your order, please make sure the waybill is printed. <br/> This has been emailed to the pick-up address.';
                                //$return_message = 'Your payment was successful.';
                                //$return_message_1 = 'To complete your order, please make sure the waybill is printed.';
                                //$return_message_2 = 'This has been emailed to the pick-up address.';
                            }
                        }

                        /*
                         * Author : Soun
                         * Date : 13.10.2016
                         * Description : Get waybill from IFS, Store to server, send as attachement to sender then delete from server
                         */

                        $order_confirmation_failed_log = new Logger('BasketOrderConfirmation');
                        $order_confirmation_failed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_failed.log', Logger::WARNING));
                        $order_confirmation_failed_log->addWarning("[BusinessController:completeBasketOrders] Trackingr=" . $basket_orders_to_mandrill_activation[$taxCount]['tracking_code']);
                        //get waybill from IFS
//                        $file = "http://www.smartfreight.com/tracking/webprint/showpdf?tid=" . $basket_orders_to_mandrill_activation[$taxCount]['tracking_code'] . "&pl=True&pm=True&pc=True&psp=True";
//
//                        $json = file_get_contents($file);
//                        $obj = json_decode($json);
//
//
//                        $waybillName = "waybill_" . $pdf_order['order_id'] . ".pdf";
//
//                        $waybillSavePath = "waybills/" . $waybillName;
//                        //save file to public/waybills
//                        file_put_contents($waybillSavePath, fopen($obj->url, 'r'));
//                        //get file for attachment
//                        $waybill = file_get_contents($waybillSavePath);
//
//                        $waybill = base64_encode($waybill);
//
//                        $mandrill = new MandrillService();
//                        $mandrill->sendWayBill($pdf_order['sender_name'], $pdf_order['sender_email'], $pdf_order['order_id'], $waybill);
//                        //delete from server
//                        unlink($waybillSavePath);

                        /*
                         * End
                         * Author Soun
                         */

                        $grand_total = $basket_orders_to_mandrill_activation[$taxCount]['total_order_price'];

                        array_push($pdf_orders, $pdf_order);
                        array_push($pdf_payment_summary, $pdf_payment);
                    }

                    $new_invoice = new Invoice();
                    $new_invoice->id = 'Internal';
                    if ($account->user_type != 5) {
                        $new_invoice = Invoice::create(["order_group_ref" => $pdf_order_group_ref]);
                    }

                    $pdf_vouchers = array();
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    for ($i = 0; $i < sizeof($vouchers); $i++) {
                        $voucher["discount_code"] = $vouchers[$i]["voucher_code"];
                        $voucher["discount_amount"] = $vouchers[$i]["amount"];
                        array_push($pdf_vouchers, $voucher);
                    }

                    $total_amount_due = 0;
                    $pdf_debts = array();
                    $debts = DB::table('debtors')
                                    ->select(DB::raw('*'))
                                    ->where('order_group_ref', '=', $order_group_ref)->get();
                    $debts = (array) (json_decode(json_encode($debts), true));

                    for ($i = 0; $i < sizeof($debts); $i++) {
                        $invoice = DB::table('invoice')
                                        ->select(DB::raw('*'))
                                        ->where('order_group_ref', '=', $order_group_ref)->get();
                        $invoice = (array) (json_decode(json_encode($invoice), true));
                        if ($debts[$i]["invoice"] == 0 || $debts[$i]["invoice"] == null) {
                            $debt['invoice'] = $invoice[0]['id'];
                        } else {
                            $debt['invoice'] = $debts[$i]["invoice"];
                        }
                        $debt["amount"] = $debts[$i]["amount"];
                        $debt["description"] = $debts[$i]["description"];
                        $total_amount_due = (float) $total_amount_due + (float) $debt["amount"];
                        array_push($pdf_debts, $debt);
                    }

                    $data = [
                        'logo' => 'imgs/rush-slider-logo2.jpg',
                        'pdf_order_created_at' => $pdf_order_created_at,
                        'pdf_user_type' => $account->user_type,
                        'pdf_new_invoice_number' => $new_invoice->id,
                        'pdf_account_surname' => $pdf_account_surname,
                        'pdf_account_name' => $pdf_account_name,
                        'pdf_account_company' => $pdf_account_company,
                        'pdf_account_physical_address' => $pdf_account_physical_address,
                        'pdf_account_province' => $pdf_account_province,
                        'pdf_account_company_landline' => $pdf_account_company_landline,
                        'pdf_account_mobile_number' => $pdf_account_mobile_number,
                        'pdf_account_company_vat' => $pdf_account_company_vat,
                        'pdf_orders' => $pdf_orders,
                        'pdf_vouchers' => $pdf_vouchers,
                        'pdf_grand_total' => $grand_total,
                        'pdf_payment_summary' => $pdf_payment_summary,
                        'pdf_debts' => $pdf_debts,
                        'pdf_total_amount_due' => $total_amount_due,
                        'pdf_reinvoicing' => false
                    ];
                    $pdf = PDF::loadView('invoice_basket', $data);
                    $mandrill = new MandrillService();
                    $sendBasketOrderEmail = $mandrill->sendBasketOrderConfirmation($account, $new_invoice->id, $pdf, $mainuser);

                    $order_basket_confirmation_passed_log = new Logger('BasketOrderConfirmation');
                    $order_basket_confirmation_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_passed.log', Logger::INFO));
                    $order_basket_confirmation_passed_log->addInfo("[BusinessController:completeBasketOrders] Sent email for OrderGroupRef=" . $order_group_ref . " Result: " . json_encode($sendBasketOrderEmail));
                } catch (Exception $e) {
                    $this->warnSupportTeamOnConfirmOrderFailure($order->account_id, "Could not send TAX BASKET INVOICE PDF for OrderGroupRef=" . $order_group_ref . ". Error:" . $e->getMessage());
                }
                return $this->respond([
                            'message' => $return_message,
                            //'message_2' => $return_message_1,
                            //'message_3' => $return_message_2,
                            'redirect' => Config::get('payuConfig.payu_rpp.refreshRedirectUrl')
                ]);
            } else {
                $this->warnSupportTeamOnConfirmOrderFailure($order->account_id, "OrderGroupRef=" . $order_group_ref . ". Payment succecssful but order was not triggered. MUST TRIGER MANUALLY.");
//                return $this->respondInternalError([
//                            'message' => "Could not continue with your order confirmation with OrderGroupRef=" . $order_group_ref . ". Please contact Support.",
//                            'response_error' => "Could not continue with your order confirmation with OrderGroupRef=" . $order_group_ref . ". Please contact Support.",
//                            'order_group_ref' => $order_group_ref]);

                return $this->respondInternalError([
                            'message' => "Your payment was successful. \n To complete your order, please print the waybill which has been emailed to you",
                            'response_error' => 'Your payment was successful. To complete your order, please print the waybill which has been emailed to you',
                            'order_group_ref' => $order_group_ref]);
            }
        }
    }

    private function getProfileTokenByAccountId($accountId, $serviceId) {
        $accountService = AccountService::where("account_id", '=', $accountId)->where("service_id", '=', $serviceId)->get();
        if (!$accountService || $accountService->isEmpty()) {
            return $this->respondNotFound("Account not found.");
        }
        $serviceAttributes = ServiceAttributes::where("account_service_id", '=', $accountService->first()->id)->where('key', '=', 'profileToken')->get();
        if (!$serviceAttributes || $serviceAttributes->isEmpty()) {
            return $this->respondNotFound("Profile Token not found.");
        }
        return $serviceAttributes->first()->value;
    }

    private function getAmrodServiceId() {
        $serviceAmrod = Service::getServiceByReference('AMROD')->get();
        if ($serviceAmrod->isEmpty()) {
            $service = Service::create(['name' => 'Amrod', 'reference' => 'AMROD']);
            return $service->id;
        } else {
            return $serviceAmrod->first()->id;
        }
    }

    private function getTogsaServiceId() {
        $serviceTogsa = Service::getServiceByReference('TOGSA')->get();
        if ($serviceTogsa->isEmpty()) {
            $service = Service::create(['name' => 'Trade Only Gift', 'reference' => 'TOGSA']);
            return $service->id;
        } else {
            return $serviceTogsa->first()->id;
        }
    }

    private function warnSupportTeamOnConfirmOrderFailure($accountId, $errorMessage) {

        try {
            $mandrill = new MandrillService();
            $sendNotificationEmail = $mandrill->sendRushBasketSupportOnFailure($accountId, $errorMessage);
            Log::info('[BusinessController:warnSupportTeamOnConfirmOrderFailure] Process: Sent Email to Rush Support Team: ' . json_encode($sendNotificationEmail));
        } catch (Exception $e) {
            Log::info("[BusinessController:warnSupportTeamOnConfirmOrderFailure] Error: " . $e->getMessage());
            Log::info("[BusinessController:warnSupportTeamOnConfirmOrderFailure] StackTrace: " . $e->getTraceAsString());
        }
    }

    public function notifyRushBasketSupport() {

        $postData = Input::all();
        $order_group_ref = $postData['orderGroupRef'];
        $error = $postData['responseError'];
        $process = $postData['process'];
        $account_id = $postData['accountId'];

        $errorMessage = "";
        if ($order_group_ref == -1) {
            $errorMessage = "Error in processing " . $process . " Error Message: " . $error;
        } else {
            $errorMessage = "Error in processing " . $process . " for OrderGroupRef=" . $order_group_ref . " Error Message: " . $error;
        }
        $this->warnSupportTeamOnConfirmOrderFailure($account_id, $errorMessage);
    }

    public function sendDebtsRecoveryEmail($order_group_ref) {

        $debt = Debtors::OrderGroupRef($order_group_ref)->get();

        $invoice = Invoice::OrderGroupRef($order_group_ref)->get();

        if (!$invoice && sizeof($invoice) <= 0) {
            return $this->respondInternalError([
                        'data' => 'Invoice number does not exist.'
            ]);
        }
        $account = Account::find($debt[0]['account_id']);
        $pdf = $this->generateReInvoicingTaxInvoicePDF($order_group_ref);

        try {
            $mandrill = new MandrillService();
            $mandrill->sendDebtorEmailNotificationPayU($account, $invoice[0]['id'], $pdf);
        } catch (Exception $e) {
            Log::info("Failed to send reminder email. Error message: " . $e->getMessage());
        }

        return $this->respond([
                    'data' => 'success.'
        ]);
    }

    public function downloadInvoiceByOrderId($id) {

    }

    public function downloadInvoiceByOrderGroupRef($ordergroupref) {

    }

    public function resendInvoiceByOrderId() {
        $id = Input::get('order_id');

        $basket_orders = Order::whereId($id)->get();
        $order_group_ref = $basket_orders[0]['order_group_ref'];


        Log::info("[BusinessController:generateOnlyBasketInvoice] Process: generate basket invoice for OrderGroupRef=" . $order_group_ref);

        if (!$basket_orders) {
            return $this->respondInternalError([
                        'message' => "Could not continue with your order confirmation. Your basket order(s) with OrderGroupRef=" . $order_group_ref . " cannot be found."
            ]);
        } else {
            $basket_orders_to_mandrill_activation = array();
            for ($countOrder = 0; $countOrder < sizeof($basket_orders); $countOrder++) {
                $order = Order::with('orderItem', 'account')->find($basket_orders[$countOrder]['id']);
                $account = Account::with('user')->find($order->account_id);
                array_push($basket_orders_to_mandrill_activation, $order);
            }

            if (sizeof($basket_orders_to_mandrill_activation) > 0) {
                try {
                    $account = $basket_orders_to_mandrill_activation[0]['account'];

                    $pdf_order_created_at = $basket_orders_to_mandrill_activation[0]['created_at'];
                    $pdf_order_group_ref = $basket_orders_to_mandrill_activation[0]['order_group_ref'];
                    $pdf_account_name = $basket_orders_to_mandrill_activation[0]['account']['name'];
                    $pdf_account_surname = $basket_orders_to_mandrill_activation[0]['account']['surname'];
                    $pdf_account_company = $basket_orders_to_mandrill_activation[0]['account']['company'];
                    $pdf_account_physical_address = $basket_orders_to_mandrill_activation[0]['account']['physical_address'];
                    $pdf_account_province = $basket_orders_to_mandrill_activation[0]['account']['province'];
                    $pdf_account_company_landline = $basket_orders_to_mandrill_activation[0]['account']['company_landline'];
                    $pdf_account_mobile_number = $basket_orders_to_mandrill_activation[0]['account']['mobile_number'];
                    $pdf_account_company_vat = $basket_orders_to_mandrill_activation[0]['account']['company_vat'];

                    $pdf_account_margin_mgmnt_groups_id = $basket_orders_to_mandrill_activation[0]['account']['margin_mgmnt_groups_id'];

                    $margin_group = DB::table('margin_mgmnt_groups')
                            ->select(DB::raw('discount_percentage,description'))
                            ->where('id', '=', $pdf_account_margin_mgmnt_groups_id)->get();

                    $get_discount_percentage =   array_map(function($o) { return $o->discount_percentage; }, $margin_group);
                    $get_discount_description =   array_map(function($o) { return $o->description; }, $margin_group);
                    $discount_percentage =$get_discount_percentage[0];
                    $discount_description =$get_discount_description[0];

                    $pdf_orders = array();
                    $pdf_payment_summary = array();
                    $grand_total = 0;
                    for ($taxCount = 0; $taxCount < sizeof($basket_orders_to_mandrill_activation); $taxCount++) {
                        $pdf_order['order_id'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_payment['order_number'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_order['sender_name'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_name'];
                        $pdf_order['account_company'] = $pdf_account_company;
                        $pdf_order['from_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['from_destination'];
                        $pdf_order['sender_email'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_email'];
                        $pdf_order['sender_tel'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_tel'];
                        $pdf_order['sender_mob'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_mob'];
                        $pdf_order['sender_ref'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_ref'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['receiver_name'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_name'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['to_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['to_destination'];
                        $pdf_order['receiver_email'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_email'];
                        $pdf_order['receiver_mobile'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_mobile'];
                        $pdf_order['receiver_phone'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_phone'];
                        $pdf_order['receiver_account_no'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_account_no'];
                        $pdf_order['waybill'] = $basket_orders_to_mandrill_activation[$taxCount]['waybill'];
                        $pdf_order['order_item'] = $basket_orders_to_mandrill_activation[$taxCount]['order_item'];
                        for ($order_item_count = 0; $order_item_count < sizeof($pdf_order['order_item']); $order_item_count++) {
                            if ($pdf_order['order_item'][$order_item_count]['parcel_desc'] == null || $pdf_order['order_item'][$order_item_count]['parcel_desc'] == '') {
                                $pdf_order['order_item'][$order_item_count]['parcel_desc'] = 'N/A';
                            }
                        }
                        $pdf_order['carrier_name'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_name'];
                        $pdf_order['carrier_service'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_service'];
                        $pdf_order['description'] = $basket_orders_to_mandrill_activation[$taxCount]['item_desc_1'];
                        $pdf_order['document_numbers'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service_order_ref'];

                        //changes in costing from margin group
                        $pdf_order['net_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['gross_selling_price'];
                        $pdf_order['discount_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['discount_cost'];
                        $pdf_order['net_selling_price'] = $basket_orders_to_mandrill_activation[$taxCount]['net_selling_price'];
                        $pdf_order['vat_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['vat_cost'];
                        $pdf_order['total_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['total_cost_plus_vat'];
                        $pdf_order['courier_fee_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['courier_fee_plus_markup_cost'];
                        $pdf_order['insurance_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['insurance_plus_markup_cost'];
                        $pdf_order['discount_percentage'] = $discount_percentage;
                        $pdf_order['discount_description'] = $discount_description;

                        $pdf_order['net_cost'] = number_format((float) $pdf_order['net_cost'], 2, '.', '');
                        $pdf_order['vat_cost'] = number_format((float) $pdf_order['vat_cost'], 2, '.', '');
                        $pdf_order['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');
                        $pdf_order['courier_fee_plus_markup_cost'] = number_format((float) $pdf_order['courier_fee_plus_markup_cost'], 2, '.', '');
                        $pdf_order['insurance_plus_markup_cost'] = number_format((float) $pdf_order['insurance_plus_markup_cost'], 2, '.', '');

                        $pdf_payment['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');

                        $insurance = $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'];
                        if ($insurance === 'no items') {
                            $pdf_order['insurance'] = "(Insurance not included)";
                            $pdf_order['insurance_value'] = 0;
                        } else {
                            $pdf_order['insurance'] = "(incl. insurance for " . $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'] . " valued at R" . $basket_orders_to_mandrill_activation[$taxCount]['insurance_value'] . ")";
                            $pdf_order['insurance_value'] =  $basket_orders_to_mandrill_activation[$taxCount]['insurance_value']  ;
                        }

                        $pdf_order['order_service_type'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service'];
                        if ($pdf_order['order_service_type'] == "RUSH") {
                            $return_message = 'Your Payment was successful. Please print your waybill which has been emailed to you.';
                        }

                        $grand_total = $basket_orders_to_mandrill_activation[$taxCount]['total_order_price'];

                        array_push($pdf_orders, $pdf_order);
                        array_push($pdf_payment_summary, $pdf_payment);
                    }

                    $new_invoice = new Invoice();
                    $new_invoice->id = 'Internal';
                    if ($account->user_type != 5) {
                        $new_invoice = Invoice::Ordergroupref($order_group_ref)->first();
                        //$new_invoice = Invoice::create(["order_group_ref" => $pdf_order_group_ref]);
                    }

                    $pdf_vouchers = array();
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    for ($i = 0; $i < sizeof($vouchers); $i++) {
                        $voucher["discount_code"] = $vouchers[$i]["voucher_code"];
                        $voucher["discount_amount"] = $vouchers[$i]["amount"];
                        array_push($pdf_vouchers, $voucher);
                    }

                    $total_amount_due = 0;
                    $pdf_debts = array();
                    $debts = DB::table('debtors')
                                    ->select(DB::raw('*'))
                                    ->where('order_group_ref', '=', $order_group_ref)->get();
                    $debts = (array) (json_decode(json_encode($debts), true));

                    for ($i = 0; $i < sizeof($debts); $i++) {
                        $invoice = DB::table('invoice')
                                        ->select(DB::raw('*'))
                                        ->where('order_group_ref', '=', $order_group_ref)->get();
                        $invoice = (array) (json_decode(json_encode($invoice), true));
                        if ($debts[$i]["invoice"] == 0 || $debts[$i]["invoice"] == null) {
                            $debt['invoice'] = $invoice[0]['id'];
                        } else {
                            $debt['invoice'] = $debts[$i]["invoice"];
                        }
                        $debt["amount"] = $debts[$i]["amount"];
                        $debt["description"] = $debts[$i]["description"];
                        $total_amount_due = (float) $total_amount_due + (float) $debt["amount"];
                        array_push($pdf_debts, $debt);
                    }

                    $data = [
                        'logo' => 'imgs/rush-slider-logo2.jpg',
                        'pdf_order_created_at' => $pdf_order_created_at,
                        'pdf_user_type' => $account->user_type,
                        'pdf_new_invoice_number' => $new_invoice->id,
                        'pdf_account_surname' => $pdf_account_surname,
                        'pdf_account_name' => $pdf_account_name,
                        'pdf_account_company' => $pdf_account_company,
                        'pdf_account_physical_address' => $pdf_account_physical_address,
                        'pdf_account_province' => $pdf_account_province,
                        'pdf_account_company_landline' => $pdf_account_company_landline,
                        'pdf_account_mobile_number' => $pdf_account_mobile_number,
                        'pdf_account_company_vat' => $pdf_account_company_vat,
                        'pdf_orders' => $pdf_orders,
                        'pdf_vouchers' => $pdf_vouchers,
                        'pdf_grand_total' => $grand_total,
                        'pdf_payment_summary' => $pdf_payment_summary,
                        'pdf_debts' => $pdf_debts,
                        'pdf_total_amount_due' => $total_amount_due,
                        'pdf_reinvoicing' => false
                    ];

                    $pdf = PDF::loadView('invoice_basket', $data);
                    $mandrill = new MandrillService();
                    $sendBasketOrderEmail = $mandrill->sendBasketOrderConfirmation($account, $new_invoice->id, $pdf);

                    $order_basket_confirmation_passed_log = new Logger('BasketOrderConfirmation');
                    $order_basket_confirmation_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_passed.log', Logger::INFO));
                    $order_basket_confirmation_passed_log->addInfo("[BusinessController:generateOnlyBasketInvoice] Sent email for OrderGroupRef=" . $order_group_ref . " Result: " . json_encode($sendBasketOrderEmail));
                } catch (Exception $e) {
                    return $this->respondInternalError([
                                'message' => "Internal Error: " . $e->getMessage()]);
                }

                return $this->respond([
                            'message' => 'Success.'
                ]);
            } else {
                return $this->respondInternalError([
                            'message' => "Could not continue with your order confirmation with OrderGroupRef=" . $order_group_ref . ". Please contact Support."]);
            }
        }
    }

    public function resendInvoiceByOrderGroupRef() {
        $order_group_ref = Input::get('order_group_ref');

        $basket_orders = Order::ordergroupref($order_group_ref)->get()->toArray();
        Log::info("[BusinessController:generateOnlyBasketInvoice] Process: generate basket invoice for OrderGroupRef=" . $order_group_ref);

        if (!$basket_orders) {
            return $this->respondInternalError([
                        'message' => "Could not continue with your order confirmation. Your basket order(s) with OrderGroupRef=" . $order_group_ref . " cannot be found."
            ]);
        } else {
            $basket_orders_to_mandrill_activation = array();
            for ($countOrder = 0; $countOrder < sizeof($basket_orders); $countOrder++) {
                $order = Order::with('orderItem', 'account')->find($basket_orders[$countOrder]['id']);
                $account = Account::with('user')->find($order->account_id);
                array_push($basket_orders_to_mandrill_activation, $order);
            }

            if (sizeof($basket_orders_to_mandrill_activation) > 0) {
                try {
                    $account = $basket_orders_to_mandrill_activation[0]['account'];

                    $pdf_order_created_at = $basket_orders_to_mandrill_activation[0]['created_at'];
                    $pdf_order_group_ref = $basket_orders_to_mandrill_activation[0]['order_group_ref'];
                    $pdf_account_name = $basket_orders_to_mandrill_activation[0]['account']['name'];
                    $pdf_account_surname = $basket_orders_to_mandrill_activation[0]['account']['surname'];
                    $pdf_account_company = $basket_orders_to_mandrill_activation[0]['account']['company'];
                    $pdf_account_physical_address = $basket_orders_to_mandrill_activation[0]['account']['physical_address'];
                    $pdf_account_province = $basket_orders_to_mandrill_activation[0]['account']['province'];
                    $pdf_account_company_landline = $basket_orders_to_mandrill_activation[0]['account']['company_landline'];
                    $pdf_account_mobile_number = $basket_orders_to_mandrill_activation[0]['account']['mobile_number'];
                    $pdf_account_company_vat = $basket_orders_to_mandrill_activation[0]['account']['company_vat'];

                    $pdf_account_margin_mgmnt_groups_id = $basket_orders_to_mandrill_activation[0]['account']['margin_mgmnt_groups_id'];

                    $margin_group = DB::table('margin_mgmnt_groups')
                            ->select(DB::raw('discount_percentage,description'))
                            ->where('id', '=', $pdf_account_margin_mgmnt_groups_id)->get();

                    $get_discount_percentage =   array_map(function($o) { return $o->discount_percentage; }, $margin_group);
                    $get_discount_description =   array_map(function($o) { return $o->description; }, $margin_group);
                    $discount_percentage =$get_discount_percentage[0];
                    $discount_description =$get_discount_description[0];

                    $pdf_orders = array();
                    $pdf_payment_summary = array();
                    $grand_total = 0;
                    for ($taxCount = 0; $taxCount < sizeof($basket_orders_to_mandrill_activation); $taxCount++) {
                        $pdf_order['order_id'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_payment['order_number'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_order['sender_name'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_name'];
                        $pdf_order['account_company'] = $pdf_account_company;
                        $pdf_order['from_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['from_destination'];
                        $pdf_order['sender_email'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_email'];
                        $pdf_order['sender_tel'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_tel'];
                        $pdf_order['sender_mob'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_mob'];
                        $pdf_order['sender_ref'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_ref'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['receiver_name'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_name'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['to_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['to_destination'];
                        $pdf_order['receiver_email'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_email'];
                        $pdf_order['receiver_mobile'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_mobile'];
                        $pdf_order['receiver_phone'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_phone'];
                        $pdf_order['receiver_account_no'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_account_no'];
                        $pdf_order['waybill'] = $basket_orders_to_mandrill_activation[$taxCount]['waybill'];
                        $pdf_order['order_item'] = $basket_orders_to_mandrill_activation[$taxCount]['order_item'];
                        for ($order_item_count = 0; $order_item_count < sizeof($pdf_order['order_item']); $order_item_count++) {
                            if ($pdf_order['order_item'][$order_item_count]['parcel_desc'] == null || $pdf_order['order_item'][$order_item_count]['parcel_desc'] == '') {
                                $pdf_order['order_item'][$order_item_count]['parcel_desc'] = 'N/A';
                            }
                        }
                        $pdf_order['carrier_name'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_name'];
                        $pdf_order['carrier_service'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_service'];
                        $pdf_order['description'] = $basket_orders_to_mandrill_activation[$taxCount]['item_desc_1'];
                        $pdf_order['document_numbers'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service_order_ref'];

                        //changes in costing from margin group
                        $pdf_order['net_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['gross_selling_price'];
                        $pdf_order['discount_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['discount_cost'];
                        $pdf_order['net_selling_price'] = $basket_orders_to_mandrill_activation[$taxCount]['net_selling_price'];
                        $pdf_order['vat_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['vat_cost'];
                        $pdf_order['total_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['total_cost_plus_vat'];
                        $pdf_order['courier_fee_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['courier_fee_plus_markup_cost'];
                        $pdf_order['insurance_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['insurance_plus_markup_cost'];
                        $pdf_order['discount_percentage'] = $discount_percentage;
                        $pdf_order['discount_description'] = $discount_description;

                        $pdf_order['net_cost'] = number_format((float) $pdf_order['net_cost'], 2, '.', '');
                        $pdf_order['vat_cost'] = number_format((float) $pdf_order['vat_cost'], 2, '.', '');
                        $pdf_order['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');
                        $pdf_order['courier_fee_plus_markup_cost'] = number_format((float) $pdf_order['courier_fee_plus_markup_cost'], 2, '.', '');
                        $pdf_order['insurance_plus_markup_cost'] = number_format((float) $pdf_order['insurance_plus_markup_cost'], 2, '.', '');

                        $pdf_payment['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');

                        $insurance = $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'];
                        if ($insurance === 'no items') {
                            $pdf_order['insurance'] = "(Insurance not included)";
                            $pdf_order['insurance_value'] = 0;
                        } else {
                            $pdf_order['insurance'] = "(incl. insurance for " . $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'] . " valued at R" . $basket_orders_to_mandrill_activation[$taxCount]['insurance_value'] . ")";
                            $pdf_order['insurance_value'] =  $basket_orders_to_mandrill_activation[$taxCount]['insurance_value']  ;
                        }

                        $pdf_order['order_service_type'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service'];
                        if ($pdf_order['order_service_type'] == "RUSH") {
                            $return_message = 'Your Payment was successful. Please print your waybill which has been emailed to you.';
                        }

                        $grand_total = $basket_orders_to_mandrill_activation[$taxCount]['total_order_price'];

                        array_push($pdf_orders, $pdf_order);
                        array_push($pdf_payment_summary, $pdf_payment);
                    }

                    $new_invoice = new Invoice();
                    $new_invoice->id = 'Internal';
                    if ($account->user_type != 5) {
                        $new_invoice = Invoice::Ordergroupref($order_group_ref)->first();
                        //$new_invoice = Invoice::create(["order_group_ref" => $pdf_order_group_ref]);
                    }

                    $pdf_vouchers = array();
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    for ($i = 0; $i < sizeof($vouchers); $i++) {
                        $voucher["discount_code"] = $vouchers[$i]["voucher_code"];
                        $voucher["discount_amount"] = $vouchers[$i]["amount"];
                        array_push($pdf_vouchers, $voucher);
                    }

                    $total_amount_due = 0;
                    $pdf_debts = array();
                    $debts = DB::table('debtors')
                                    ->select(DB::raw('*'))
                                    ->where('order_group_ref', '=', $order_group_ref)->get();
                    $debts = (array) (json_decode(json_encode($debts), true));

                    for ($i = 0; $i < sizeof($debts); $i++) {
                        $invoice = DB::table('invoice')
                                        ->select(DB::raw('*'))
                                        ->where('order_group_ref', '=', $order_group_ref)->get();
                        $invoice = (array) (json_decode(json_encode($invoice), true));
                        if ($debts[$i]["invoice"] == 0 || $debts[$i]["invoice"] == null) {
                            $debt['invoice'] = $invoice[0]['id'];
                        } else {
                            $debt['invoice'] = $debts[$i]["invoice"];
                        }
                        $debt["amount"] = $debts[$i]["amount"];
                        $debt["description"] = $debts[$i]["description"];
                        $total_amount_due = (float) $total_amount_due + (float) $debt["amount"];
                        array_push($pdf_debts, $debt);
                    }

                    $data = [
                        'logo' => 'imgs/rush-slider-logo2.jpg',
                        'pdf_order_created_at' => $pdf_order_created_at,
                        'pdf_user_type' => $account->user_type,
                        'pdf_new_invoice_number' => $new_invoice->id,
                        'pdf_account_surname' => $pdf_account_surname,
                        'pdf_account_name' => $pdf_account_name,
                        'pdf_account_company' => $pdf_account_company,
                        'pdf_account_physical_address' => $pdf_account_physical_address,
                        'pdf_account_province' => $pdf_account_province,
                        'pdf_account_company_landline' => $pdf_account_company_landline,
                        'pdf_account_mobile_number' => $pdf_account_mobile_number,
                        'pdf_account_company_vat' => $pdf_account_company_vat,
                        'pdf_orders' => $pdf_orders,
                        'pdf_vouchers' => $pdf_vouchers,
                        'pdf_grand_total' => $grand_total,
                        'pdf_payment_summary' => $pdf_payment_summary,
                        'pdf_debts' => $pdf_debts,
                        'pdf_total_amount_due' => $total_amount_due,
                        'pdf_reinvoicing' => false
                    ];

                    $pdf = PDF::loadView('invoice_basket', $data);
                    $mandrill = new MandrillService();
                    $sendBasketOrderEmail = $mandrill->sendBasketOrderConfirmation($account, $new_invoice->id, $pdf);

                    $order_basket_confirmation_passed_log = new Logger('BasketOrderConfirmation');
                    $order_basket_confirmation_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_passed.log', Logger::INFO));
                    $order_basket_confirmation_passed_log->addInfo("[BusinessController:generateOnlyBasketInvoice] Sent email for OrderGroupRef=" . $order_group_ref . " Result: " . json_encode($sendBasketOrderEmail));
                } catch (Exception $e) {
                    return $this->respondInternalError([
                                'message' => "Internal Error: " . $e->getMessage()]);
                }

                return $this->respond([
                            'message' => 'Success.'
                ]);
            } else {
                return $this->respondInternalError([
                            'message' => "Could not continue with your order confirmation with OrderGroupRef=" . $order_group_ref . ". Please contact Support."]);
            }
        }
    }

    public function generateOnlyWechatInvoice() {

        $postData = Input::all();
        if (!isset($postData['order_id'])) {
            return $this->respondInternalError([
                        'message' => 'Missing order number'
            ]);
        }

        $order_id = $postData['order_id'];
        try {

            Log::info("[BusinessController:generateOnlyWechatInvoice] Process: finding order for sending order confirmation for orderId=" . $order_id);
            $order = Order::with('orderItem', 'account')->find($order_id);
            $account = Account::with('user')->find($order->account_id);
            $acc = $account->toArray();
            if (empty($order->sender_email)) {
                $order->email = $acc['user']['email'];
            } else {
                $order->email = $order->sender_email;
            }

            $orderInfo = $order->toArray();

            $new_invoice = Invoice::create(["order_group_ref" => $orderInfo['order_group_ref']]);

            $totCost = str_replace(',', '', $orderInfo['grand_tot_mrkup']) + str_replace(',', '', $orderInfo['insurance_cost']);
            $netCost = $orderInfo['total_cost_plus_markup'] + str_replace(',', '', $orderInfo['insurance_cost']);
            $vat = $orderInfo['gston_markup'];

            $data = [
                "logo" => 'imgs/rush-slider-logo.png',
                "order" => $orderInfo,
                "invoiceNumber" => $new_invoice->id,
                "insurance" => (boolean) $orderInfo['insurance'],
                "netCost" => $netCost,
                "vat" => $vat,
                "totCost" => $totCost,
                "invoice_number" => $new_invoice->id
            ];

            $pdf = PDF::loadView('invoice', $data);

            $result = array();
            $mandrill = new MandrillService();
            $sendActivationEmail = $mandrill->sendOrderConfirmation($result, $account, $order, $new_invoice->id, $pdf);

            Log::info('[BusinessController:generateOnlyWechatInvoice] Process: Send Email: ' . json_encode($sendActivationEmail));
            return $this->respond([
                        'message' => 'Success.'
            ]);
        } catch (Exception $e) {
            Log::info('[BusinessController:generateOnlyWechatInvoice] Internal Error: ' . $e->getMessage());
            return $this->respondInternalError([
                        'message' => 'Internal Error: Order number = ' . $order_id . '.' . $e->getMessage()
            ]);
        }
        return $this->respond([
                    'message' => 'Success.'
        ]);
    }

    public function generateInvoiceByOrderIdPDF($id) {

        $basket_orders = Order::whereId($id)->get();
        $order_group_ref = $basket_orders[0]['order_group_ref'];


        Log::info("[BusinessController:generateInvoiceByOrderIdPDF] Process: generate basket invoice for OrderGroupRef=" . $order_group_ref);

        if (!$basket_orders) {
            return $this->respondInternalError([
                        'message' => "Could not generate invoice with OrderGroupRef=" . $order_group_ref . " cannot be found."
            ]);
        } else {
            $basket_orders_to_mandrill_activation = array();
            for ($countOrder = 0; $countOrder < sizeof($basket_orders); $countOrder++) {
                $order = Order::with('orderItem', 'account')->find($basket_orders[$countOrder]['id']);
                $account = Account::with('user')->find($order->account_id);
                array_push($basket_orders_to_mandrill_activation, $order);
            }

            if (sizeof($basket_orders_to_mandrill_activation) > 0) {
                try {
                    $account = $basket_orders_to_mandrill_activation[0]['account'];

                    $pdf_order_created_at = $basket_orders_to_mandrill_activation[0]['created_at'];
                    $pdf_order_group_ref = $basket_orders_to_mandrill_activation[0]['order_group_ref'];
                    $pdf_account_name = $basket_orders_to_mandrill_activation[0]['account']['name'];
                    $pdf_account_surname = $basket_orders_to_mandrill_activation[0]['account']['surname'];
                    $pdf_account_company = $basket_orders_to_mandrill_activation[0]['account']['company'];
                    $pdf_account_physical_address = $basket_orders_to_mandrill_activation[0]['account']['physical_address'];
                    $pdf_account_province = $basket_orders_to_mandrill_activation[0]['account']['province'];
                    $pdf_account_company_landline = $basket_orders_to_mandrill_activation[0]['account']['company_landline'];
                    $pdf_account_mobile_number = $basket_orders_to_mandrill_activation[0]['account']['mobile_number'];
                    $pdf_account_company_vat = $basket_orders_to_mandrill_activation[0]['account']['company_vat'];
                    $pdf_account_margin_mgmnt_groups_id = $basket_orders_to_mandrill_activation[0]['account']['margin_mgmnt_groups_id'];

                    $margin_group = DB::table('margin_mgmnt_groups')
                            ->select(DB::raw('discount_percentage,description'))
                            ->where('id', '=', $pdf_account_margin_mgmnt_groups_id)->get();

                    $get_discount_percentage =   array_map(function($o) { return $o->discount_percentage; }, $margin_group);
                    $get_discount_description =   array_map(function($o) { return $o->description; }, $margin_group);
                    $discount_percentage =$get_discount_percentage[0];
                    $discount_description =$get_discount_description[0];

                    $pdf_orders = array();
                    $pdf_payment_summary = array();
                    $grand_total = 0;
                    for ($taxCount = 0; $taxCount < sizeof($basket_orders_to_mandrill_activation); $taxCount++) {
                        $pdf_order['order_id'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_payment['order_number'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_order['sender_name'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_name'];
                        $pdf_order['account_company'] = $pdf_account_company;
                        $pdf_order['from_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['from_destination'];
                        $pdf_order['sender_email'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_email'];
                        $pdf_order['sender_tel'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_tel'];
                        $pdf_order['sender_mob'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_mob'];
                        $pdf_order['sender_ref'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_ref'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['receiver_name'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_name'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['to_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['to_destination'];
                        $pdf_order['receiver_email'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_email'];
                        $pdf_order['receiver_mobile'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_mobile'];
                        $pdf_order['receiver_phone'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_phone'];
                        $pdf_order['receiver_account_no'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_account_no'];
                        $pdf_order['waybill'] = $basket_orders_to_mandrill_activation[$taxCount]['waybill'];
                        $pdf_order['order_item'] = $basket_orders_to_mandrill_activation[$taxCount]['order_item'];
                        for ($order_item_count = 0; $order_item_count < sizeof($pdf_order['order_item']); $order_item_count++) {
                            if ($pdf_order['order_item'][$order_item_count]['parcel_desc'] == null || $pdf_order['order_item'][$order_item_count]['parcel_desc'] == '') {
                                $pdf_order['order_item'][$order_item_count]['parcel_desc'] = 'N/A';
                            }
                        }
                        $pdf_order['carrier_name'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_name'];
                        $pdf_order['carrier_service'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_service'];
                        $pdf_order['description'] = $basket_orders_to_mandrill_activation[$taxCount]['item_desc_1'];
                        $pdf_order['document_numbers'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service_order_ref'];

                        //changes in costing from margin group
                        $pdf_order['net_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['gross_selling_price'];
                        $pdf_order['discount_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['discount_cost'];
                        $pdf_order['net_selling_price'] = $basket_orders_to_mandrill_activation[$taxCount]['net_selling_price'];
                        $pdf_order['vat_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['vat_cost'];
                        $pdf_order['total_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['total_cost_plus_vat'];
                        $pdf_order['courier_fee_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['courier_fee_plus_markup_cost'];
                        $pdf_order['insurance_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['insurance_plus_markup_cost'];
                        $pdf_order['discount_percentage'] = $discount_percentage;
                        $pdf_order['discount_description'] = $discount_description;

                        $pdf_order['net_cost'] = number_format((float) $pdf_order['net_cost'], 2, '.', '');
                        $pdf_order['vat_cost'] = number_format((float) $pdf_order['vat_cost'], 2, '.', '');
                        $pdf_order['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');
                        $pdf_order['courier_fee_plus_markup_cost'] = number_format((float) $pdf_order['courier_fee_plus_markup_cost'], 2, '.', '');
                        $pdf_order['insurance_plus_markup_cost'] = number_format((float) $pdf_order['insurance_plus_markup_cost'], 2, '.', '');

                        $pdf_payment['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');

                        $insurance = $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'];
                        if ($insurance === 'no items') {
                            $pdf_order['insurance'] = "(Insurance not included)";
                            $pdf_order['insurance_value'] = 0;
                        } else {
                            $pdf_order['insurance'] = "(incl. insurance for " . $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'] . " valued at R" . $basket_orders_to_mandrill_activation[$taxCount]['insurance_value'] . ")";
                            $pdf_order['insurance_value'] =  $basket_orders_to_mandrill_activation[$taxCount]['insurance_value']  ;
                        }

                        $pdf_order['order_service_type'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service'];
                        $grand_total = $basket_orders_to_mandrill_activation[$taxCount]['total_order_price'];

                        array_push($pdf_orders, $pdf_order);
                        array_push($pdf_payment_summary, $pdf_payment);
                    }

                    $new_invoice = new Invoice();
                    $new_invoice->id = 'Internal';
                    if ($account->user_type != 5) {
                        $new_invoice = Invoice::Ordergroupref($order_group_ref)->first();
                        //$new_invoice = Invoice::create(["order_group_ref" => $pdf_order_group_ref]);
                    }

                    $pdf_vouchers = array();
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    for ($i = 0; $i < sizeof($vouchers); $i++) {
                        $voucher["discount_code"] = $vouchers[$i]["voucher_code"];
                        $voucher["discount_amount"] = $vouchers[$i]["amount"];
                        array_push($pdf_vouchers, $voucher);
                    }

                    $total_amount_due = 0;
                    $pdf_debts = array();
                    $debts = DB::table('debtors')
                                    ->select(DB::raw('*'))
                                    ->where('order_group_ref', '=', $order_group_ref)->get();
                    $debts = (array) (json_decode(json_encode($debts), true));

                    for ($i = 0; $i < sizeof($debts); $i++) {
                        $invoice = DB::table('invoice')
                                        ->select(DB::raw('*'))
                                        ->where('order_group_ref', '=', $order_group_ref)->get();
                        $invoice = (array) (json_decode(json_encode($invoice), true));
                        if ($debts[$i]["invoice"] == 0 || $debts[$i]["invoice"] == null) {
                            $debt['invoice'] = $invoice[0]['id'];
                        } else {
                            $debt['invoice'] = $debts[$i]["invoice"];
                        }
                        $debt["amount"] = $debts[$i]["amount"];
                        $debt["description"] = $debts[$i]["description"];
                        $total_amount_due = (float) $total_amount_due + (float) $debt["amount"];
                        array_push($pdf_debts, $debt);
                    }

                    $data = [
                        'logo' => 'imgs/rush-slider-logo2.jpg',
                        'pdf_order_created_at' => $pdf_order_created_at,
                        'pdf_user_type' => $account->user_type,
                        'pdf_new_invoice_number' =>  $new_invoice->id,
                        'pdf_account_surname' => $pdf_account_surname,
                        'pdf_account_name' => $pdf_account_name,
                        'pdf_account_company' => $pdf_account_company,
                        'pdf_account_physical_address' => $pdf_account_physical_address,
                        'pdf_account_province' => $pdf_account_province,
                        'pdf_account_company_landline' => $pdf_account_company_landline,
                        'pdf_account_mobile_number' => $pdf_account_mobile_number,
                        'pdf_account_company_vat' => $pdf_account_company_vat,
                        'pdf_orders' => $pdf_orders,
                        'pdf_vouchers' => $pdf_vouchers,
                        'pdf_grand_total' => $grand_total,
                        'pdf_payment_summary' => $pdf_payment_summary,
                        'pdf_debts' => $pdf_debts,
                        'pdf_total_amount_due' => $total_amount_due,
                        'pdf_reinvoicing' => false
                    ];

                    $pdf = PDF::loadView('invoice_basket', $data);

                    return $pdf->download('invoice_basket.pdf');
                } catch (Exception $e) {
                    return $this->respondInternalError([
                                'message' => "Internal Error: " . $e->getMessage()]);
                }

                return $this->respond([
                            'message' => 'Success.'
                ]);
            } else {
                return $this->respondInternalError([
                            'message' => "Could not generate Invoice with OrderGroupRef=" . $order_group_ref . ". Please contact Support."]);
            }
        }
    }

    public function generateInvoiceByRefPDF($order_group_ref) {
        $basket_orders = Order::ordergroupref($order_group_ref)->get()->toArray();

        Log::info("[BusinessController:generateInvoiceByOrderIdPDF] Process: generate basket invoice for OrderGroupRef=" . $order_group_ref);

        if (!$basket_orders) {
            return $this->respondInternalError([
                        'message' => "Could not generate invoice with OrderGroupRef=" . $order_group_ref . " cannot be found."
            ]);
        } else {
            $basket_orders_to_mandrill_activation = array();
            for ($countOrder = 0; $countOrder < sizeof($basket_orders); $countOrder++) {
                $order = Order::with('orderItem', 'account')->find($basket_orders[$countOrder]['id']);
                $account = Account::with('user')->find($order->account_id);
                array_push($basket_orders_to_mandrill_activation, $order);
            }

            if (sizeof($basket_orders_to_mandrill_activation) > 0) {
                try {
                    $account = $basket_orders_to_mandrill_activation[0]['account'];

                    $pdf_order_created_at = $basket_orders_to_mandrill_activation[0]['created_at'];
                    $pdf_order_group_ref = $basket_orders_to_mandrill_activation[0]['order_group_ref'];
                    $pdf_account_name = $basket_orders_to_mandrill_activation[0]['account']['name'];
                    $pdf_account_surname = $basket_orders_to_mandrill_activation[0]['account']['surname'];
                    $pdf_account_company = $basket_orders_to_mandrill_activation[0]['account']['company'];
                    $pdf_account_physical_address = $basket_orders_to_mandrill_activation[0]['account']['physical_address'];
                    $pdf_account_province = $basket_orders_to_mandrill_activation[0]['account']['province'];
                    $pdf_account_company_landline = $basket_orders_to_mandrill_activation[0]['account']['company_landline'];
                    $pdf_account_mobile_number = $basket_orders_to_mandrill_activation[0]['account']['mobile_number'];
                    $pdf_account_company_vat = $basket_orders_to_mandrill_activation[0]['account']['company_vat'];

                    $pdf_account_margin_mgmnt_groups_id = $basket_orders_to_mandrill_activation[0]['account']['margin_mgmnt_groups_id'];

                    $margin_group = DB::table('margin_mgmnt_groups')
                            ->select(DB::raw('discount_percentage,description'))
                            ->where('id', '=', $pdf_account_margin_mgmnt_groups_id)->get();

                    $get_discount_percentage =   array_map(function($o) { return $o->discount_percentage; }, $margin_group);
                    $get_discount_description =   array_map(function($o) { return $o->description; }, $margin_group);
                    $discount_percentage =$get_discount_percentage[0];
                    $discount_description =$get_discount_description[0];

                    $pdf_orders = array();
                    $pdf_payment_summary = array();
                    $grand_total = 0;
                    for ($taxCount = 0; $taxCount < sizeof($basket_orders_to_mandrill_activation); $taxCount++) {
                        $pdf_order['order_id'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_payment['order_number'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_order['sender_name'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_name'];
                        $pdf_order['account_company'] = $pdf_account_company;
                        $pdf_order['from_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['from_destination'];
                        $pdf_order['sender_email'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_email'];
                        $pdf_order['sender_tel'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_tel'];
                        $pdf_order['sender_mob'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_mob'];
                        $pdf_order['sender_ref'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_ref'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['receiver_name'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_name'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['to_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['to_destination'];
                        $pdf_order['receiver_email'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_email'];
                        $pdf_order['receiver_mobile'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_mobile'];
                        $pdf_order['receiver_phone'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_phone'];
                        $pdf_order['receiver_account_no'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_account_no'];
                        $pdf_order['waybill'] = $basket_orders_to_mandrill_activation[$taxCount]['waybill'];
                        $pdf_order['order_item'] = $basket_orders_to_mandrill_activation[$taxCount]['order_item'];
                        for ($order_item_count = 0; $order_item_count < sizeof($pdf_order['order_item']); $order_item_count++) {
                            if ($pdf_order['order_item'][$order_item_count]['parcel_desc'] == null || $pdf_order['order_item'][$order_item_count]['parcel_desc'] == '') {
                                $pdf_order['order_item'][$order_item_count]['parcel_desc'] = 'N/A';
                            }
                        }
                        $pdf_order['carrier_name'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_name'];
                        $pdf_order['carrier_service'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_service'];
                        $pdf_order['description'] = $basket_orders_to_mandrill_activation[$taxCount]['item_desc_1'];
                        $pdf_order['document_numbers'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service_order_ref'];

                        //changes in costing from margin group
                        $pdf_order['net_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['gross_selling_price'];
                        $pdf_order['discount_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['discount_cost'];
                        $pdf_order['net_selling_price'] = $basket_orders_to_mandrill_activation[$taxCount]['net_selling_price'];
                        $pdf_order['vat_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['vat_cost'];
                        $pdf_order['total_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['total_cost_plus_vat'];
                        $pdf_order['courier_fee_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['courier_fee_plus_markup_cost'];
                        $pdf_order['insurance_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['insurance_plus_markup_cost'];
                        $pdf_order['discount_percentage'] = $discount_percentage;
                        $pdf_order['discount_description'] = $discount_description;

                        $pdf_order['net_cost'] = number_format((float) $pdf_order['net_cost'], 2, '.', '');
                        $pdf_order['vat_cost'] = number_format((float) $pdf_order['vat_cost'], 2, '.', '');
                        $pdf_order['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');
                        $pdf_order['courier_fee_plus_markup_cost'] = number_format((float) $pdf_order['courier_fee_plus_markup_cost'], 2, '.', '');
                        $pdf_order['insurance_plus_markup_cost'] = number_format((float) $pdf_order['insurance_plus_markup_cost'], 2, '.', '');

                        $pdf_payment['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');

                        $insurance = $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'];
                        if ($insurance === 'no items') {
                            $pdf_order['insurance'] = "(Insurance not included)";
                            $pdf_order['insurance_value'] = 0;
                        } else {
                            $pdf_order['insurance'] = "(incl. insurance for " . $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'] . " valued at R" . $basket_orders_to_mandrill_activation[$taxCount]['insurance_value'] . ")";
                            $pdf_order['insurance_value'] =  $basket_orders_to_mandrill_activation[$taxCount]['insurance_value']  ;
                        }
                        $pdf_order['order_service_type'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service'];
                        $grand_total = $basket_orders_to_mandrill_activation[$taxCount]['total_order_price'];

                        array_push($pdf_orders, $pdf_order);
                        array_push($pdf_payment_summary, $pdf_payment);
                    }

                    $new_invoice = new Invoice();
                    $new_invoice->id = 'Internal';
                    if ($account->user_type != 5) {
                        $new_invoice = Invoice::Ordergroupref($order_group_ref)->first();
                        //$new_invoice = Invoice::create(["order_group_ref" => $pdf_order_group_ref]);
                    }

                    $pdf_vouchers = array();
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    for ($i = 0; $i < sizeof($vouchers); $i++) {
                        $voucher["discount_code"] = $vouchers[$i]["voucher_code"];
                        $voucher["discount_amount"] = $vouchers[$i]["amount"];
                        array_push($pdf_vouchers, $voucher);
                    }

                    $total_amount_due = 0;
                    $pdf_debts = array();
                    $debts = DB::table('debtors')
                                    ->select(DB::raw('*'))
                                    ->where('order_group_ref', '=', $order_group_ref)->get();
                    $debts = (array) (json_decode(json_encode($debts), true));

                    for ($i = 0; $i < sizeof($debts); $i++) {
                        $invoice = DB::table('invoice')
                                        ->select(DB::raw('*'))
                                        ->where('order_group_ref', '=', $order_group_ref)->get();
                        $invoice = (array) (json_decode(json_encode($invoice), true));
                        if ($debts[$i]["invoice"] == 0 || $debts[$i]["invoice"] == null) {
                            $debt['invoice'] = $invoice[0]['id'];
                        } else {
                            $debt['invoice'] = $debts[$i]["invoice"];
                        }
                        $debt["amount"] = $debts[$i]["amount"];
                        $debt["description"] = $debts[$i]["description"];
                        $total_amount_due = (float) $total_amount_due + (float) $debt["amount"];
                        array_push($pdf_debts, $debt);
                    }

                    $data = [
                        'logo' => 'imgs/rush-slider-logo2.jpg',
                        'pdf_order_created_at' => $pdf_order_created_at,
                        'pdf_user_type' => $account->user_type,
                        'pdf_new_invoice_number' => (isset($new_invoice->id)? $new_invoice->id : 'Internal'),
                        'pdf_account_surname' => $pdf_account_surname,
                        'pdf_account_name' => $pdf_account_name,
                        'pdf_account_company' => $pdf_account_company,
                        'pdf_account_physical_address' => $pdf_account_physical_address,
                        'pdf_account_province' => $pdf_account_province,
                        'pdf_account_company_landline' => $pdf_account_company_landline,
                        'pdf_account_mobile_number' => $pdf_account_mobile_number,
                        'pdf_account_company_vat' => $pdf_account_company_vat,
                        'pdf_orders' => $pdf_orders,
                        'pdf_vouchers' => $pdf_vouchers,
                        'pdf_grand_total' => $grand_total,
                        'pdf_payment_summary' => $pdf_payment_summary,
                        'pdf_debts' => $pdf_debts,
                        'pdf_total_amount_due' => $total_amount_due,
                        'pdf_reinvoicing' => false
                    ];

                    $pdf = PDF::loadView('invoice_basket', $data);

                    return $pdf->download('invoice_basket.pdf');
                } catch (Exception $e) {
                    return $this->respondInternalError([
                                'message' => "Internal Error: " . $e->getMessage()]);
                }

                return $this->respond([
                            'message' => 'Success.'
                ]);
            } else {
                return $this->respondInternalError([
                            'message' => "Could not generate Invoice with OrderGroupRef=" . $order_group_ref . ". Please contact Support."]);
            }
        }
    }

    public function generateOnlyBasketInvoicePDF($id) {

//        $postData = Input::all();
        $order_group_ref = $id;

//        if (!isset($postData["order_group_ref"])) {
//            return $this->respondInternalError([
//                        'message' => "Order Group Reference is missing."
//            ]);
//        }

        Log::info("[BusinessController:generateOnlyBasketInvoicePDF] Process: generate basket invoice for OrderGroupRef=" . $order_group_ref);
        $basket_orders = Order::ordergroupref($order_group_ref)->get()->toArray();
        if (!$basket_orders) {
            return $this->respondInternalError([
                        'message' => "Could not continue with your order confirmation. Your basket order(s) with OrderGroupRef=" . $order_group_ref . " cannot be found."
            ]);
        } else {
            $basket_orders_to_mandrill_activation = array();
            for ($countOrder = 0; $countOrder < sizeof($basket_orders); $countOrder++) {
                $order = Order::with('orderItem', 'account')->find($basket_orders[$countOrder]['id']);
                $account = Account::with('user')->find($order->account_id);
                array_push($basket_orders_to_mandrill_activation, $order);
            }

            Log::info($basket_orders_to_mandrill_activation);

            if (sizeof($basket_orders_to_mandrill_activation) > 0) {
                try {
                    $account = $basket_orders_to_mandrill_activation[0]['account'];

                    $pdf_order_created_at = $basket_orders_to_mandrill_activation[0]['created_at'];
                    $pdf_order_group_ref = $basket_orders_to_mandrill_activation[0]['order_group_ref'];
                    $pdf_account_name = $basket_orders_to_mandrill_activation[0]['account']['name'];
                    $pdf_account_surname = $basket_orders_to_mandrill_activation[0]['account']['surname'];
                    $pdf_account_company = $basket_orders_to_mandrill_activation[0]['account']['company'];
                    $pdf_account_physical_address = $basket_orders_to_mandrill_activation[0]['account']['physical_address'];
                    $pdf_account_province = $basket_orders_to_mandrill_activation[0]['account']['province'];
                    $pdf_account_company_landline = $basket_orders_to_mandrill_activation[0]['account']['company_landline'];
                    $pdf_account_mobile_number = $basket_orders_to_mandrill_activation[0]['account']['mobile_number'];
                    $pdf_account_company_vat = $basket_orders_to_mandrill_activation[0]['account']['company_vat'];

                    $pdf_account_margin_mgmnt_groups_id = $basket_orders_to_mandrill_activation[0]['account']['margin_mgmnt_groups_id'];

                    $margin_group = DB::table('margin_mgmnt_groups')
                            ->select(DB::raw('discount_percentage,description'))
                            ->where('id', '=', $pdf_account_margin_mgmnt_groups_id)->get();

                    $get_discount_percentage =   array_map(function($o) { return $o->discount_percentage; }, $margin_group);
                    $get_discount_description =   array_map(function($o) { return $o->description; }, $margin_group);
                    $discount_percentage =$get_discount_percentage[0];
                    $discount_description =$get_discount_description[0];

                    $pdf_orders = array();
                    $pdf_payment_summary = array();
                    $grand_total = 0;
                    for ($taxCount = 0; $taxCount < sizeof($basket_orders_to_mandrill_activation); $taxCount++) {
                        $pdf_order['order_id'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_payment['order_number'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_order['sender_name'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_name'];
                        $pdf_order['account_company'] = $pdf_account_company;
                        $pdf_order['from_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['from_destination'];
                        $pdf_order['sender_email'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_email'];
                        $pdf_order['sender_tel'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_tel'];
                        $pdf_order['sender_mob'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_mob'];
                        $pdf_order['sender_ref'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_ref'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['receiver_name'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_name'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['to_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['to_destination'];
                        $pdf_order['receiver_email'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_email'];
                        $pdf_order['receiver_mobile'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_mobile'];
                        $pdf_order['receiver_phone'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_phone'];
                        $pdf_order['receiver_account_no'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_account_no'];
                        $pdf_order['waybill'] = $basket_orders_to_mandrill_activation[$taxCount]['waybill'];
                        $pdf_order['order_item'] = $basket_orders_to_mandrill_activation[$taxCount]['order_item'];
                        for ($order_item_count = 0; $order_item_count < sizeof($pdf_order['order_item']); $order_item_count++) {
                            if ($pdf_order['order_item'][$order_item_count]['parcel_desc'] == null || $pdf_order['order_item'][$order_item_count]['parcel_desc'] == '') {
                                $pdf_order['order_item'][$order_item_count]['parcel_desc'] = 'N/A';
                            }
                        }
                        $pdf_order['carrier_name'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_name'];
                        $pdf_order['carrier_service'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_service'];
                        $pdf_order['description'] = $basket_orders_to_mandrill_activation[$taxCount]['item_desc_1'];
                        $pdf_order['document_numbers'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service_order_ref'];

                        //changes in costing from margin group
                        $pdf_order['net_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['gross_selling_price'];
                        $pdf_order['discount_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['discount_cost'];
                        $pdf_order['net_selling_price'] = $basket_orders_to_mandrill_activation[$taxCount]['net_selling_price'];
                        $pdf_order['vat_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['vat_cost'];
                        $pdf_order['total_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['total_cost_plus_vat'];
                        $pdf_order['courier_fee_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['courier_fee_plus_markup_cost'];
                        $pdf_order['insurance_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['insurance_plus_markup_cost'];
                        $pdf_order['discount_percentage'] = $discount_percentage;
                        $pdf_order['discount_description'] = $discount_description;

                        $pdf_order['net_cost'] = number_format((float) $pdf_order['net_cost'], 2, '.', '');
                        $pdf_order['vat_cost'] = number_format((float) $pdf_order['vat_cost'], 2, '.', '');
                        $pdf_order['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');
                        $pdf_order['courier_fee_plus_markup_cost'] = number_format((float) $pdf_order['courier_fee_plus_markup_cost'], 2, '.', '');
                        $pdf_order['insurance_plus_markup_cost'] = number_format((float) $pdf_order['insurance_plus_markup_cost'], 2, '.', '');

                        $pdf_payment['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');

                        $insurance = $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'];
                        if ($insurance === 'no items') {
                            $pdf_order['insurance'] = "(Insurance not included)";
                            $pdf_order['insurance_value'] = 0;
                        } else {
                            $pdf_order['insurance'] = "(incl. insurance for " . $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'] . " valued at R" . $basket_orders_to_mandrill_activation[$taxCount]['insurance_value'] . ")";
                            $pdf_order['insurance_value'] =  $basket_orders_to_mandrill_activation[$taxCount]['insurance_value']  ;
                        }

                        $pdf_order['order_service_type'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service'];
                        if ($pdf_order['order_service_type'] == "RUSH") {
                            $return_message = 'Your Payment was successful. Please print your waybill which has been emailed to you.';
                        }

                        $grand_total = $basket_orders_to_mandrill_activation[$taxCount]['total_order_price'];

                        array_push($pdf_orders, $pdf_order);
                        array_push($pdf_payment_summary, $pdf_payment);
                    }

                    $new_invoice = new Invoice();
                    $new_invoice->id = 'Internal';
                    if ($account->user_type != 5) {
                        $new_invoice = Invoice::create(["order_group_ref" => $pdf_order_group_ref]);
                    }

                    $pdf_vouchers = array();
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    for ($i = 0; $i < sizeof($vouchers); $i++) {
                        $voucher["discount_code"] = $vouchers[$i]["voucher_code"];
                        $voucher["discount_amount"] = $vouchers[$i]["amount"];
                        array_push($pdf_vouchers, $voucher);
                    }

                    $total_amount_due = 0;
                    $pdf_debts = array();
                    $debts = DB::table('debtors')
                                    ->select(DB::raw('*'))
                                    ->where('order_group_ref', '=', $order_group_ref)->get();
                    $debts = (array) (json_decode(json_encode($debts), true));

                    for ($i = 0; $i < sizeof($debts); $i++) {
                        $invoice = DB::table('invoice')
                                        ->select(DB::raw('*'))
                                        ->where('order_group_ref', '=', $order_group_ref)->get();
                        $invoice = (array) (json_decode(json_encode($invoice), true));
                        if ($debts[$i]["invoice"] == 0 || $debts[$i]["invoice"] == null) {
                            $debt['invoice'] = $invoice[0]['id'];
                        } else {
                            $debt['invoice'] = $debts[$i]["invoice"];
                        }
                        $debt["amount"] = $debts[$i]["amount"];
                        $debt["description"] = $debts[$i]["description"];
                        $total_amount_due = (float) $total_amount_due + (float) $debt["amount"];
                        array_push($pdf_debts, $debt);
                    }

                    $data = [
                        'logo' => 'imgs/rush-slider-logo2.jpg',
                        'pdf_order_created_at' => $pdf_order_created_at,
                        'pdf_user_type' => $account->user_type,
                        'pdf_new_invoice_number' => $new_invoice->id,
                        'pdf_account_surname' => $pdf_account_surname,
                        'pdf_account_name' => $pdf_account_name,
                        'pdf_account_company' => $pdf_account_company,
                        'pdf_account_physical_address' => $pdf_account_physical_address,
                        'pdf_account_province' => $pdf_account_province,
                        'pdf_account_company_landline' => $pdf_account_company_landline,
                        'pdf_account_mobile_number' => $pdf_account_mobile_number,
                        'pdf_account_company_vat' => $pdf_account_company_vat,
                        'pdf_orders' => $pdf_orders,
                        'pdf_vouchers' => $pdf_vouchers,
                        'pdf_grand_total' => $grand_total,
                        'pdf_payment_summary' => $pdf_payment_summary,
                        'pdf_debts' => $pdf_debts,
                        'pdf_total_amount_due' => $total_amount_due,
                        'pdf_reinvoicing' => false
                    ];
                    Log::info($data);

                    $pdf = PDF::loadView('invoice_basket', $data);
//                            $mandrill = new MandrillService();
//                    $sendBasketOrderEmail = $mandrill->sendBasketOrderConfirmation($account, $new_invoice->id, $pdf);
//
//                    $order_basket_confirmation_passed_log = new Logger('BasketOrderConfirmation');
//                    $order_basket_confirmation_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_passed.log', Logger::INFO));
//                    $order_basket_confirmation_passed_log->addInfo("[BusinessController:generateOnlyBasketInvoice] Sent email for OrderGroupRef=" . $order_group_ref . " Result: " . json_encode($sendBasketOrderEmail));

                    return $pdf->download('invoice_basket.pdf');
//
                } catch (Exception $e) {
                    return $this->respondInternalError([
                                'message' => "Internal Error: " . $e->getMessage()]);
                }

                return $this->respond([
                            'message' => 'Success.'
                ]);
            } else {
                return $this->respondInternalError([
                            'message' => "Could not continue with your order confirmation with OrderGroupRef=" . $order_group_ref . ". Please contact Support."]);
            }
        }
    }

    public function generateOnlyBasketInvoice() {

        $postData = Input::all();
        $order_group_ref = $postData["order_group_ref"];

        if (!isset($postData["order_group_ref"])) {
            return $this->respondInternalError([
                        'message' => "Order Group Reference is missing."
            ]);
        }

        Log::info("[BusinessController:generateOnlyBasketInvoice] Process: generate basket invoice for OrderGroupRef=" . $order_group_ref);
        $basket_orders = Order::ordergroupref($order_group_ref)->get()->toArray();
        if (!$basket_orders) {
            return $this->respondInternalError([
                        'message' => "Could not continue with your order confirmation. Your basket order(s) with OrderGroupRef=" . $order_group_ref . " cannot be found."
            ]);
        } else {
            $basket_orders_to_mandrill_activation = array();
            for ($countOrder = 0; $countOrder < sizeof($basket_orders); $countOrder++) {
                $order = Order::with('orderItem', 'account')->find($basket_orders[$countOrder]['id']);
                $account = Account::with('user')->find($order->account_id);
                array_push($basket_orders_to_mandrill_activation, $order);
            }

            if (sizeof($basket_orders_to_mandrill_activation) > 0) {
                try {
                    $account = $basket_orders_to_mandrill_activation[0]['account'];

                    $pdf_order_created_at = $basket_orders_to_mandrill_activation[0]['created_at'];
                    $pdf_order_group_ref = $basket_orders_to_mandrill_activation[0]['order_group_ref'];
                    $pdf_account_name = $basket_orders_to_mandrill_activation[0]['account']['name'];
                    $pdf_account_surname = $basket_orders_to_mandrill_activation[0]['account']['surname'];
                    $pdf_account_company = $basket_orders_to_mandrill_activation[0]['account']['company'];
                    $pdf_account_physical_address = $basket_orders_to_mandrill_activation[0]['account']['physical_address'];
                    $pdf_account_province = $basket_orders_to_mandrill_activation[0]['account']['province'];
                    $pdf_account_company_landline = $basket_orders_to_mandrill_activation[0]['account']['company_landline'];
                    $pdf_account_mobile_number = $basket_orders_to_mandrill_activation[0]['account']['mobile_number'];
                    $pdf_account_company_vat = $basket_orders_to_mandrill_activation[0]['account']['company_vat'];

                    $pdf_account_margin_mgmnt_groups_id = $basket_orders_to_mandrill_activation[0]['account']['margin_mgmnt_groups_id'];

                    $margin_group = DB::table('margin_mgmnt_groups')
                            ->select(DB::raw('discount_percentage,description'))
                            ->where('id', '=', $pdf_account_margin_mgmnt_groups_id)->get();

                    $get_discount_percentage =   array_map(function($o) { return $o->discount_percentage; }, $margin_group);
                    $get_discount_description =   array_map(function($o) { return $o->description; }, $margin_group);
                    $discount_percentage =$get_discount_percentage[0];
                    $discount_description =$get_discount_description[0];

                    $pdf_orders = array();
                    $pdf_payment_summary = array();
                    $grand_total = 0;
                    for ($taxCount = 0; $taxCount < sizeof($basket_orders_to_mandrill_activation); $taxCount++) {
                        $pdf_order['order_id'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_payment['order_number'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_order['sender_name'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_name'];
                        $pdf_order['account_company'] = $pdf_account_company;
                        $pdf_order['from_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['from_destination'];
                        $pdf_order['sender_email'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_email'];
                        $pdf_order['sender_tel'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_tel'];
                        $pdf_order['sender_mob'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_mob'];
                        $pdf_order['sender_ref'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_ref'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['receiver_name'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_name'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['to_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['to_destination'];
                        $pdf_order['receiver_email'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_email'];
                        $pdf_order['receiver_mobile'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_mobile'];
                        $pdf_order['receiver_phone'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_phone'];
                        $pdf_order['receiver_account_no'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_account_no'];
                        $pdf_order['waybill'] = $basket_orders_to_mandrill_activation[$taxCount]['waybill'];
                        $pdf_order['order_item'] = $basket_orders_to_mandrill_activation[$taxCount]['order_item'];
                        for ($order_item_count = 0; $order_item_count < sizeof($pdf_order['order_item']); $order_item_count++) {
                            if ($pdf_order['order_item'][$order_item_count]['parcel_desc'] == null || $pdf_order['order_item'][$order_item_count]['parcel_desc'] == '') {
                                $pdf_order['order_item'][$order_item_count]['parcel_desc'] = 'N/A';
                            }
                        }
                        $pdf_order['carrier_name'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_name'];
                        $pdf_order['carrier_service'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_service'];
                        $pdf_order['description'] = $basket_orders_to_mandrill_activation[$taxCount]['item_desc_1'];
                        $pdf_order['document_numbers'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service_order_ref'];

                        //changes in costing from margin group
                        $pdf_order['net_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['gross_selling_price'];
                        $pdf_order['discount_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['discount_cost'];
                        $pdf_order['net_selling_price'] = $basket_orders_to_mandrill_activation[$taxCount]['net_selling_price'];
                        $pdf_order['vat_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['vat_cost'];
                        $pdf_order['total_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['total_cost_plus_vat'];
                        $pdf_order['courier_fee_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['courier_fee_plus_markup_cost'];
                        $pdf_order['insurance_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['insurance_plus_markup_cost'];
                        $pdf_order['discount_percentage'] = $discount_percentage;
                        $pdf_order['discount_description'] = $discount_description;

                        $pdf_order['net_cost'] = number_format((float) $pdf_order['net_cost'], 2, '.', '');
                        $pdf_order['vat_cost'] = number_format((float) $pdf_order['vat_cost'], 2, '.', '');
                        $pdf_order['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');
                        $pdf_order['courier_fee_plus_markup_cost'] = number_format((float) $pdf_order['courier_fee_plus_markup_cost'], 2, '.', '');
                        $pdf_order['insurance_plus_markup_cost'] = number_format((float) $pdf_order['insurance_plus_markup_cost'], 2, '.', '');

                        $pdf_payment['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');

                        $insurance = $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'];
                        if ($insurance === 'no items') {
                            $pdf_order['insurance'] = "(Insurance not included)";
                            $pdf_order['insurance_value'] = 0;
                        } else {
                            $pdf_order['insurance'] = "(incl. insurance for " . $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'] . " valued at R" . $basket_orders_to_mandrill_activation[$taxCount]['insurance_value'] . ")";
                            $pdf_order['insurance_value'] =  $basket_orders_to_mandrill_activation[$taxCount]['insurance_value']  ;
                        }

                        $pdf_order['order_service_type'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service'];
                        if ($pdf_order['order_service_type'] == "RUSH") {
                            $return_message = 'Your Payment was successful. Please print your waybill which has been emailed to you.';
                        }

                        $grand_total = $basket_orders_to_mandrill_activation[$taxCount]['total_order_price'];

                        array_push($pdf_orders, $pdf_order);
                        array_push($pdf_payment_summary, $pdf_payment);
                    }

                    $new_invoice = new Invoice();
                    $new_invoice->id = 'Internal';
                    if ($account->user_type != 5) {
                        $new_invoice = Invoice::create(["order_group_ref" => $pdf_order_group_ref]);
                    }

                    $pdf_vouchers = array();
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    for ($i = 0; $i < sizeof($vouchers); $i++) {
                        $voucher["discount_code"] = $vouchers[$i]["voucher_code"];
                        $voucher["discount_amount"] = $vouchers[$i]["amount"];
                        array_push($pdf_vouchers, $voucher);
                    }

                    $total_amount_due = 0;
                    $pdf_debts = array();
                    $debts = DB::table('debtors')
                                    ->select(DB::raw('*'))
                                    ->where('order_group_ref', '=', $order_group_ref)->get();
                    $debts = (array) (json_decode(json_encode($debts), true));

                    for ($i = 0; $i < sizeof($debts); $i++) {
                        $invoice = DB::table('invoice')
                                        ->select(DB::raw('*'))
                                        ->where('order_group_ref', '=', $order_group_ref)->get();
                        $invoice = (array) (json_decode(json_encode($invoice), true));
                        if ($debts[$i]["invoice"] == 0 || $debts[$i]["invoice"] == null) {
                            $debt['invoice'] = $invoice[0]['id'];
                        } else {
                            $debt['invoice'] = $debts[$i]["invoice"];
                        }
                        $debt["amount"] = $debts[$i]["amount"];
                        $debt["description"] = $debts[$i]["description"];
                        $total_amount_due = (float) $total_amount_due + (float) $debt["amount"];
                        array_push($pdf_debts, $debt);
                    }

                    $data = [
                        'logo' => 'imgs/rush-slider-logo2.jpg',
                        'pdf_order_created_at' => $pdf_order_created_at,
                        'pdf_user_type' => $account->user_type,
                        'pdf_new_invoice_number' => $new_invoice->id,
                        'pdf_account_surname' => $pdf_account_surname,
                        'pdf_account_name' => $pdf_account_name,
                        'pdf_account_company' => $pdf_account_company,
                        'pdf_account_physical_address' => $pdf_account_physical_address,
                        'pdf_account_province' => $pdf_account_province,
                        'pdf_account_company_landline' => $pdf_account_company_landline,
                        'pdf_account_mobile_number' => $pdf_account_mobile_number,
                        'pdf_account_company_vat' => $pdf_account_company_vat,
                        'pdf_orders' => $pdf_orders,
                        'pdf_vouchers' => $pdf_vouchers,
                        'pdf_grand_total' => $grand_total,
                        'pdf_payment_summary' => $pdf_payment_summary,
                        'pdf_debts' => $pdf_debts,
                        'pdf_total_amount_due' => $total_amount_due,
                        'pdf_reinvoicing' => false
                    ];

                    $pdf = PDF::loadView('invoice_basket', $data);
                    $mandrill = new MandrillService();
                    $sendBasketOrderEmail = $mandrill->sendBasketOrderConfirmation($account, $new_invoice->id, $pdf);

                    $order_basket_confirmation_passed_log = new Logger('BasketOrderConfirmation');
                    $order_basket_confirmation_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/orders_confirmation_passed.log', Logger::INFO));
                    $order_basket_confirmation_passed_log->addInfo("[BusinessController:generateOnlyBasketInvoice] Sent email for OrderGroupRef=" . $order_group_ref . " Result: " . json_encode($sendBasketOrderEmail));
                } catch (Exception $e) {
                    return $this->respondInternalError([
                                'message' => "Internal Error: " . $e->getMessage()]);
                }

                return $this->respond([
                            'message' => 'Success.'
                ]);
            } else {
                return $this->respondInternalError([
                            'message' => "Could not continue with your order confirmation with OrderGroupRef=" . $order_group_ref . ". Please contact Support."]);
            }
        }
    }

    public function generateReInvoicingTaxInvoicePDF($order_group_ref) {

        Log::info("[BusinessController:generateReInvoicingTaxInvoicePDF] Process: generate basket invoice for OrderGroupRef=" . $order_group_ref);
        $basket_orders = Order::ordergroupref($order_group_ref)->get()->toArray();
        if (!$basket_orders) {
            return null;
        } else {
            $basket_orders_to_mandrill_activation = array();
            for ($countOrder = 0; $countOrder < sizeof($basket_orders); $countOrder++) {
                $order = Order::with('orderItem', 'account')->find($basket_orders[$countOrder]['id']);
                $account = Account::with('user')->find($order->account_id);
                array_push($basket_orders_to_mandrill_activation, $order);
            }

            if (sizeof($basket_orders_to_mandrill_activation) > 0) {
                try {
                    $account = $basket_orders_to_mandrill_activation[0]['account'];

                    $pdf_order_created_at = $basket_orders_to_mandrill_activation[0]['created_at'];
                    $pdf_order_group_ref = $basket_orders_to_mandrill_activation[0]['order_group_ref'];
                    $pdf_account_name = $basket_orders_to_mandrill_activation[0]['account']['name'];
                    $pdf_account_surname = $basket_orders_to_mandrill_activation[0]['account']['surname'];
                    $pdf_account_company = $basket_orders_to_mandrill_activation[0]['account']['company'];
                    $pdf_account_physical_address = $basket_orders_to_mandrill_activation[0]['account']['physical_address'];
                    $pdf_account_province = $basket_orders_to_mandrill_activation[0]['account']['province'];
                    $pdf_account_company_landline = $basket_orders_to_mandrill_activation[0]['account']['company_landline'];
                    $pdf_account_mobile_number = $basket_orders_to_mandrill_activation[0]['account']['mobile_number'];
                    $pdf_account_company_vat = $basket_orders_to_mandrill_activation[0]['account']['company_vat'];

                    $pdf_account_margin_mgmnt_groups_id = $basket_orders_to_mandrill_activation[0]['account']['margin_mgmnt_groups_id'];

                    $margin_group = DB::table('margin_mgmnt_groups')
                            ->select(DB::raw('discount_percentage,description'))
                            ->where('id', '=', $pdf_account_margin_mgmnt_groups_id)->get();

                    $get_discount_percentage =   array_map(function($o) { return $o->discount_percentage; }, $margin_group);
                    $get_discount_description =   array_map(function($o) { return $o->description; }, $margin_group);
                    $discount_percentage =$get_discount_percentage[0];
                    $discount_description =$get_discount_description[0];

                    $pdf_orders = array();
                    $pdf_payment_summary = array();
                    $grand_total = 0;
                    for ($taxCount = 0; $taxCount < sizeof($basket_orders_to_mandrill_activation); $taxCount++) {
                        $pdf_order['order_id'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_payment['order_number'] = $basket_orders_to_mandrill_activation[$taxCount]['id'];
                        $pdf_order['sender_name'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_name'];
                        $pdf_order['account_company'] = $pdf_account_company;
                        $pdf_order['from_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['from_destination'];
                        $pdf_order['sender_email'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_email'];
                        $pdf_order['sender_tel'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_tel'];
                        $pdf_order['sender_mob'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_mob'];
                        $pdf_order['sender_ref'] = $basket_orders_to_mandrill_activation[$taxCount]['sender_ref'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['receiver_name'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_name'];
                        $pdf_order['receiver_contact'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_contact'];
                        $pdf_order['to_destination'] = $basket_orders_to_mandrill_activation[$taxCount]['to_destination'];
                        $pdf_order['receiver_email'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_email'];
                        $pdf_order['receiver_mobile'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_mobile'];
                        $pdf_order['receiver_phone'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_phone'];
                        $pdf_order['receiver_account_no'] = $basket_orders_to_mandrill_activation[$taxCount]['receiver_account_no'];
                        $pdf_order['waybill'] = $basket_orders_to_mandrill_activation[$taxCount]['waybill'];
                        $pdf_order['order_item'] = $basket_orders_to_mandrill_activation[$taxCount]['order_item'];
                        for ($order_item_count = 0; $order_item_count < sizeof($pdf_order['order_item']); $order_item_count++) {
                            if ($pdf_order['order_item'][$order_item_count]['parcel_desc'] == null || $pdf_order['order_item'][$order_item_count]['parcel_desc'] == '') {
                                $pdf_order['order_item'][$order_item_count]['parcel_desc'] = 'N/A';
                            }
                        }
                        $pdf_order['carrier_name'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_name'];
                        $pdf_order['carrier_service'] = $basket_orders_to_mandrill_activation[$taxCount]['carrier_service'];
                        $pdf_order['description'] = $basket_orders_to_mandrill_activation[$taxCount]['item_desc_1'];
                        $pdf_order['document_numbers'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service_order_ref'];

                        //changes in costing from margin group
                        $pdf_order['net_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['gross_selling_price'];
                        $pdf_order['discount_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['discount_cost'];
                        $pdf_order['net_selling_price'] = $basket_orders_to_mandrill_activation[$taxCount]['net_selling_price'];
                        $pdf_order['vat_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['vat_cost'];
                        $pdf_order['total_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['total_cost_plus_vat'];
                        $pdf_order['courier_fee_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['courier_fee_plus_markup_cost'];
                        $pdf_order['insurance_plus_markup_cost'] = $basket_orders_to_mandrill_activation[$taxCount]['insurance_plus_markup_cost'];
                        $pdf_order['discount_percentage'] = $discount_percentage;
                        $pdf_order['discount_description'] = $discount_description;

                        $pdf_order['net_cost'] = number_format((float) $pdf_order['net_cost'], 2, '.', '');
                        $pdf_order['vat_cost'] = number_format((float) $pdf_order['vat_cost'], 2, '.', '');
                        $pdf_order['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');
                        $pdf_order['courier_fee_plus_markup_cost'] = number_format((float) $pdf_order['courier_fee_plus_markup_cost'], 2, '.', '');
                        $pdf_order['insurance_plus_markup_cost'] = number_format((float) $pdf_order['insurance_plus_markup_cost'], 2, '.', '');

                        $pdf_payment['total_cost'] = number_format((float) $pdf_order['total_cost'], 2, '.', '');

                        $insurance = $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'];
                        if ($insurance === 'no items') {
                            $pdf_order['insurance'] = "(Insurance not included)";
                            $pdf_order['insurance_value'] = 0;
                        } else {
                            $pdf_order['insurance'] = "(incl. insurance for " . $basket_orders_to_mandrill_activation[$taxCount]['insurance_description'] . " valued at R" . $basket_orders_to_mandrill_activation[$taxCount]['insurance_value'] . ")";
                            $pdf_order['insurance_value'] =  $basket_orders_to_mandrill_activation[$taxCount]['insurance_value']  ;
                        }

                        $pdf_order['order_service_type'] = $basket_orders_to_mandrill_activation[$taxCount]['linked_service'];
                        if ($pdf_order['order_service_type'] == "RUSH") {
                            $return_message = 'Your Payment was successful. Please print your waybill which has been emailed to you.';
                        }

                        $grand_total = $basket_orders_to_mandrill_activation[$taxCount]['total_order_price'];

                        array_push($pdf_orders, $pdf_order);
                        array_push($pdf_payment_summary, $pdf_payment);
                    }

                    $new_invoice = new Invoice();
                    $new_invoice->id = 'Internal';
                    if ($account->user_type != 5) {
                        $new_invoice = Invoice::create(["order_group_ref" => $pdf_order_group_ref]);
                    }

                    $pdf_vouchers = array();
                    $total_voucher = 0;
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    for ($i = 0; $i < sizeof($vouchers); $i++) {
                        $voucher["discount_code"] = $vouchers[$i]["voucher_code"];
                        $voucher["discount_amount"] = $vouchers[$i]["amount"];
                        $total_voucher = $total_voucher + (float) $vouchers[$i]["amount"];
                        array_push($pdf_vouchers, $voucher);
                    }

                    $pdf_debts = array();
                    $total_amount_due = 0;

                    $debts = DB::table('debtors')
                                    ->select(DB::raw('*'))
                                    ->where('order_group_ref', '=', $order_group_ref)->get();
                    $debts = (array) (json_decode(json_encode($debts), true));

                    for ($i = 0; $i < sizeof($debts); $i++) {
                        $invoice = DB::table('invoice')
                                        ->select(DB::raw('*'))
                                        ->where('order_group_ref', '=', $order_group_ref)->get();
                        $invoice = (array) (json_decode(json_encode($invoice), true));
                        if ($debts[$i]["invoice"] == 0 || $debts[$i]["invoice"] == null) {
                            $debt['invoice'] = $invoice[0]['id'];
                        } else {
                            $debt['invoice'] = $debts[$i]["invoice"];
                        }
                        $debt["amount"] = $debts[$i]["amount"];
                        $debt["description"] = $debts[$i]["description"];
                        $total_amount_due = (float) $total_amount_due + (float) $debt["amount"];
                        array_push($pdf_debts, $debt);
                    }

                    $overall_cost = (float) $grand_total + (float) $total_amount_due;
                    $data = [
                        'logo' => 'imgs/rush-slider-logo2.jpg',
                        'pdf_order_created_at' => $pdf_order_created_at,
                        'pdf_user_type' => $account->user_type,
                        'pdf_new_invoice_number' => $new_invoice->id,
                        'pdf_account_surname' => $pdf_account_surname,
                        'pdf_account_name' => $pdf_account_name,
                        'pdf_account_company' => $pdf_account_company,
                        'pdf_account_physical_address' => $pdf_account_physical_address,
                        'pdf_account_province' => $pdf_account_province,
                        'pdf_account_company_landline' => $pdf_account_company_landline,
                        'pdf_account_mobile_number' => $pdf_account_mobile_number,
                        'pdf_account_company_vat' => $pdf_account_company_vat,
                        'pdf_orders' => $pdf_orders,
                        'pdf_vouchers' => $pdf_vouchers,
                        'pdf_grand_total' => $overall_cost,
                        'pdf_payment_summary' => $pdf_payment_summary,
                        'pdf_debts' => $pdf_debts,
                        'pdf_total_amount_due' => $total_amount_due,
                        'pdf_reinvoicing' => true
                    ];

                    $pdf = PDF::loadView('invoice_basket', $data);
                    return $pdf;
                } catch (Exception $e) {
                    Log::info($e);
                }

                return $this->respond([
                            'message' => 'Success.'
                ]);
            } else {
                Log::info("null");
                return null;
            }
        }
    }

    public function checkUnsuccessfulOrdersByDates() {
        $postData = Input::all();
        $start_date = $postData["start"];
        $end_date = $postData["end"];

        return $this->respond([
                    "message" => "Quering unsuccessful orders by start date=" . $start_date . ", end date=" . $end_date
        ]);
    }

    public function getUserTypeSum() {
//        $business = User::where('accounts.user_type', '=', 3)
//            ->join('accounts', 'accounts.user_id', '=', 'users.id')
//            ->leftjoin('account_service', 'accounts.id', '=', 'account_service.account_id')
//            ->where('accounts.active_ecommerce', '=', 0)
//            ->where('account_service.service_id', '=', '')
//            ->where('accounts.vodacom_user', '=', 0)
//            ->where('users.email', 'NOT LIKE', 'jiniguru')
//            ->count();

        $business =User::whereRaw('users.email NOT LIKE "%jini%"')
            ->whereRaw('accounts.vodacom_user = 0')
            ->whereRaw('accounts.ecommerce_token IS NULL')
            ->whereRaw('account_service.service_id IS NULL')
            ->leftjoin('accounts', 'users.id', '=', 'accounts.user_id')
            ->leftjoin('account_service', 'accounts.id', '=', 'account_service.account_id')
            ->count();

        $business_plus = Account::where('user_type', '=', 4)->count();

        $amrod_plus = AccountService::where('service_id', '=', 1)->count();

        $togsa = User::whereRaw('account_service.service_id = 2')
            ->whereRaw('users.email NOT LIKE "%jini%"')
            ->join('accounts', 'users.id', '=', 'accounts.user_id')
            ->join('account_service', 'accounts.id', '=', 'account_service.account_id')
            ->count();

        $wechat = Wechat::all()->count();
        $vodacom = User::where('accounts.vodacom_user', '=', 1)
            ->join('accounts', 'users.id', '=', 'accounts.user_id')
            ->whereRaw('users.email NOT LIKE "%jini%"')
            ->count();


        $amrod = User::whereRaw('users.email NOT LIKE "%jini%"')
            ->whereRaw('account_service.service_id = 1')
            ->join('accounts', 'users.id', '=', 'accounts.user_id')
            ->join('account_service', 'accounts.id', '=', 'account_service.account_id')
            ->count();

        $ecommerce = Account::where('active_ecommerce', '=', 1)->count();


        $users = array('business' => $business, 'business_plus' => $business_plus, 'amrod' => $amrod, 'togsa' => $togsa,'ecommerce' => $ecommerce, 'vodacom' => $vodacom);

        return $users;
    }

        public function getuserSuspendedSum() {
        $suspended = Throttle::where('suspended', '=', 1)->count();
        $not_activated = User::where('activated', '=', 0)->count();
        $activated = User::where('activated', '=', 1)->count();


        $users1 = array('suspended' => $suspended, 'not_activated' => $not_activated, 'activated' => $activated);

        return $users1;
    }

    public function allocateVoucher() {

        $postData = Input::all();
        $account_id = $postData['account_id'];
        $discount_amount = $postData['discount_amount'];
        $discount_expires = $postData['discount_expires'];
        $service_type = isset($postData['service_type']) ? $postData['service_type'] : "ALL";

        $account = Account::find($account_id);
        if (!$account) {
            return $this->respondInternalError([
                        'message' => "Could not find account with Id=" . $account_id]);
        } else if ($account->eligible_voucher = 0) {
            return $this->respondInternalError([
                        'message' => "Account not eligible to have voucher(s)."]);
        }

        $date = date("Y-m-d 23:59:59", strtotime($discount_expires));
//$new_date_format = date("d M Y", strtotime($discount_expires));
        $new_date_format = date('d M Y', strtotime($date . ' + 1 day'));

        $new_voucher = Vouchers::create(
                        [
                            "voucher_code" => "RUSH" . $discount_amount,
                            "voucher_name" => "RUSH" . $discount_amount,
                            "amount" => $discount_amount,
                            "expiry_date" => $date,
                            "available" => 1,
                            "account_id" => $account_id,
                            "service_type" => $service_type
        ]);

        $mandrill = new MandrillService();

        $service_type_email = $service_type;
        if ($service_type == "ALL") {
            $service_type_email = "all";
        } else if ($service_type == "AMROD") {
            $service_type_email = "all Amrod";
        } else if ($service_type == "TOGSA") {
            $service_type_email = "all Trade Only Gifts";
        }

        $sendVoucherEmail = $mandrill->sendVouchersEmailNotification($account, $new_voucher->amount, $new_date_format, $service_type_email);

        return $this->respond([
                    'message' => 'Success.'
        ]);
    }

    public function allocateBulkVouchers() {

        $postData = Input::all();
        $discount_amount = $postData['discount_amount'];
        $discount_expires = $postData['discount_expires'];
        $service_type = $postData['service_type'];

        $service = Service::getServiceByReference($service_type)->get();
        if ($service->isEmpty()) {
            return $this->respondInternalError([
                        'message' => "Could not find service with reference=" . $service_type]);
        }

        Log::info($service);

        $accountService = AccountService::serviceId($service->first()->id)->get()->toArray();

        $newVouchers = array();
        $accountIds = array();
        $date = date("Y-m-d 23:59:59", strtotime($discount_expires));

        for ($i = 0; $i < sizeof($accountService); $i++) {
            $voucher = [
                "voucher_code" => $service_type . $discount_amount,
                "voucher_name" => $service_type . $discount_amount,
                "created_at" => Carbon::now()->toDateTimeString(),
                "updated_at" => Carbon::now()->toDateTimeString(),
                "expiry_date" => $date,
                "amount" => $discount_amount,
                "account_id" => $accountService[$i]['account_id'],
                "order_group_ref" => "",
                "available" => 1,
                "service_type" => $service_type
            ];
            array_push($newVouchers, $voucher);
            array_push($accountIds, $accountService[$i]['account_id']);
        }

        $accounts = Account::whereIn('id', $accountIds)->where('eligible_voucher', '=', '0');
        if (!$accounts->get()->isEmpty()) {
            $accounts->update(['eligible_voucher' => 1]);
        }

        Log::info($newVouchers);
        $success = Vouchers::insert($newVouchers);

        if (!$success) {
            Log::info("You have failed this DB");
            return $this->respondWithError('Error.');
        }

//        $mandrill = new MandrillService();
//
//        $service_type_email = $service_type;
//        if ($service_type == "ALL") {
//            $service_type_email = "all";
//        } else if ($service_type == "AMROD") {
//            $service_type_email = "all Amrod";
//        } else if ($service_type == "TOGSA") {
//            $service_type_email = "all Trade Only Gifts";
//        }
//
//        $sendVoucherEmail = $mandrill->sendVouchersEmailNotification($account, $new_voucher->amount, $new_date_format, $service_type_email);

        return $this->respond([
                    'message' => 'Success.'
        ]);
    }

    public function getVouchersByAccountId() {

        $postData = Input::all();

        if (!isset($postData['accountId'])) {
            return $this->respondInternalError([
                        'data' => 'Internal Error: Missing accountId.'
            ]);
        }

        $account_id = $postData['accountId'];
        $voucher = Vouchers::getVouchers($account_id)->get()->toArray();
        return $this->respond([
                    'data' => $voucher
        ]);
    }

    public function changeVoucherStatus() {
        $postData = Input::all();
        $account = Account::find($postData['account_id']);
        $account->eligible_voucher = $postData['eligible_voucher'];
        $account->save();
        return $this->respond([
                    'data' => 'Success.'
        ]);
    }

    public function getDebtors() {
        $debtors = Debtors::with('account')->get();
        $debtorAccounts = array();
        foreach ($debtors as $debtor) {
            if ($debtor->status === "PENDING") {
                $account = Account::with('user')->find($debtor->account_id);
                $debtorAccount['debt_id'] = $debtor->id;
                $debtorAccount['account_id'] = $account->id;
                $debtorAccount['email'] = $account->user->email;
                $debtorAccount['phone'] = $account->mobile_number;
                $debtorAccount['description'] = $debtor->description;
                $debtorAccount['order_group_ref'] = $debtor->order_group_ref;
                $debtorAccount['payu_reference'] = $debtor->payu_reference;
                $debtorAccount['amount'] = $debtor->amount;
                $debtorAccount['status'] = $debtor->status;
                $debtorAccount['store_payment'] = $account->store_payment;

                array_push($debtorAccounts, $debtorAccount);
            }
        }
        return $this->respond([
                    'data' => $debtorAccounts
        ]);
    }

    public function getDebtorsByAccountId() {
        $postData = Input::all();
        $debtors = Debtors::AccountId($postData['account_id'])->where('status', '=', 'PENDING')->get();
        return $this->respond([
                    'data' => $debtors
        ]);
    }

    public function addDiscripancy() {
        $postData = Input::all();
        $account_id = $postData['account_id'];
        $description = $postData['description'];
        $amount = $postData['amount'];
        $invoicenum = $postData['invoice'];

        $invoice = Invoice::InvoiceById($invoicenum)->get();
        $ordergroupref = $invoice[0]['order_group_ref'];

        $debtor = Debtors::create(
                        [
                            'account_id' => $account_id,
                            'amount' => $amount,
                            'invoice' => $invoicenum,
                            'description' => $description,
                            'order_group_ref' => $ordergroupref,
                            'status' => 'PENDING'
                        ]
        );
        return $this->respond([
                    'data' => 'success.'
        ]);
    }

    public function payDiscripancyWithWallet() {
        $postData = Input::all();
        $account_id = $postData['account_id'];
        $description = $postData['description'];
        $amount = $postData['amount'];
        $invoice_number = $postData['invoice'];

        $invoice = Invoice::find($invoice_number);
        if (!$invoice && sizeof($invoice) <= 0) {
            return $this->respondInternalError([
                        'data' => 'Invoice number does not exist.'
            ]);
        }
        $order_group_ref = $invoice['order_group_ref'];

        $debtor = Debtors::create(
                        [
                            'account_id' => $account_id,
                            'amount' => $amount,
                            'invoice' => $invoice_number,
                            'description' => $description,
                            'status' => 'CLEARED',
                            'order_group_ref' => $order_group_ref
                        ]
        );

        $orders = Order::OrderGroupRef($order_group_ref)->get();
        for ($i = 0; $i < sizeof($orders); $i++) {
            $update_order = $orders[$i];
            $total_order_price = $update_order['total_order_price'];
            $update_order->total_order_price = $total_order_price + ($amount * 1.14);
            $update_order->save();
        }


        $account = Account::find($account_id);
        $pdf = $this->generateReInvoicingTaxInvoicePDF($order_group_ref);
        try {
            $mandrill = new MandrillService();
            $mandrill->sendDebtorEmailNotification($account, $invoice->id, $pdf);
        } catch (Exception $e) {
            Log::info("Failed to send reminder email. Error message: " . $e->getMessage());
        }

        return $this->respond([
                    'data' => 'success.'
        ]);
    }

    public function suspendedusers() {
        $suspended = DB::table('throttle')
                        ->join('users', 'throttle.user_id', '=', 'users.id')
                        ->join('accounts', 'users.id', '=', 'accounts.user_id')
                        ->select('throttle.suspended', 'users.email', 'accounts.id', 'accounts.user_id', 'accounts.name', 'accounts.surname', 'throttle.suspended_at')
                        ->where('throttle.suspended', '=', 1)
                        ->orWhere('throttle.banned', '=', 1)
                        ->distinct()
                        ->get();
        return $suspended;
    }

//    public function unsuspendUser($id) {
//
//        $throttle = DB::table('throttle')->select('throttle.*')
//                ->where('throttle.user_id', '=', $id)
//                ->where('throttle.suspended', '=', 1)
//                ->get();
//        $throttle = (array) (json_decode(json_encode($throttle), true));
//        $throttle = $throttle[0];
//        DB::table('throttle')
//                ->where('throttle.id', $throttle['id'])
//                ->update(['suspended' => 0]);
//    }

    public function unsuspendAUser($id) {

        $throttle = DB::table('throttle')->select('throttle.*')
                ->where('throttle.user_id', '=', $id)
                ->get();
        $throttle = (array) (json_decode(json_encode($throttle), true));

         foreach ($throttle as $k => $v) {
            if ($v['suspended'] == 1) {

                DB::table('throttle')
                        ->where('throttle.id', $v['id'])
                        ->update(['suspended' => 0]);
            }
            if ($v['banned'] == 1) {

                DB::table('throttle')
                        ->where('throttle.id', $v['id'])
                        ->update(['banned' => 0]);
            }
        }
    }

        public function suspendAUser($id) {

        $throttle = DB::table('throttle')->select('throttle.*')
                ->where('throttle.user_id', '=', $id)
                ->get();
        $throttle = (array) (json_decode(json_encode($throttle), true));

         foreach ($throttle as $k => $v) {
            if ($v['banned'] == 0) {

                DB::table('throttle')
                        ->where('throttle.id', $v['id'])
                        ->update(['banned' => 1]);
            }
        }
    }

    public function setDebtorPayU() {
        $postData = Input::all();

        $account_id = $postData['account_id'];
        $debt_id = $postData['debt_id'];
        $orderGroupRef = $postData['order_group_ref'];


        $account = Account::find($account_id); //accountId same for all orders.
        return $this->setDebtorRTRRPPPayU($debt_id, $orderGroupRef, $account);
    }

    private function setDebtorRTRRPPPayU($debt_id, $orderGroupRef, $account) {
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        ob_start();


//        $postData = Input::all();
//        $orderGroupRef = $postData['orderGroupRef'];

        /** Start Configuration */
        $baseUrl = Config::get('payuConfig.debtor_payu_rtr_rpp.baseUrl'); //environment URL
        $soapWdslUrl = Config::get('payuConfig.debtor_payu_rtr_rpp.wsdlUrl');
        $payuRppUrl = Config::get('payuConfig.debtor_payu_rtr_rpp.redirectUrl');
        $apiVersion = Config::get('payuConfig.debtor_payu_rtr_rpp.apiVersion');
        $doAutoRedirectToPaymentPage = Config::get('payuConfig.debtor_payu_rtr_rpp.redirect'); //set value != 1 if you dont want to auto redirect topayment page

        /** Store config details */
        $safeKey = Config::get('payuConfig.debtor_payu_rtr_rpp.safeKey');
        $soapUsername = Config::get('payuConfig.debtor_payu_rtr_rpp.username');
        $soapPassword = Config::get('payuConfig.debtor_payu_rtr_rpp.password');
        /** End Store config details */
        $cancelUrl = Config::get('payuConfig.debtor_payu_rtr_rpp.cancelUrl');
        $returnUrl = Config::get('payuConfig.debtor_payu_rtr_rpp.returnUrl') . $orderGroupRef;
        $transaction_type = Config::get('payuConfig.debtor_payu_rtr_rpp.transactionType');
        $supported_payment_methods = Config::get('payuConfig.debtor_payu_rtr_rpp.supportedPaymentMethods');

        $merchant_reference = $orderGroupRef;
        $managedBy = Config::get('payuConfig.debtor_payu_rtr_rpp.managedBy');
        $redirectUrl = Config::get('payuConfig.debtor_payu_rtr_rpp.redirectUrl');
        /**  End Configuration  */
//        $basket_orders = Order::ordergrouprefnotpaid($orderGroupRef)->get()->toArray();
//        $account = Account::with('user')->find($basket_orders[0]['account_id']); //accountId same for all orders.
        //
        //
//Unique identifier on the merchant system to identify the customer. This ID must be sent into PayU to identify that the card was tokenised.
        $merchant_customer_user_id = Config::get('payuConfig.debtor_payu_rtr_rpp.platform') . $account['user_id'] . "_" . $account['id'];

        /** Start Customer & Basket */
        $current_user_id = $account['user_id'];
        $strEmail = $account['user']['email'];
        $strFirstname = $account['name'];
        $strLastname = $account['surname'];
        $strMobile = $account['mobile_number'];

        $debt_description = "Rush RTR Store";


//        $debt = DB::table('debtors')->where('id', '=', $debt_id)->get();
        $debt = Debtors::find($debt_id);


        if (!$debt || empty($debt)) {
            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addError("[BusinessController:setRPPPayU] Error: Payment could not proceed for OrderGroupRef=" . $orderGroupRef . ". Debt details are missing.");
            return $this->respondInternalError([
                        'message' => "Your payment could not proceed. Please try again.",
                        'order_group_ref' => $orderGroupRef,
                        'response_error' => 'Error: PayU failure!'
            ]);
        }

        $debt_total_amountInCents = $debt['amount'] * 100;
        $debt_currencyCode = 'ZAR';
        /** End Customer & Basket */
        try {
// 1. Building the Soap array  of data to send
            $setTransactionArray = array();
            $setTransactionArray['Api'] = $apiVersion;
            $setTransactionArray['Safekey'] = $safeKey;
            $setTransactionArray['TransactionType'] = $transaction_type;

            $setTransactionArray['AdditionalInformation']['merchantReference'] = $merchant_reference;
            $setTransactionArray['AdditionalInformation']['secure3d'] = 'False';
            $setTransactionArray['AdditionalInformation']['cancelUrl'] = $cancelUrl;
            $setTransactionArray['AdditionalInformation']['returnUrl'] = $returnUrl;
            $setTransactionArray['AdditionalInformation']['supportedPaymentMethods'] = $supported_payment_methods;
            $setTransactionArray['AdditionalInformation']['RedirectChannel'] = Config::get('payuConfig.debtor_payu_rtr_rpp.redirectChannel');

            $setTransactionArray ['Basket'] ['description'] = $debt_description;
            $setTransactionArray ['Basket'] ['amountInCents'] = $debt_total_amountInCents * 1.14;
            $setTransactionArray ['Basket'] ['currencyCode'] = $debt_currencyCode;

            $setTransactionArray['TransactionRecord']['managedBy'] = $managedBy;

            $setTransactionArray ['Customer'] ['merchantUserId'] = $merchant_customer_user_id;
            $setTransactionArray ['Customer'] ['email'] = $strEmail;
            $setTransactionArray ['Customer'] ['firstName'] = $strFirstname;
            $setTransactionArray ['Customer'] ['lastName'] = $strLastname;
            $setTransactionArray ['Customer'] ['mobile'] = $strMobile;

            $setTransactionArray['Customfield']['key'] = 'processingType';
            $setTransactionArray['Customfield']['value'] = 'REAL_TIME_RECURRING';

// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
            $headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
            $headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
            $headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
            $headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
            $headerXml .= '</wsse:UsernameToken>';
            $headerXml .= '</wsse:Security>';
            $headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

// 3. Create Soap Header.
            $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
            $header = new SOAPHeader($ns, 'Security', $headerbody, true);

// 4. Make new instance of the PHP Soap client
            $soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

// 5. Set the Headers of soap client.
            $soap_client->__setSoapHeaders($header);

// 6. Do the setTransaction soap call to PayU
            $soapCallResult = $soap_client->setTransaction($setTransactionArray);

// 7. Decode the Soap Call Result
            $returnData = json_decode(json_encode($soapCallResult), true);

            $request = $soap_client->__getLastRequest();
            $response = $soap_client->__getLastResponse();

            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
            $payu_setTransaction_log->addInfo("[BusinessController:setRTRRPPPayU] Info: PayU SetTransaction for OrderGroupRef=" . $orderGroupRef . ", Request: " . $request);
            $payu_setTransaction_log->addInfo("[BusinessController:setRTRRPPPayU] Info: PayU SetTransaction for OrderGroupRef=" . $orderGroupRef . ", Response: " . $response);

            if (isset($doAutoRedirectToPaymentPage) && ($doAutoRedirectToPaymentPage == 1)) {
                if (
                        (isset($returnData['return']['successful']) &&
                        ($returnData['return']['successful'] === true) &&
                        isset($returnData['return']['payUReference']))
                ) {
                    $order = Order::orderGroupRef($debt['order_group_ref'])->get();

                    $log = PayULog::create([
                                "order_id" => $order[0]['id'],
                                "user_id" => $current_user_id,
                                "payu_reference" => $returnData['return']['payUReference'],
                                "api_method" => "set transaction",
                                "input_from_user" => json_encode($order),
                                "api_post" => $request,
                                "api_response" => $response,
                    ]);
                    return $this->respond(['redirectUrl' => $redirectUrl . $returnData['return']['payUReference']]);
                }
                return $this->respondInternalError([
                            'message' => "Couldn't get a success response from PayU. Please try again later.",
                            'order_group_ref' => $orderGroupRef,
                            'response_error' => 'PayU failure!'
                ]);
            }
        } catch (Exception $ex) {
            $payu_setTransaction_log = new Logger('SetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addWarning("[BusinessController:setRPPPayU] Error: Internal PayU Gateway Error: " . $ex->getMessage());
            return $this->respondInternalError([
                        'message' => "Your payment could not proceed. Please try again.",
                        'order_group_ref' => $orderGroupRef,
                        'response_error' => '[BusinessController:setRTRRPPPayU] Error: Payu Failure. ' . $ex->getMessage()
            ]);
        }

        $payu_setTransaction_log = new Logger('SetTransaction');
        $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::ERROR));
        $payu_setTransaction_log->addError("[BusinessController:setRTRRPPPayU] Error: Payment could not proceed for OrderGroupRef=" . $orderGroupRef);
        return $this->respondInternalError([
                    'message' => "Your payment could not proceed. Please try again.",
                    'order_group_ref' => $orderGroupRef,
                    'response_error' => 'Error: PayU failure!'
        ]);
    }

    public function getDebtorPayUPaymentStatus() {
        $postData = Input::all();
        $order_group_ref = $postData['OrderGroupRef'];
        $basket_order_ids = $postData['BasketOrderIds'];
        $payu_reference = $postData['PayUReference'];

        $order = Order::ordergroupref($order_group_ref)->get()->toArray();
        $account_id = $order[0]['account_id'];

        $account = Account::find($account_id);

        $payu_setTransaction_log = new Logger('GetTransaction');
        $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
        $payu_setTransaction_log->addInfo("[BusinessController:getPayUPaymentStatus] Process: getPayU Payment Status for payURef=" . $payu_reference . " and OrderGroupRef=" . $order_group_ref);

        /** Start Configuration  */
        $environment = null;
        $baseUrl = null;
        $soapWdslUrl = null;
        $payuRppUrl = null;
        $apiVersion = null;
        $safeKey = null;
        $soapUsername = null;
        $soapPassword = null;
        if (!($account->store_payment) || $account->store_payment == 0 || $account->store_payment === 'undefined' || $account->store_payment == null || $account->store_payment === '') {

            $environment = Config::get('payuConfig.payu_rpp.environment');
            $baseUrl = Config::get('payuConfig.payu_rpp.baseUrl');
            $soapWdslUrl = Config::get('payuConfig.payu_rpp.wsdlUrl');
            $payuRppUrl = Config::get('payuConfig.payu_rpp.redirectUrl');
            $apiVersion = Config::get('payuConfig.payu_rpp.apiVersion');
            $safeKey = Config::get('payuConfig.payu_rpp.safeKey');
            $soapUsername = Config::get('payuConfig.payu_rpp.username');
            $soapPassword = Config::get('payuConfig.payu_rpp.password');
        } else if ($account->store_payment == 1) {
            $environment = Config::get('payuConfig.payu_rtr_rpp.environment');
            $baseUrl = Config::get('payuConfig.payu_rtr_rpp.baseUrl');
            $soapWdslUrl = Config::get('payuConfig.payu_rtr_rpp.wsdlUrl');
            $payuRppUrl = Config::get('payuConfig.payu_rtr_rpp.redirectUrl');
            $apiVersion = Config::get('payuConfig.payu_rtr_rpp.apiVersion');
            $safeKey = Config::get('payuConfig.payu_rtr_rpp.safeKey');
            $soapUsername = Config::get('payuConfig.payu_rtr_rpp.username');
            $soapPassword = Config::get('payuConfig.payu_rtr_rpp.password');
        }

        $merchant_reference = $order_group_ref;

        /** End Configuration  */
        try {

// 1. Building the Soap array  of data to send
            $soapDataArray = array();
            $soapDataArray['Api'] = $apiVersion;
            $soapDataArray['Safekey'] = $safeKey;
            $soapDataArray['AdditionalInformation']['payUReference'] = $payu_reference;

// 2. Creating a XML header for sending in the soap heaeder (creating it raw a.k.a xml mode)
            $headerXml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">';
            $headerXml .= '<wsse:UsernameToken wsu:Id="UsernameToken-9" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">';
            $headerXml .= '<wsse:Username>' . $soapUsername . '</wsse:Username>';
            $headerXml .= '<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $soapPassword . '</wsse:Password>';
            $headerXml .= '</wsse:UsernameToken>';
            $headerXml .= '</wsse:Security>';
            $headerbody = new SoapVar($headerXml, XSD_ANYXML, null, null, null);

// 3. Create Soap Header.
            $ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'; //Namespace of the WS.
            $header = new SOAPHeader($ns, 'Security', $headerbody, true);

// 4. Make new instance of the PHP Soap client
            $soap_client = new SoapClient($soapWdslUrl, array("trace" => 1, "exception" => 0));

// 5. Set the Headers of soap client.
            $soap_client->__setSoapHeaders($header);

// 6. Do the setTransaction soap call to PayU
            $soapCallResult = $soap_client->getTransaction($soapDataArray);

// 7. Decode the Soap Call Result
            $returnData = json_decode(json_encode($soapCallResult), true);

            if (is_object($soap_client)) {
                $request = $soap_client->__getLastRequest();
                $response = $soap_client->__getLastResponse();

                $payu_setTransaction_log = new Logger('GetTransaction');
                $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::INFO));
                $payu_setTransaction_log->addInfo("[BusinessController:getPayUPaymentStatus] Info: PayU GetTransaction for OrderGroupRef=" . $order_group_ref . ", Request: " . $request);
                $payu_setTransaction_log->addInfo("[BusinessController:getPayUPaymentStatus] Info: PayU GetTransaction for OrderGroupRef=" . $order_group_ref . ", Response: " . $response);

                $methodType = "";
                if ($returnData['return']['resultCode'] === '00' && $returnData['return']['transactionState'] === 'SUCCESSFUL') {
                    $methodType = "Payment Successful";

                    $payu_payment_passed_log = new Logger('PayU Payment Passed');
                    $payu_payment_passed_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_payments_passed.log', Logger::INFO));
                    $payu_payment_passed_log->addInfo("[BusinessController:getPayUPaymentStatus] Info: PayU Payment Status for OrderGroupRef=" . $order_group_ref . " is: " . $methodType);

                    for ($countp = 0; $countp < sizeof($basket_order_ids); $countp++) {
                        $PayUPassedLog = PaymentLog::create([
                                    "order_id" => $basket_order_ids[$countp],
                                    "method_type" => $methodType,
                                    "config_data" => "",
                                    "post_data" => $request,
                                    "result_data" => $response,
                        ]);
                    }

                    /**
                     * Update debts if any to CLEARED.
                     */
                    $debtors = Debtors::OrderGroupRef($order_group_ref)->get()->toArray();
                    if ($debtors && sizeof($debtors) > 0) {

                        $debt_amount = 0;

                        for ($i = 0; $i < sizeof($debtors); $i++) {
                            $debt = Debtors::find($debtors[$i]['id']);
                            $debt_amount = $debt_amount + $debt['amount'];
//                            Log::info($debt_amount);
                            $debt->status = "CLEARED";
                            $debt->payu_reference = $payu_reference;
                            $debt->save();
                        }

                        $orders = Order::OrderGroupRef($order_group_ref)->get();
                        for ($i = 0; $i < sizeof($orders); $i++) {
                            $update_order = $orders[$i];
                            $total_order_price = $update_order['total_order_price'];
                            $update_order->total_order_price = $total_order_price + ($debt_amount * 1.14);
                            $update_order->save();
                        }
                    }

                    $basketDel = Basket::with('basketItem')->accountbyid($account_id)->get();
                    foreach ($basketDel as $basketD) {
                        $basketD->delete();
                    }

                    return $this->respond([
                                'returnData' => $returnData,
                                'environment' => $environment,
                                'orderGroupRef' => $order_group_ref
                    ]);
                } else {
                    $methodType = $returnData['return']['resultMessage'];

                    $payu_payment_failed_log = new Logger('PayU Payment Failed');
                    $payu_payment_failed_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_payments_failed.log', Logger::INFO));
                    $payu_payment_failed_log->addInfo("[BusinessController:getPayUPaymentStatus] Info: PayU Payment Status for OrderGroupRef=" . $order_group_ref . " is: " . $methodType);

                    for ($countp = 0; $countp < sizeof($basket_order_ids); $countp++) {
                        $PayUPassedLog = PaymentLog::create([
                                    "order_id" => $basket_order_ids[$countp],
                                    "method_type" => $methodType,
                                    "config_data" => "",
                                    "post_data" => $request,
                                    "result_data" => $response,
                        ]);
                    }

                    /**
                     * Revert Vouchers.
                     */
                    $vouchers = Vouchers::GetVouchersByOrderGroupRef($order_group_ref)->get()->toArray();
                    if ($vouchers && sizeof($vouchers) > 0) {
                        for ($i = 0; $i < sizeof($vouchers); $i++) {

                            $voucher = Vouchers::find($vouchers[$i]["id"]);
                            $voucher->available = 1;
                            $voucher->save();
                        }
                    }

                    return $this->respondInternalError([
                                'message' => "PayU Payment Failed.",
                                'response_error' => "[BusinessController:getPayUPaymentStatus] PayU Payment Failed.",
                                'returnData' => $returnData,
                                'order_group_ref' => $order_group_ref
                    ]);
                }
            }

            return $this->respondInternalError([
                        'message' => "Internal Error: Could not check payment status for OrderGroupRef=" . $order_group_ref,
                        'response_error' => "[BusinessController:getPayUPaymentStatus] Internal Error: Could not check payment status for OrderGroupRef=" . $order_group_ref,
                        'order_group_ref' => $order_group_ref]);
        } catch (Exception $e) {
            $payu_setTransaction_log = new Logger('GetTransaction');
            $payu_setTransaction_log->pushHandler(new StreamHandler(storage_path() . '/logs/payu_services.log', Logger::WARNING));
            $payu_setTransaction_log->addWarning("[BusinessController:getPayUPaymentStatus] Internal Error: " . $e->getMessage());
            return $this->respondInternalError([
                        'message' => "Internal Error: Your confirmation order could not proceed.",
                        'response_error' => "[BusinessController:getPayUPaymentStatus] Internal Error: " . $e->getMessage(),
                        'order_group_ref' => $order_group_ref]);
        }
    }

    public function checkDebtForInvoice($id) {
        $invoice = Invoice::whereId($id)->get();
        if (sizeof($invoice) < 1) {
            return $this->respondInternalError([
                        'message' => "Invoice not found"
            ]);
        }
        Log::info($invoice);
        $debt = DB::table('debtors')
                        ->select(DB::raw('*'))
                        ->where('order_group_ref', '=', $invoice[0]['order_group_ref'])->get();

        return $this->respond([
                    'message' => "noDebt"
        ]);
    }

    public function importVoucher() {
        $postData = Input::all();
        $emails = array();
        $rows = Excel::selectSheetsByIndex(0)->load($postData['file'], function($reader) {
                    //$reader->noHeading();
                    $results = $reader->get();
                    // print_r($results);


                    $reader->each(function($results) {

                        // Loop through all rows
                        $results->each(function($row) {
                            $emails = $row;
                        });
                    });
                })->get();
        $results = array();
        //return $rows;
        foreach ($rows as $row) {
            if (isset($row->email) && ($row->email <> "")) {
                $result[] = array(
                    "success" => true,
                    "email" => $row->email
                );
                //echo $row->email;
                $accountIds = DB::table('accounts')
                        ->select('accounts.id', 'accounts.name', 'users.email')
                        ->join('users', 'users.id', '=', 'accounts.user_id')
                        ->where('email', '=', $row->email)
                        ->get();


                if ($accountIds) {

                    $account_id = $accountIds;
                    $discount_amount = $postData['amount'];
                    $discount_code = $postData['code'];
                    $discount_expires = $postData['expiry'];
                    $service_type = isset($postData['type']) ? $postData['type'] : "ALL";
                    $date = date("Y-m-d 23:59:59", strtotime($discount_expires));
                    //$new_date_format = date("d M Y", strtotime($discount_expires));
                    $new_date_format = date('d M Y', strtotime($date . ' + 1 day'));

                    $new_voucher = Vouchers::create(
                                    [
                                        "voucher_code" => $discount_code,
                                        "voucher_name" => $discount_code,
                                        "amount" => $discount_amount,
                                        "expiry_date" => $date,
                                        "available" => 1,
                                        "account_id" => $accountIds[0]->id,
                                        "service_type" => $service_type
                    ]);

                    $mandrill = new MandrillService();

                    $service_type_email = $service_type;
                    if ($service_type == "ALL") {
                        $service_type_email = "all";
                    } else if ($service_type == "AMROD") {
                        $service_type_email = "all Amrod";
                    } else if ($service_type == "TOGSA") {
                        $service_type_email = "all Trade Only Gifts";
                    }

                    $account = array(
                        "id" => $accountIds[0]->id,
                        "name" => $accountIds[0]->name,
                        "email" => $accountIds[0]->email
                    );

                    $accounts = (object) $account;


                    $sendVoucherEmail = $mandrill->sendVouchersEmailNotification($accounts, $new_voucher->amount, $new_date_format, $service_type_email);
                }
            } else {
                $result[] = array(
                    "success" => false,
                    "email" => $row->email
                );
            }
        }

        $tst = new Excel();
        $tst::create('Import_voucher_results', function($excel) use($result) {
            $excel->sheet('Amrod_orders', function($sheet) use($result) {
                // $lastRownum = count($items) + 1;
                //$totalWalletAmountCell = $lastRownum + 1;
                // $sheet->freezeFirstRow();
                $sheet->fromArray($result);
                //$sheet->setCellValue('K' . $totalWalletAmountCell, '=SUM(K2:K' . $lastRownum . ')');
                //$sheet->setCellValue('L' . $totalWalletAmountCell, '=SUM(L2:L' . $lastRownum . ')');
                //$sheet->setCellValue('M' . $totalWalletAmountCell, '=SUM(M2:M' . $lastRownum . ')');
            });
        })->store('xls');
        return "Import_voucher_results";
        //return $result;
    }

}
