<?php

class PagesController extends BaseController {

    protected static $rules = [
        'email' => 'required|email',
        'password' => 'required'

    ];

    protected static $rules2 = [
        'query' => 'required'

    ];

    protected static $rules3 = [
        'query' => 'required'

    ];

    public function home()
    {
        $image = DB::table('banner')
            ->where('id','=',1)
            ->first();
        $image = $image->image;

        $email = Auth::user()->email;

        $user = DB::table('users')
            ->where('email','=',$email)
            ->first();

        return View::make('pages.home')
            ->with('user',$user)
            ->with('image',$image);
    }

    public function serverLogin()
    {
        return View::make('users.login');
    }

    public function serverSupport()
    {
        return View::make('pages.support');
    }

    public function serverTermsConditions()
    {
        return View::make('pages.terms-and-conditions');
    }


    public function handleSupport()
    {
        $validator = Validator::make(Input::all(), static::$rules2);

        if($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', '
        Oops! There was a problem with your entry, please try again.');
        }

        $query = new Query;
        $query->name = Input::get('name');
        $query->email = Input::get('email');
        $query->query = Input::get('query');
        $query->save();

        $data = ['query' => $query];

        Mail::send('emails.query', $data, function($message)
        {
            $message->to('Admin2@prestigeAdvantage.co.za', 'Admin2')->bcc('rachael@statusdata.co.za','Rachael')->cc('Admin1@prestigeAdvantage.co.za','Admin1')->subject('Prestige Enquiry');
            $message->from('Admin2@prestigeAdvantage.co.za');
        });

        return Redirect::to('/home')->with('view-success',' Thank you! Our support team will get back to you as soon as possible.');

    }

    public function handleLogin()
    {
        $validator = Validator::make(Input::all(), static::$rules);

        if (Auth::attempt(['email' => Input::get('email'), 'password' => Input::get('password')]))
        {
            $role = Auth::user()->role;

            return Redirect::to('/disclaimer');

            /*
            if(Input::get('email')=='Admin1@prestigeAdvantage.co.za')
            {
                return Redirect::to('management-dashboard');
            }
            elseif(Input::get('email')=='Admin2@prestigeAdvantage.co.za')
            {
                return Redirect::to('management-dashboard');
            }
            elseif(Input::get('email')=='admin@statusdata.co.za')
            {
                return Redirect::to('management-dashboard');
            }
            else
            {
                //return Redirect::intended('/home');
                return Redirect::intended('/disclaimer');
            }*/
        }

        elseif((Input::get('password'))==NULL and Input::get('email'))
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', ' A password is required to login.');
        }

        elseif((Input::get('email'))==NULL and Input::get('password'))
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', 'An email is required to login.');
        }

        elseif($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', '<strong>Oops!</strong> No credentials entered.');
        }

        else
        {
            return Redirect::back()->withInput()->with('view-error', 'The email and password you entered do not correspond, please try again.');
        }

    }

    public function handleLogout()
    {
        Auth::logout();
        Session::flush();
        return Redirect::to('home');
    }

    public function serverRegister()
    {
        return View::make('users.register');
    }

    public function handleRegister()
    {
        $validator = Validator::make(Input::all(),
            [
                'name' => 'required',
                'email' => 'required',
                'password' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', '<i class="white fa fa-exclamation-triangle"></i> There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        if((Input::get('password'))!=(Input::get('password1')))
        {
            return Redirect::back()->with('view-error', '<i class="fa fa-exclamation-triangle"></i> Passwords do not match')->withInput()->withErrors($validator);
        }

        $user = new User;
        $user->password = Hash::make(Input::get('password'));
        $user->email = Input::get('email');
        $user->name = Input::get('name');

        if (Input::hasFile('profile_pic'))
        {
            $file = Input::file('profile_pic');
            $file->move('img/admin/', $file->getClientOriginalName());
            $user->profile_pic = 'img/admin/'.$file->getClientOriginalName();
        }

        $user->save();

        return Redirect::to('userDashboard')->with('view-success', '<i class="green circleBg fa fa-check"></i> SUCCESS: New User Added');

    }

    public function serverDashboard()
    {
        return View::make('pages.dashboard');
    }

    public function serverBCS()
    {
        return View::make('bank-codes.BCS-request');
    }

    public function handleBCS()
    {

        $validator = Validator::make(Input::all(),
            [
                'name' => 'required',
                'bank' => 'required',
                'branchCode' => 'required',
                'branchName' => 'required',
                'terms' => 'required',
                'country' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }


        $request = new BCS;
        $request->name = Input::get('name');
        $request->email = Input::get('email');
        $request->idNumber = Input::get('idNumber');
        $request->bank = Input::get('bank');
        $request->amount = Input::get('amount');
        $request->branchCode = Input::get('branchCode');
        $request->accountNumber = Input::get('accountNumber');
        $request->branchCode = Input::get('branchCode');
        $request->branchName = Input::get('branchName');
        $request->terms = Input::get('terms');
        $request->transactionType = Input::get('transactionType');
        $request->country = Input::get('country');

        $request->save();

        // username: 77802-1
        // password: statusdev

        $params = new StdClass();
        $params->request = new StdClass();
        $params->request->pUsername = "77802-1";
        $params->request->pPassword = "statusdev";
        $params->request->pMyOrigin = "StatusData";
        $params->request->pVersion = "3.0";
        $params->request->pInputType = "XML";
        $params->request->pTransactionData = "<fullEnquiry>
                                                <Identity_number>7408285107080</Identity_number>
                                                <Passport_flag>Y</Passport_flag>
                                                <gender>M</gender>
                                                <dateOfBirth>20140121</dateOfBirth>
                                                <Surname>Goofy</Surname>
                                                <Forename>Just</Forename>
                                                <ResultType>PDF</ResultType>
                                                <Enq_Purpose>12</Enq_Purpose>
                                                <incomeAmount>0</incomeAmount>
                                                <productId>1</productId>
                                             </fullEnquiry>";

        $options = array('trace' => 1, 'exceptions'  => 1);

        $wsdl = "https://webservices-uat.compuscan.co.za/ConsumerCreditReportService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient'))
        {
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->doCCRFullEnquiry($params);

        dd($response);

        $result=$response->TransReplyClass;


        if($result->transactionCompleted){

            $results = $response->TransReplyClass->retData;
            $xml = simplexml_load_string($results);


        }

        else{
            if($response->TransReplyClass->errorCode == -101)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Error parsing input JSON.');
            }
            elseif($response->TransReplyClass->errorCode == -102)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Not all variables are filled in.');
            }
            if($response->TransReplyClass->errorCode == -103)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Invalid Parameters.');
            }
            elseif($response->TransReplyClass->errorCode == -104)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Incorrect version number.');
            }
            if($response->TransReplyClass->errorCode == -105)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Incorrect input/output type.');
            }
            elseif($response->TransReplyClass->errorCode == -107)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Incorrect transaction type.');
            }
            if($response->TransReplyClass->errorCode == -108)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Username or Password is incorrect for this Branch.');
            }
            elseif($response->TransReplyClass->errorCode == -109)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Your user is not activated for this service.');
            }
            if($response->TransReplyClass->errorCode == -110)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Branch not switched on for this service.');
            }
            elseif($response->TransReplyClass->errorCode == -111)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Invalid transaction XML.');
            }
            if($response->TransReplyClass->errorCode == -112)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Invalid transaction JSON.');
            }
            elseif($response->TransReplyClass->errorCode == -113)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Transaction file does not exist.');
            }
            if($response->TransReplyClass->errorCode == -114)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Job ID must be numeric.');
            }
            elseif($response->TransReplyClass->errorCode == -115)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Invalid Job ID.');
            }
            if($response->TransReplyClass->errorCode == -116)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> See First Responses for Errors.');
            }
            elseif($response->TransReplyClass->errorCode == -117)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Incorrect request type.');
            }
            if($response->TransReplyClass->errorCode == -997)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Problems creating Job.');
            }
            elseif($response->TransReplyClass->errorCode == -999)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Internal Error.');
            }
        }


        return Redirect::to('bank-code-options')
            ->with('view-success', ' An email with your Job Number will be sent to the email address you specified. use the job number to collect your report');
    }

    public function view1stResponse()
    {
        return View::make('bank-codes.BCS-reponse1');
    }

    public function showJobBCSstatus()
    {
        return View::make('bank-codes.check-BCS-status');
    }

    public function serverBankCodeOption()
    {
        return View::make('pages.bank-code-options');
    }

    public function checkBCSstatus()
    {
        $params = new StdClass();
        $params->request = new StdClass();
        $params->request->pUsername = "77802-1";
        $params->request->pPassword = "statusdev";
        $params->request->pMyOrigin = "StatusData";
        $params->request->pVersion = "1.0";
        $params->request->pOutputType = "XML";
        $params->request->pJobId = Input::get('jobId');

        $options = array('trace' => 1, 'exceptions'  => 1);
        //Configure the WSDL location
        // echo "Configuring WSDL<br/>";
        $wsdl = "https://cbw-uat.compuscan.co.za/BankCodesService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient'))
        {
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->DoBankCodesCheckStatus($params);

        $result=$response->TransReplyClass;

        $request = DB::table('bcss')
            ->where('jobId','=',Input::get('jobId'))
            ->first();

        if($result->transactionCompleted){

            $results = $response->TransReplyClass->retData;

            //$xml = file_get_contents($results);
            $sxe = preg_replace('#&(?=[a-z_0-9]+=)#', '&amp;', $results);
            //$sxe = simplexml_load_string($xml);

            $xml = simplexml_load_string($sxe);


            $LoadRef = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->LOAD_REF;
            $status = $xml->STATUS_DES;
            $dateCreated = $xml->DATE_CREATED;
            $clientRef = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->CLIENT_REF;
            $recordNum = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->RECORD_NUM;
            $accountNum = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->ACCOUNT_NUMBER;
            $idNumber = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->ID_NUMBER;
            $clientName = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->CLIENT_NAME;
            $bank = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->BANK;
            $branchName = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->BRANCH_NAME;
            $branchCode = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->BRANCH_CODE;
            $emptyReason = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->BANK_CODE_EMPTY_REASON;
            $dateOpened = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->DATE_ACCOUNT_OPENED;
            $dishonors = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->DISHONORS;
            $conduct = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->CONDUCT_OF_ACCOUNT;
            $terms = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->TERMS;
            $origin = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->ORIGIN;
            $avsrDone = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_DONE;
            $avsrSendBank = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_SEND_BANK;
            $bankCode = $avsrSendBank = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->BANK_CODE;
            $avsrReceiveBank = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_RECV_BANK;
            $avsrReceiveBranch = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_RECV_BRANCH;
            $avsrLateDelivery = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_LATE_DELIVERY;
            $avsrAccountFound = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_ACC_FOUND;
            $avsrAccountOpened = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_ACC_OPEN;
            $avsrAccountLength = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_ACC_LENGTH;
            $avsrIdNumberMatch = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_ID_NUMBER_MATCH;
            $avsrNameMatch = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_NAME_MATCH;
            $avsrAccountDebits = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_ACC_DEBITS;
            $avsrAccountCredit = $xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE->AVSR_RESULT->AVSR_ACC_CREDIT;



            if($xml->FINAL_RESPONSES_CONTENT->FINAL_RESPONSE)
            {
                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'status' => $status
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'dateCreated' => $dateCreated
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'loadRef' => $LoadRef
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'clientRef' => $clientRef
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'recordNumber' => $recordNum
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'idNumber' => $idNumber
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'name' => $clientName
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'emptyReason' => $emptyReason
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'dateOpened' => $dateOpened
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'dishonors' => $dishonors
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'conduct' => $conduct
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'origin' => $origin
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'avsrDone' => $avsrDone
                        )
                    );

                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'terms' => $terms
                        )
                    );
                DB::table('bcss')
                    ->where('id','=', $request->id)
                    ->update(array(
                            'bankCode' => $bankCode
                        )
                    );
                if($avsrDone)
                {
                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrSendBank' => $avsrSendBank
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrReceiveBank' => $avsrReceiveBank
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrReceiveBranch' => $avsrReceiveBranch
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrLateDelivery' => $avsrLateDelivery
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrAccountFound' => $avsrAccountFound
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrAccountOpened' => $avsrAccountOpened
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrAccountLength' => $avsrAccountLength
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrIdNumberMatch' => $avsrIdNumberMatch
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrNameMatch' => $avsrNameMatch
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrAccountDebits' => $avsrAccountDebits
                            )
                        );

                    DB::table('bcss')
                        ->where('id','=', $request->id)
                        ->update(array(
                                'avsrAccountCredit' => $avsrAccountCredit
                            )
                        );
                }
            }
        }

        return View::make('bank-codes.BCS-results', array('request' => $request));
    }

    public function seeBCSResults($request)
    {
        //temporary need to add actual user details

        return View::make('bank-codes.BCS-results')
            ->with('request',$request);
    }

    public function serverOFS()
    {
        return View::make('bank-codes.OFS-request');
    }

    public function handleOFS()
    {

        $validator = Validator::make(Input::all(),
            [
                'accountNumber' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }


        $request = new OFS;
        $request->idNumber = Input::get('idNumber');
        $request->accountNumber = Input::get('accountNumber');
        $request->email = Input::get('email');

        $request->save();

        $params = new StdClass();
        $params->request = new StdClass();
        $params->request->pUsername = "77802-1";
        $params->request->pPassword = "statusdev";
        $params->request->pMyOrigin = "StatusData";
        $params->request->pVersion = "1.0";
        $params->request->pInputType = "XML";
        $params->request->pTranType = "OFS";
        $params->request->pEmailAddress = "rachael@mybusinessvault.co.za";
        $params->request->pTransaction = "<BANK_CODE_TRANSACTION>
                        <RECORDS>
                            <RECORD>
                                <ACCOUNT_NUMBER>123456789</ACCOUNT_NUMBER>
                                <CLIENT_REF>6514</CLIENT_REF>
                                <RECORD_NUM>1</RECORD_NUM>
                                <CLIENT_NAME>John Doe</CLIENT_NAME>
                                <ID_NUMBER>8209147250087</ID_NUMBER>
                            </RECORD>
                        </RECORDS>
                    </BANK_CODE_TRANSACTION>";

        $options = array('trace' => 1, 'exceptions'  => 1);
        //Configure the WSDL location
        // echo "Configuring WSDL<br/>";
        $wsdl = "https://cbw-uat.compuscan.co.za/BankCodesService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient'))
        {
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->DoBankCodesSubmit($params);

        $result=$response->TransReplyClass;
        dd($result);
        $jobId="";
        $jobStatusDescription="";
        $dateCreated="";

        if($result->transactionCompleted){

            $results = $response->TransReplyClass->retData;
            $xml = simplexml_load_string($results);

            $jobId =  $xml->JOB_ID;
            $jobStatusDescription = $xml->STATUS_DES;
            $dateCreated = $xml->DATE_CREATED;

            if($xml->FIRST_RESPONSES_CONTENT->FIRST_RESPONSE->STATUS_CODE_ROOT->STATUS_CODE->DESCRIPTION)
            {
                Redirect::back()->with('view-success', 'ERROR: ONFILE RECORD NOT FOUND');
            }

        }

        else{
            Redirect::to('dashboard')->with('view-success', 'ERROR: Please contact system administrator');

            //echo("Error Code:".$response->TransReplyClass->errorCode."<br/>Error String:".
            //  $response->TransReplyClass->errorString);
        }


        return Redirect::to('BCS-reponse1')->with('view-success', ' SUCCESS: OFS request sent');
    }


    public function serverAVSR()
    {
        return View::make('bank-codes.AVSR-request');
    }

    public function handleAVSR()
    {

        $validator = Validator::make(Input::all(),
            [
                'accountNumber' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $request = new AVSR;
        $request->idNumber = Input::get('idNumber');
        $request->accountNumber = Input::get('accountNumber');
        $request->initials = Input::get('initials');
        $request->surname = Input::get('surname');
        $request->branchCode = Input::get('branchCode');
        $request->accountType = Input::get('accountType');
        $request->save();

        $params = new StdClass();
        $params->pUsername="77802-1";
        $params->pPassword="statusdev";
        $params->pMyOrigin="statudData";
        $params->pVersion="1.0";
        $params->pSubmissionType="RS";
        $params->pFileContent=
            "<AVS_TRANSACTIONS>
				<VERSION>1.0</VERSION>
                <DATE_CREATED>20170405</DATE_CREATED>
                <RECORDS>
					<RECORD num='1'>
						<BANK_BRANCH_CD>$request->branchCode</BANK_BRANCH_CD>
                        <BANK_ACC>$request->accountNumber</BANK_ACC>
                        <BANK_ACC_TYPE>$request->accountType</BANK_ACC_TYPE>
                        <ID_NUMBER>$request->idNumber</ID_NUMBER>
                        <INITIALS>$request->initials</INITIALS>
                        <SURNAME>$request->surname</SURNAME>
                    </RECORD>
               </RECORDS>
			</AVS_TRANSACTIONS>";

        $options = array('trace' => 1, 'exceptions'  => 1);
        //Configure the WSDL location

        $wsdl = "https://webservices-uat.compuscan.co.za/AVSService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient')){
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->SubmitFile($params);
        //Save the response in a StdClass object
        $result=$response->TransReplyClass;

        if($result->transactionCompleted) {

            $jobId = htmlentities($response->TransReplyClass->retData);

            $params = new StdClass();
            $params->pUsername = "77802-1";
            $params->pPassword = "statusdev";
            $params->pMyOrigin = "statudData";
            $params->pVersion = "1.0";
            $params->pJobId = $jobId;

            $options = array('trace' => 1, 'exceptions' => 1);
            //Configure the WSDL location

            $wsdl = "https://webservices-uat.compuscan.co.za/AVSService?wsdl";

            //Check if the PHP-SOAP module is installed
            if (!class_exists('SoapClient')) {
                die("Missing PHP-Soap module.");
            }
            //Create the webservice connection

            $webservice = new SoapClient($wsdl, $options);
            $response = $webservice->CheckStatus($params);
            //Save the response in a StdClass object
            $result = $response->TransReplyClass;

            $result = $response->TransReplyClass;

            if ($result->transactionCompleted) {

                $results = $response->TransReplyClass->retData;
                $xml = simplexml_load_string($results);


                $data = ['xml' => $xml];

                Mail::send('emails.AVSR', $data, function ($message) {
                    $message->to('rachael@mybusinessvault.co.za', 'Rachael Maphopha')->to('koketso.maphopha@gmail.com', 'Koketso')->subject('Bank Code - Job Number');
                    $message->from('Admin2@prestigeAdvantage.co.za');
                });

                return Redirect::to('bank-code-options')
                    ->with('view-success', ' Your Bank Verification Information will be sent shortly');


            } else {

                echo("Error Code:" . $response->TransReplyClass->errorCode . "<br/>Error String:" .
                    $response->TransReplyClass->errorString);
            }

        }

        return Redirect::to('bank-code-options')
            ->with('view-success', ' An email with your Job Number has been sent. Use the job number to collect your report');

    }

    public function serverCollectAVSR()
    {
        return View::make('bank-codes.collect-AVSR-report');
    }

    public function viewAVSRReport()
    {}

    public function handleCollectAVSR()
    {

        $validator = Validator::make(Input::all(),
            [
                'jobId' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $jobId = Input::get('jobId');

        $params = new StdClass();
        $params->pUsername="77802-1";
        $params->pPassword="statusdev";
        $params->pMyOrigin="statudData";
        $params->pVersion="1.0";
        $params->pJobId=$jobId;

        $options = array('trace' => 1, 'exceptions'  => 1);
        //Configure the WSDL location

        $wsdl = "https://webservices-uat.compuscan.co.za/AVSService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient')){
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->CheckStatus($params);
        //Save the response in a StdClass object
        $result=$response->TransReplyClass;

        $result=$response->TransReplyClass;
/*
        if($result->transactionCompleted){

            $results = $response->TransReplyClass->retData;
            $xml = simplexml_load_string($results);

            DB::table('bcss')
                ->where('id','=', $request->id)
                ->update(array(
                        'status' => $status
                    )
                );

            return View::make('bank-codes.AVSR-report')
                ->with('xml', $xml);

        }*/

    }

    public function serverCollectOFS()
    {
        return View::make('bank-codes.collect-OFS-report');
    }

    public function serverManageUsers()
    {
        $companies = DB::table('companies')
            ->orderBy('companyName','asc')
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('users.manage-users')
            ->with('user',$user)
            ->with('companies',$companies);
    }

    public function serverManageInvoices()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

       // $companies = Transaction::select('company')->distinct()->get();
        $companies = DB::table('companies')
            ->get();

        return View::make('invoice.manage-invoices')
            ->with('user',$user)
            ->with('companies',$companies);
    }


    public function newUser($company)
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $companies = DB::table('companies')
            ->get();

        return View::make('users.new-user')
            ->with('companies',$companies)
            ->with('user',$user)
            ->with('company',$company);
    }

    public function CreateNewUser($company)
    {

        $validator = Validator::make(Input::all(),
            [
                'name' => 'required',
                'email' => 'required',
                'password' => 'required',
                'password1' => 'required'
            ]);

        $users = DB::table('users')
            ->get();

        foreach($users as $user)
        {
            if($user->email==Input::get('email'))
            {
                return Redirect::back()->with('view-error', ' This email address already exists, rather link email address to multiple companies')->withInput()->withErrors($validator);
            }
        }

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        if((Input::get('password'))!=(Input::get('password1')))
        {
            return Redirect::back()->with('view-error', ' Passwords do not match')->withInput()->withErrors($validator);
        }

        $user = new User;
        $user->password = Hash::make(Input::get('password'));
        $user->email = Input::get('email');
        $user->name = Input::get('name');
        $user->role = 'user';
        $user->designation = Input::get('designation');
        if(Input::has('companies')) {
            $user->linkedCompanies = implode(',', Input::get('companies'));
        }
        else{
            $user->linkedCompanies = $company.',';
        }
        $user->companyName = $company;

        $user->save();

        $password =  Input::get('password');

        $data = ['user' => $user, 'password' => $password];

        Mail::send('emails.new-user', $data, function($message) use($user)
        {
            $message->to(Input::get('email'),'New User')->subject('New user account for the Prestige Advantage client system');
            $message->from('Admin2@prestigeAdvantage.co.za');

        });
        $users = DB::table('users')
            ->where('companyName','=',$company)
            ->orderBy('name','asc')
            ->paginate(10);

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('management.view-users')
            ->with('user',$user)
            ->with('users',$users)
            ->with('company',$company)
            ->with('view-success', ' SUCCESS: New User Added');

    }

    public function handleEditUser($user)
    {
        $validator = Validator::make(Input::all(),
            [
                'name' => 'required',
                'email' => 'required',
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        if((Input::get('password'))!=(Input::get('password1')))
        {
            return Redirect::back()->with('view-error', 'Passwords do not match ')->withInput()->withErrors($validator);
        }

        if(Input::has('name')) {
            DB::table('users')
                ->where('id','=', $user)
                ->update(array(
                        'name' => Input::get('name')
                    )
                );
        }

        if(Input::has('companyName')) {
            DB::table('users')
                ->where('id','=', $user)
                ->update(array(
                        'companyName' => Input::get('companyName')
                    )
                );
        }

        if(Input::has('designation')) {
            DB::table('users')
                ->where('id','=', $user)
                ->update(array(
                        'designation' => Input::get('designation')
                    )
                );
        }

        if(Input::has('email')) {
            DB::table('users')
                ->where('id','=', $user)
                ->update(array(
                        'email' => Input::get('email')
                    )
                );
        }

        if((Input::has('password') and Input::has('password1')) and Input::get('password')===Input::get('password1')) {
            DB::table('users')
                ->where('id','=', $user)
                ->update(array(
                        'password' => Hash::make(Input::get('password'))
                    )
                );

            $user = DB::table('users')
                ->where('id','=',$user)
                ->first();

            $password = Input::get('password');

            $data = ['user' => $user, 'password' => $password];

            Mail::send('emails.passwordChange', $data, function($message) use($user)
            {
                $message->to($user->email,$user->name)->bcc('rachael@statusdata.co.za','Rach')->subject('Password Change');
                $message->from('Admin2@prestigeAdvantage.co.za');

            });
        }



        return Redirect::to('all-users')->with('view-success', 'SUCCESS: User Updated');
    }

    public function serveEditUser($user)
    {
        $user = DB::table('users')
            ->where('id','=',$user)
            ->first();

        $companies = DB::table('companies')
            ->get();

        return View::make('users.edit-user', compact('user', 'companies'));
    }

    public function deleteUser($user)
    {
        DB::table('users')
            ->where('id','=',$user)
            ->delete();

        return Redirect::to('all-users')->with('view-success', ' SUCCESS: User Deleted');
    }

    public function searchUser()
    {
        $validator = Validator::make(Input::all(),
            [
                'search' => 'required',
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'No search entered, please try again')->withInput()->withErrors($validator);
        }

        $query = Request::get('search');

        $users = DB::table('users')
            ->where('email', 'LIKE', '%' . $query . '%')//email
            ->orWhere('companyName', 'LIKE', '%' . $query . '%')//company
            ->orWhere('name', 'LIKE', '%' . $query . '%')//name
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();



        if($users==NULL)
        {
            return Redirect::back()->with('view-search-error', '<i class="white fa fa-times"></i> <strong>Oops!</strong>  There where no results found, please try searching by user name or email or role.');
        }

        else
        {
            // multiple users search results
            return View::make('users.user-search')
                ->with('user', $user)
                ->with('users',$users);

        }
    }

    public function manageInvoices()
    {
        $companies = Transaction::select('company')->distinct()->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('invoice.manage-invoices')
            ->with('user',$user)
            ->with('companies',$companies);
    }

    public function serverSetPricing($company)
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        return View::make('invoice.set-pricing')
            ->with('company',$company)
            ->with('user',$user);
    }

    public function handleSetPricing($company)
    {
        $validator = Validator::make(Input::all(),
            [
                'compuscan_on_file' => 'required',

                'transunion_on_file' => 'required',

                'compuscan_principal_on_file' => 'required',

                'transunion_24hr_bank_code' => 'required',

                'compuscan_24hr_principal_bank_code' => 'required',

                'transunion_24hr_principal_bank_code' => 'required',

                'compuscan_4hr_bank_code' => 'required',

                'compuscan_4hr_principal_bank_code' => 'required',

                'transunion_4hr_principal_bank_code' => 'required',

                'compuscan_company_deeds' => 'required',

                'transunion_principal_deeds' => 'required',

                'compuscan_comprehensive' => 'required',

                'status_data_comprehensive' => 'required',

                'quick_fix' => 'required',

                'inoxico_quick' => 'required',

                'inoxico_basic' => 'required',

                'inoxico_detailed' => 'required',

                'inoxico_comprehensive' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' Some prices missing, please review below')->withInput()->withErrors($validator);
        }

        $pricing = new Pricing;
        $pricing->company = $company;
        $pricing->transunion_on_file = Input::get('transunion_on_file');
        $pricing->transunion_principal_deeds = Input::get('transunion_principal_deeds');
        $pricing->compuscan_principal_on_file = Input::get('compuscan_principal_on_file');
        $pricing->compuscan_company_deeds = Input::get('compuscan_company_deeds');
        $pricing->transunion_24hr_principal_bank_code = Input::get('transunion_24hr_principal_bank_code');
        $pricing->transunion_4hr_principal_bank_code = Input::get('transunion_4hr_principal_bank_code');
        $pricing->compuscan_on_file = Input::get('compuscan_on_file');
        $pricing->compuscan_24hr_bank_code = Input::get('compuscan_24hr_bank_code');
        $pricing->transunion_24hr_bank_code = Input::get('transunion_24hr_bank_code');
        $pricing->compuscan_4hr_bank_code = Input::get('compuscan_4hr_bank_code');
        $pricing->compuscan_24hr_principal_bank_code = Input::get('compuscan_24hr_principal_bank_code');
        $pricing->compuscan_4hr_principal_bank_code = Input::get('compuscan_4hr_principal_bank_code');
        $pricing->status_data_detailed = Input::get('status_data_detailed');
        $pricing->compuscan_detailed = Input::get('compuscan_detailed');
        $pricing->quick_fix = Input::get('quick_fix');
        $pricing->compuscan_detailed = Input::get('compuscan_detailed');
        $pricing->compuscan_comprehensive = Input::get('compuscan_comprehensive');
        $pricing->status_data_comprehensive = Input::get('status_data_comprehensive');

        $pricing->inoxico_quick = Input::get('inoxico_quick');
        $pricing->inoxico_basic = Input::get('inoxico_basic');
        $pricing->inoxico_detailed = Input::get('inoxico_detailed');
        $pricing->inoxico_comprehensive = Input::get('inoxico_comprehensive');
        $pricing->save();

        $companies = DB::table('companies')
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('users.manage-users')
            ->with('companies',$companies)
            ->with('user',$user)
            ->with('view-success', 'SUCCESS: Pricing has been successfully set');
    }

    public function serverQuote()
    {
        return View::make('pages.quote');
    }

    public function debtCollection()
    {
        return View::make('pages.debt-collection');
    }

    protected static $rules7 = [
        'debtor' => 'required',
        'reference' => 'required',
        'registration_number' => 'required',
        'amount' => 'required',
        'outstandingSince' => 'required',
        'cause' => 'required',
        'interest' => 'required',
        'surerty' => 'required',
        'contactPerson' => 'required',
        'telephone' => 'required',
        'email' => 'required|email',
        'cell' => 'required'

    ];

    public function handleDebtCollection()
    {
        $validator = Validator::make(Input::all(), static::$rules7);

        if($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', '
        Oops! There was a problem with your entry, please try again.');
        }

        $debtCollection = new DebtCollection;
        $debtCollection->debtor = Input::get('debtor');
        $debtCollection->reference = Input::get('reference');
        $debtCollection->registration_number = Input::get('registration_number');
        $debtCollection->amount = Input::get('amount');
        $debtCollection->outstandingSince = Input::get('outstandingSince');
        $debtCollection->cause = Input::get('cause');
        $debtCollection->interest = Input::get('interest');
        $debtCollection->surerty = Input::get('surerty');
        $debtCollection->otherSurerty = Input::get('otherSurerty');
        $debtCollection->contactPerson = Input::get('contactPerson');
        $debtCollection->telephone = Input::get('telephone');
        $debtCollection->email = Input::get('email');
        $debtCollection->cell = Input::get('cell');
        $debtCollection->fax = Input::get('fax');
        $debtCollection->dated = Input::get('dated');
        $debtCollection->postalAddress = Input::get('postalAddress');
        $debtCollection->physicalAddress = Input::get('physicalAddress');

        if (Input::hasFile('statement'))
        {
            $file = Input::file('statement');
            $file->move('app/statement/', $file->getClientOriginalName());
            $debtCollection->statement = 'app/statement/'.$file->getClientOriginalName();

        }
        if (Input::hasFile('creditApplication'))
        {
            $file = Input::file('creditApplication');
            $file->move('app/creditApplication/', $file->getClientOriginalName());
            $debtCollection->creditApplication = 'app/creditApplication/'.$file->getClientOriginalName();

        }
        $debtCollection->save();

        $data = ['debtCollection' => $debtCollection];

        Mail::send('emails.debtCollection', $data, function($message) use ($debtCollection)
        {
            $message->to('george@prestigecredit.co.za','George')->to('koketso.maphopha@gmail.com','Koketso')->subject('HandOver Application');
            $message->from('no-reply@prestige.co.za');
            $message->attach($debtCollection->statement);
            $message->attach($debtCollection->creditApplication);

        });

        return Redirect::back()->with('view-success', 'SUCCESS: Your Handover Application has been submitted');

    }

    protected static $rules4 = [
        'company_name' => 'required',
        'contact_name' => 'required',
        'designation' => 'required',
        'contact_number' => 'required',
        'email' => 'required'

    ];

    public function handleInsuranceQuote()
    {
        $validator = Validator::make(Input::all(), static::$rules4);

        if($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', '
        Oops! There was a problem with your entry, please try again.');
        }

        $insuranceApplication = new Insurance;
        $insuranceApplication->company_name = Input::get('company_name');
        $insuranceApplication->contact_name = Input::get('contact_name');
        $insuranceApplication->designation = Input::get('designation');
        $insuranceApplication->contact_number = Input::get('contact_number');
        $insuranceApplication->email = Input::get('email');

        if (Input::has('registration_number'))
        {
            $insuranceApplication->registration_number = Input::get('registration_number');
        }

        $insuranceApplication->save();

        $data = ['insuranceApplication' => $insuranceApplication];

        Mail::send('emails.insuranceApplication', $data, function($message) use ($insuranceApplication)
        {
            $message->to('info@prestigecredit.co.za','Info at Prestige')->to('rachael@mybusinessvault.co.za','Rachael Maphopha')->subject('Insurance Quote Request');
            $message->from('Admin2@prestigeAdvantage.co.za');
        });

        return Redirect::back()->with('view-success', 'SUCCESS: Your insurance quote request has been submitted');

    }

    public function viewBureauMenu()
    {
        return View::make('pages.bureau-reports-menu');
    }

    public function serverQuerySystem()
    {
        return View::make('management.query-system');
    }

    protected static $rules5 = [
        'name' => 'required',
        'query' => 'required',
        'email' => 'required|email'
    ];

    public function handleQuerySystem()
    {
        $validator = Validator::make(Input::all(), static::$rules4);

        if($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', '
        Oops! There was a problem with your entry, please try again.');
        }

        $querySystem = new QuerySystem;
        $querySystem->name = Input::get('name');
        $querySystem->email = Input::get('email');
        $querySystem->query = Input::get('query');
        if (Input::hasFile('attachment'))
        {
            $file = Input::file('attachment');
            $file->move('attachments/', $file->getClientOriginalName());
            $querySystem->attachment = 'attachment/'.$file->getClientOriginalName();
        }

        $querySystem->save();
        $attachment =$querySystem->attachment;

        $data = ['querySystem' => $querySystem];

        Mail::send('emails.querySystem', $data, function($message) use($attachment)
        {
            $message->to('rachael@mybusinessvault.co.za','Rachael Maphopha')->to('insure@collectionsonline.co.za','Online Collections')->to('koketso.maphopha@gmail.com','Koketso')->attachData($attachment, "Attachments")->subject('Query Report System with Status Data');
            $message->from('Admin2@prestigeAdvantage.co.za');

        });



        return Redirect::back()->with('view-success', 'SUCCESS: Query has been submitted, the Status Data team will get back to you soon.');

    }

    public function serverManagementDashboard()
    {
        $image = DB::table('banner')
            ->where('id','=',2)
            ->first();
        $image = $image->image;

        /*
        $url = 'https://cir.credit-network.biz/api/Application?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&filter=';


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $xmlresponse = curl_exec($ch);

            $xml=simplexml_load_file($xmlresponse.'.xml');
        */

        $transactions = DB::table('transactions')
            ->orderBy('created_at','desc')
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('management.management-dashboard')
            ->with('user',$user)
            ->with('transactions',$transactions)
            ->with('image',$image);
    }

    public function searchManagementDashboard()
    {
        $validator = Validator::make(Input::all(),
            [
                'search' => 'required',
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'No search entered, please try again')->withInput()->withErrors($validator);
        }

        $query = Request::get('search');

        $transactions = DB::table('transactions')
            ->where('user', 'LIKE', '%' . $query . '%')//user
            ->orWhere('company', 'LIKE', '%' . $query . '%')//company
            ->orWhere('product', 'LIKE', '%' . $query . '%')//product
            ->paginate(10);

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if($transactions==NULL)
        {
            return Redirect::back()->with('view-search-error', '<i class="white fa fa-times"></i> <strong>Oops!</strong>  There where no results found, please try searching by user name or email or role.');
        }

        else
        {
            return View::make('management.dashboard-search')
                ->with('user', $user)
                ->with('transactions',$transactions);
        }
    }

    public function searchCompany()
    {
        $validator = Validator::make(Input::all(),
            [
                'search' => 'required',
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'No search entered, please try again')->withInput()->withErrors($validator);
        }

        $query = Request::get('search');

        $companies = DB::table('companies')
            ->where('companyName', 'LIKE', '%' . $query . '%')//company
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if($companies==NULL)
        {
            return Redirect::back()->with('view-search-error', '<i class="white fa fa-times"></i> <strong>Oops!</strong>  There where no results found, please try searching by user name or email or role.');
        }

        else
        {
            return View::make('users.company-search')
                ->with('user', $user)
                ->with('companies',$companies);
        }
    }

    public function serverClientUsage()
    {
        $users = DB::table('users')
            ->paginate(10);

        return View::make('management.client-usage')
            ->with('users',$users);
    }

    public function serverEditPricing($name)
    {
       $pricing = DB::table('pricing')
           ->where('company','=',$name)
           ->first();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('invoice.edit-pricing')
            ->with('user',$user)
            ->with('pricing',$pricing);
    }

    public function handleEditPricing($name)
    {
        $validator = Validator::make(Input::all(),
            [
                'compuscan_on_file' => 'required',

                'transunion_on_file' => 'required',

                'compuscan_principal_on_file' => 'required',

                'transunion_24hr_bank_code' => 'required',

                'compuscan_24hr_principal_bank_code' => 'required',

                'transunion_24hr_principal_bank_code' => 'required',

                'compuscan_4hr_bank_code' => 'required',

                'compuscan_4hr_principal_bank_code' => 'required',

                'transunion_4hr_principal_bank_code' => 'required',

                'compuscan_company_deeds' => 'required',

                'transunion_principal_deeds' => 'required',

                'compuscan_comprehensive' => 'required',

                'status_data_comprehensive' => 'required',

                'quick_fix' => 'required',

                'inoxico_quick' => 'required',

                'inoxico_basic' => 'required',

                'inoxico_detailed' => 'required',

                'inoxico_comprehensive' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $name = DB::table('pricing')
            ->where('id','=',$name)
            ->first();


        if(Input::has('compuscan_on_file')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_on_file' => Input::get('compuscan_on_file')
                    )
                );
        }

        if(Input::has('inoxico_quick')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'inoxico_quick' => Input::get('inoxico_quick')
                    )
                );
        }

        if(Input::has('inoxico_basic')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'inoxico_basic' => Input::get('inoxico_basic')
                    )
                );
        }

        if(Input::has('inoxico_detailed')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'inoxico_detailed' => Input::get('inoxico_detailed')
                    )
                );
        }

        if(Input::has('inoxico_comprehensive')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'inoxico_comprehensive' => Input::get('inoxico_comprehensive')
                    )
                );
        }


        if(Input::has('transunion_on_file')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_on_file' => Input::get('transunion_on_file')
                    )
                );
        }

        if(Input::has('compuscan_principal_on_file')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_principal_on_file' => Input::get('compuscan_principal_on_file')
                    )
                );
        }

        if(Input::has('transunion_24hr_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_24hr_bank_code' => Input::get('transunion_24hr_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_24hr_principal_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_24hr_principal_bank_code' => Input::get('compuscan_24hr_principal_bank_code')
                    )
                );
        }

        if(Input::has('transunion_24hr_principal_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_24hr_principal_bank_code' => Input::get('transunion_24hr_principal_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_4hr_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_4hr_bank_code' => Input::get('compuscan_4hr_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_24hr_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_24hr_bank_code' => Input::get('compuscan_24hr_bank_code')
                    )
                );
        }

        if(Input::has('transunion_4hr_principal_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_4hr_principal_bank_code' => Input::get('transunion_4hr_principal_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_4hr_principal_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_4hr_principal_bank_code' => Input::get('compuscan_4hr_principal_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_company_deeds')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_company_deeds' => Input::get('compuscan_company_deeds')
                    )
                );
        }

        if(Input::has('transunion_principal_deeds')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_principal_deeds' => Input::get('transunion_principal_deeds')
                    )
                );
        }

        if(Input::has('Detailed_transunion')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'Detailed_transunion' => Input::get('Detailed_transunion')
                    )
                );
        }


        if(Input::has('compuscan_detailed')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_detailed' => Input::get('compuscan_detailed')
                    )
                );
        }

        if(Input::has('status_data_detailed')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'status_data_detailed' => Input::get('status_data_detailed')
                    )
                );
        }


        if(Input::has('compuscan_comprehensive')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_comprehensive' => Input::get('compuscan_comprehensive')
                    )
                );
        }

        if(Input::has('status_data_comprehensive')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'status_data_comprehensive' => Input::get('status_data_comprehensive')
                    )
                );
        }

        if(Input::has('quick_fix')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'quick_fix' => Input::get('quick_fix')
                    )
                );
        }


        return Redirect::back()->with('view-success', 'SUCCESS: Pricing Updated');
    }

    public function serverEditPricing2($name)
    {
        $pricing = new Pricing;
        $pricing->company = $name;
        $pricing->save();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('invoice.edit-pricing')
            ->with('user',$user)
            ->with('pricing',$pricing);
    }

    public function handleEditPricing2($name)
    {
        $validator = Validator::make(Input::all(),
            [
                'compuscan_on_file' => 'required',

                'transunion_on_file' => 'required',

                'compuscan_principal_on_file' => 'required',

                'transunion_24hr_bank_code' => 'required',

                'compuscan_24hr_principal_bank_code' => 'required',

                'transunion_24hr_principal_bank_code' => 'required',

                'compuscan_4hr_bank_code' => 'required',

                'compuscan_4hr_principal_bank_code' => 'required',

                'transunion_4hr_principal_bank_code' => 'required',

                'compuscan_company_deeds' => 'required',

                'transunion_principal_deeds' => 'required',

                'compuscan_comprehensive' => 'required',

                'status_data_comprehensive' => 'required',

                'quick_fix' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $name = DB::table('pricing')
            ->where('id','=',$name)
            ->first();


        if(Input::has('compuscan_on_file')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_on_file' => Input::get('compuscan_on_file')
                    )
                );
        }


        if(Input::has('transunion_on_file')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_on_file' => Input::get('transunion_on_file')
                    )
                );
        }

        if(Input::has('compuscan_principal_on_file')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_principal_on_file' => Input::get('compuscan_principal_on_file')
                    )
                );
        }

        if(Input::has('transunion_24hr_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_24hr_bank_code' => Input::get('transunion_24hr_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_24hr_principal_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_24hr_principal_bank_code' => Input::get('compuscan_24hr_principal_bank_code')
                    )
                );
        }

        if(Input::has('transunion_24hr_principal_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_24hr_principal_bank_code' => Input::get('transunion_24hr_principal_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_4hr_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_4hr_bank_code' => Input::get('compuscan_4hr_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_24hr_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_24hr_bank_code' => Input::get('compuscan_24hr_bank_code')
                    )
                );
        }

        if(Input::has('transunion_4hr_principal_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_4hr_principal_bank_code' => Input::get('transunion_4hr_principal_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_4hr_principal_bank_code')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_4hr_principal_bank_code' => Input::get('compuscan_4hr_principal_bank_code')
                    )
                );
        }

        if(Input::has('compuscan_company_deeds')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_company_deeds' => Input::get('compuscan_company_deeds')
                    )
                );
        }

        if(Input::has('transunion_principal_deeds')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'transunion_principal_deeds' => Input::get('transunion_principal_deeds')
                    )
                );
        }

        if(Input::has('Detailed_transunion')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'Detailed_transunion' => Input::get('Detailed_transunion')
                    )
                );
        }


        if(Input::has('compuscan_detailed')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_detailed' => Input::get('compuscan_detailed')
                    )
                );
        }

        if(Input::has('status_data_detailed')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'status_data_detailed' => Input::get('status_data_detailed')
                    )
                );
        }


        if(Input::has('compuscan_comprehensive')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'compuscan_comprehensive' => Input::get('compuscan_comprehensive')
                    )
                );
        }

        if(Input::has('status_data_comprehensive')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'status_data_comprehensive' => Input::get('status_data_comprehensive')
                    )
                );
        }

        if(Input::has('quick_fix')) {
            DB::table('pricing')
                ->where('company','=', $name->company)
                ->update(array(
                        'quick_fix' => Input::get('quick_fix')
                    )
                );
        }


        return Redirect::back()->with('view-success', 'SUCCESS: Pricing Updated');
    }


    public function handle()
    {

        $validator = Validator::make(Input::all(),
            [
                'accountNumber' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }


        $request = new AVSR;
        $request->idNumber = Input::get('idNumber');
        $request->accountNumber = Input::get('accountNumber');
        $request->initials = Input::get('initials');
        $request->surname = Input::get('surname');
        $request->branchCode = Input::get('branchCode');
        $request->accountType = Input::get('accountType');

        $request->save();

        $params = new StdClass();
        $params->request = new StdClass();
        $params->request->pUsername = "77802-1";
        $params->request->pPassword = "statusdev";
        $params->request->pMyOrigin = "StatusData";
        $params->request->pVersion = "1.0";
        $params->request->pSubmissionType = "RS";
        $params->request->pFileContent = "
                <AVS_TRANSACTIONS>
                    <VERSION>1.0</VERSION>
                    <DATE_CREATED>20120530</DATE_CREATED>
                        <RECORDS>
                            <RECORD num='1'>
                                <BANK_BRANCH_CD>$request->branchCode</BANK_BRANCH_CD>
                                <BANK_ACC>$request->accountNumber</BANK_ACC>
                                <BANK_ACC_TYPE>$request->accountType</BANK_ACC_TYPE>
                                <ID_NUMBER>$request->idNumber</ID_NUMBER>
                                <INITIALS>$request->initials</INITIALS>
                                <SURNAME>$request->surname</SURNAME>
                            </RECORD>
                        </RECORDS>
                </AVS_TRANSACTIONS>
        ";

        $options = array('trace' => 1, 'exceptions'  => 1);
        //Configure the WSDL location
        // echo "Configuring WSDL<br/>";
        $wsdl = "https://webservices-uat.compuscan.co.za/AVSService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient'))
        {
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->SubmitFile($params);

        $result=$response->TransReplyClass;

        $jobId="";
        $jobStatusDescription="";
        $dateCreated="";

        if($result->transactionCompleted){

            $results = $response->TransReplyClass->retData;
            $xml = simplexml_load_string($results);
            dd($xml);
            $jobId =  $results;


        }

        else{
            Redirect::to('dashboard')->with('view-success', 'ERROR: Please contact system administrator');

            //echo("Error Code:".$response->TransReplyClass->errorCode."<br/>Error String:".
            //  $response->TransReplyClass->errorString);
        }

        return Redirect::to('dashboard')->with('view-success', ' SUCCESS: AVRS request sent');

    }

    public function serverGenerateInvoice($company)
    {
        $transactions = DB::table('transactions')
            ->where('company','=',$company)
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $total = 0;

        foreach($transactions as $transaction)
        {
            $total = $total + $transaction->price;
        }

        return View::make('invoice.generate-invoice')
            ->with('user',$user)
            ->with('company',$company)
            ->with('total',$total)
            ->with('transactions',$transactions);
    }
    
    public function serverHandleGenerateInvoice($id)
    {
    	$client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $pricing = DB::table('pricing')
            ->where('user_id','=',$id)
            ->first();


        return View::make('invoice.generate-invoice')
            ->with('client',$client)
            ->with('pricing',$pricing);
      }

    public function serverPossibleMatchSearch()
    {
        return View::make('compuscan.compuscan-report');
    }

    public function handlePossibleMatchSearch()
    {
        $validator = Validator::make(Input::all(),
            [
                'companyName' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }


        $request = new Company;
        $request->companyName = Input::get('companyName');
        $request->RegNum1 = Input::get('RegNum1');
        $request->RegNum2 = Input::get('RegNum2');
        $request->RegNum3 = Input::get('RegNum3');
        $request->vatNumber = Input::get('vatNumber');
        $request->taxNumber = Input::get('taxNumber');
        $request->save();

        $params = new StdClass();
        $params->request = new StdClass();
        $params->request->pUsrnme = "77802-1";
        $params->request->pPasswrd = "statusdev";
        $params->request->pOrigin = "StatusData";
        $params->request->pVersion = "1.0";
        $params->request->pOrigin_Version = "1.0";
        $params->request->pTransaction = "
                <Transactions>
                    <Search_Criteria>
                        <Company_Name>$request->companyName</Company_Name>
                        <Reg_Number1>$request->RegNum1</Reg_Number1>
                        <Reg_Number2>$request->RegNum2</Reg_Number2>
                        <Reg_Number3>$request->RegNum3</Reg_Number3>
                        <Tax_Number>$request->vatNumber</Tax_Number>
                        <Vat_Number>$request->taxNumber</Vat_Number>
                        <ResultType>XML</ResultType>
                    </Search_Criteria>
                </Transactions>
        ";

        $options = array('trace' => 1, 'exceptions'  => 1);

        $wsdl = "https://webservices-uat.compuscan.co.za/CompanySearchService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient'))
        {
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection
        $webservice = new SoapClient($wsdl,$options);

        $response = $webservice->CompanyPossibleSearch($params);

        $result=$response->TransReplyClass;
        if($result->transactionCompleted){

            $results = $response->TransReplyClass->retData;
            $xml = simplexml_load_string($results);
            dd($xml);
            $companyID = $xml->POS_MATCHES->ROW['1']->COMPANY_ID;
            $enquiry = $xml->ENQUIRY_ID;


            /*
            $matchesResults = $xml->POS_MATCHES;

            $arraySize = sizeof($xml->POS_MATCHES->ROW);


            foreach($matchesResults as $result)
            {

            }

            $companyId = $xml->POS_MATCHES->ROW['1']->COMPANY_ID;
            $companyRegNumber = $xml->POS_MATCHES->ROW['1']->COMPANY_REG_NUMBER;
            $oldRegNumber = $xml->POS_MATCHES->ROW['1']->OLD_REGISTRATION_NUMBER;
            $companyName = $xml->POS_MATCHES->ROW['1']->COMPANY_NAME;
            $taxNumber = $xml->POS_MATCHES->ROW['1']->TAX_NUMBER;
            $vatNumber = $xml->POS_MATCHES->ROW['1']->VAT_NUMBER;
           //$rNum = $xml->POS_MATCHES->ROW['1']->RNUM;
            $equiryNumber = $xml->ENQUIRY_ID;

            DB::table('companies')
                ->where('id','=', $request->id)
                ->update(array(
                        'companyID' => $companyId
                    )
                );

            DB::table('companies')
                ->where('id','=', $request->id)
                ->update(array(
                        'RegNumber' => $companyRegNumber
                    )
                );

            DB::table('companies')
                ->where('id','=', $request->id)
                ->update(array(
                        'OldRegNumber' => $oldRegNumber
                    )
                );

            DB::table('companies')
                ->where('id','=', $request->id)
                ->update(array(
                        'companyName' => $companyName
                    )
                );

            DB::table('companies')
                ->where('id','=', $request->id)
                ->update(array(
                        'taxNumber' => $taxNumber
                    )
                );

            DB::table('companies')
                ->where('id','=', $request->id)
                ->update(array(
                        'vatNumber' => $vatNumber
                    )
                );

            DB::table('companies')
                ->where('id','=', $request->id)
                ->update(array(
                        'equiryID' => $equiryNumber
                    )
                );
*/

        }

        return View::make('compuscan.full-company-search')
            ->with('enquiry',$enquiry)
            ->with('companyID',$companyID)
            ->with('request',$request);
    }

    public function serverPossibleMatchResult($request)
    {
        return View::make('compuscan.possible-match-result')
            ->with('request',$request);
    }

    public function serverFullCompanySearch()
    {
        return View::make('compuscan.full-company-search');
    }

    public function handleFullCompanySearch()
    {
        $validator = Validator::make(Input::all(),
            [
                'companyName' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }


        $request = new Company;
        $request->companyName = Input::get('companyName');
        $request->RegNum1 = Input::get('RegNum1');
        $request->RegNum2 = Input::get('RegNum2');
        $request->RegNum3 = Input::get('RegNum3');
        $request->vatNumber = Input::get('vatNumber');
        $request->taxNumber = Input::get('taxNumber');

        if(Input::get('deedData')==1)
        {
           $request->deedData = 'Y';
        }
        else
        {
            $request->deedData = 'N';
        }

        if(Input::get('score')==1)
        {
            $request->score = 'Y';
        }
        else
        {
            $request->score = 'N';
        }

        if(Input::get('codix')==1)
        {
            $request->codix = 'Y';
        }
        else
        {
            $request->codix = 'N';
        }
        $request->equiryID = Input::get('equiryID');
        $request->companyID = Input::get('companyID');
        $request->save();

        $params = new StdClass();
        $params->request = new StdClass();
        $params->request->pUsrnme = "77802-1";
        $params->request->pPasswrd = "statusdev";
        $params->request->pOrigin = "StatusData";
        $params->request->pVersion = "1.0";
        $params->request->pOrigin_Version = "1.0";
        $params->request->pTransaction = "
           <Transactions>
               <Search_Criteria>
                    <Company_Name>Compuscan</Company_Name>
                    <Reg_Number1></Reg_Number1>
                    <Reg_Number2></Reg_Number2>
                    <Reg_Number3></Reg_Number3>
                    <Vat_Number></Vat_Number>
                    <Tax_Number></Tax_Number>
                    <Deeds_Data>Y</Deeds_Data>
                    <ResultType>XML</ResultType>
                    <Run_CompanyScore>Y</Run_CompanyScore>
                    <Run_Codix>N</Run_Codix>
                    <PosMatchEnq_Id>77422</PosMatchEnq_Id>
                    <CompanyId>10137109068108094178</CompanyId>
                </Search_Criteria>
            </Transactions>
        ";

        $options = array('trace' => 1, 'exceptions'  => 1);
        //Configure the WSDL location
        // echo "Configuring WSDL<br/>";
        $wsdl = "https://webservices-uat.compuscan.co.za/CompanySearchService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient'))
        {
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->CompanyFullSearch($params);

        $result=$response->TransReplyClass;

        if($result->transactionCompleted){
            $results = $response->TransReplyClass->retData;

            $xml = simplexml_load_string($results);

            return View::make('compuscan.full-company-search-results')
                ->with('xml',$xml);
        }
        else
        {
            if($response->TransReplyClass->errorCode == -101)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Not all variables are filled in.');
            }
            elseif($response->TransReplyClass->errorCode == -102)
            {
                return Redirect::back()->withInput()->with('view-error', '<i class="white fa fa-times"></i> <strong class="white">Oops!</strong> Invalid parameters.');
            }
        }

    }

    public function serverPreviousCompanySearch()
    {
        return View::make('compuscan.previous-company-search');
    }

    public function handlePreviousCompanySearch()
    {
        $validator = Validator::make(Input::all(),
            [
                'companyName' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }


        $request = new Company;
        $request->companyName = Input::get('companyName');
        $request->RegNum1 = Input::get('RegNum1');
        $request->RegNum2 = Input::get('RegNum2');
        $request->RegNum3 = Input::get('RegNum3');
        $request->vatNumber = Input::get('vatNumber');
        $request->taxNumber = Input::get('taxNumber');

        if(Input::get('deedData')==1)
        {
            $request->deedData = 'Y';
        }
        else
        {
            $request->deedData = 'N';
        }

        if(Input::get('score')==1)
        {
            $request->score = 'Y';
        }
        else
        {
            $request->score = 'N';
        }

        if(Input::get('codix')==1)
        {
            $request->codix = 'Y';
        }
        else
        {
            $request->codix = 'N';
        }
        $request->equiryID = Input::get('equiryID');
        $request->companyID = Input::get('companyID');
        $request->save();

        $params = new StdClass();
        $params->request = new StdClass();
        $params->request->pUsrnme = "77802-1";
        $params->request->pPasswrd = "statusdev";
        $params->request->pOrigin = "StatusData";
        $params->request->pVersion = "1.0";
        $params->request->pOrigin_Version = "1.0";
        $params->request->pTransaction = "
                <Transactions>
                    <Search_Criteria>
                        <Company_Name>$request->companyName</Company_Name>
                        <Reg_Number1>$request->RegNum1</Reg_Number1>
                        <Reg_Number2>$request->RegNum2</Reg_Number2>
                        <Reg_Number3>$request->RegNum3</Reg_Number3>
                        <Tax_Number>$request->vatNumber</Tax_Number>
                        <Vat_Number>$request->taxNumber</Vat_Number>
                        <Deeds_Data>Y</Deeds_Data>
                        <Run_CompanyScore>Y</Run_CompanyScore>
                        <Run_Codix>Y</Run_Codix>
                        <PosMatchEnq_Id>1307</PosMatchEnq_Id>
                        <CompanyId>1096531</CompanyId>
                        <ResultType>XML</ResultType>
                    </Search_Criteria>
                </Transactions>
        ";

        $options = array('trace' => 1, 'exceptions'  => 1);
        //Configure the WSDL location
        // echo "Configuring WSDL<br/>";
        $wsdl = "https://webservices-uat.compuscan.co.za/CompanySearchService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient'))
        {
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->CompanyEnqIdLookup($params);

        $result=$response->TransReplyClass;
        if($result->transactionCompleted){

            $results = $response->TransReplyClass->retData;
            $xml = simplexml_load_string($results);

            dd($xml->POS_MATCHES->ROW['1']);

        }
    }

    public function serverFullReport()
    {
        return View::make('compuscan.full-reports');
    }

    public function handleResearchedReport()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $request = new ResearchedReport;
        $request->clientName = Input::get('clientName');
        $request->ClientTel = Input::get('ClientTel');
        $request->clientEmail = Input::get('clientEmail');
        $request->companyName = Input::get('companyName');
        $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
        $request->debtorContacts = Input::get('debtorContacts');
        $request->DebtorEmail = Input::get('DebtorEmail');
        $request->refCompany1 = Input::get('refCompany1');
        $request->termRef1 = Input::get('termRef1');
        $request->creditLimitRef1 = Input::get('creditLimitRef1');
        $request->contact1 = Input::get('contact1');
        $request->contactPerson1 = Input::get('contactPerson1');
        $request->refCompany2 = Input::get('refCompany2');
        $request->termRef2 = Input::get('termRef2');
        $request->creditLimitRef2 = Input::get('creditLimitRef2');
        $request->contact2 = Input::get('contact2');
        $request->contactPerson2 = Input::get('contactPerson2');
        $request->refCompany3 = Input::get('refCompany3');
        $request->termRef3 = Input::get('termRef3');
        $request->creditLimitRef3 = Input::get('creditLimitRef3');
        $request->contact3 = Input::get('contact3');
        $request->contactPerson3 = Input::get('contactPerson3');
        $request->initials = Input::get('initials');
        $request->surname = Input::get('surname');
        $request->idNumber = Input::get('idNumber');
        $request->accountNumber = Input::get('accountNumber');
        $request->branchCode = Input::get('branchCode');
        $request->accountType = Input::get('accountType');
        $request->branchCode = Input::get('branchCode');
        $request->accountType = Input::get('accountType');
        $request->report = Input::get('report');

        if (Input::hasFile('creditApplication'))
        {
            $file = Input::file('creditApplication');
            $file->move('app/creditApplication/', $file->getClientOriginalName());
            $request->creditApplication = 'app/creditApplication/'.$file->getClientOriginalName();

        }

        $id = Auth::user()->id;
        $user = User::find($id);

        $request->save();

        $data = ['request' => $request, 'user' => $user];

        Mail::send('emails.researchedReport', $data, function($message) use ($request)
        {
            $message->to('pjacobs@compuscan.co.za','Pasha Jacobs')->bcc('rachael@mybusinessvault.co.za','Rachael Maphopha')->subject('Researched Report Request');
            $message->from('no-reply@prestige.co.za');
            $message->attach($request->creditApplication);

        });

        return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
    }

    public function handleFullReport()
    {
        $validator = Validator::make(Input::all(),
            [
                'companyName' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $request = new Company;
        $request->companyName = Input::get('companyName');
        $request->RegNum1 = Input::get('RegNum1');
        $request->RegNum2 = Input::get('RegNum2');
        $request->RegNum3 = Input::get('RegNum3');
        $request->vatNumber = Input::get('vatNumber');
        $request->taxNumber = Input::get('taxNumber');
        $request->deedData = Input::get('deedsData');
        $request->score = Input::get('score');
        $request->codix = Input::get('codix');
        $request->postMatchEnquiry = Input::get('postMatchEnquiry');
        $request->companyId = Input::get('companyId');
        $request->save();

        $deedData = '';
        $score = '';
        $codix = '';

        if(Input::get('deedsData')==1)
        {
            $deedData = 'Y';
        }

        if(Input::get('score')==1)
        {
            $score = 'Y';
        }

        if(Input::get('codix')==1)
        {
            $codix = 'Y';
        }


        $params = new StdClass();
        $params->request = new StdClass();
        $params->request->pUsrnme = "77802-1";
        $params->request->pPasswrd = "statusdev";
        $params->request->pOrigin = "StatusData";
        $params->request->pVersion = "1.0";
        $params->request->pOrigin_Version = "1.0";
        $params->request->pTransaction = "
                <Transactions>
                    <Search_Criteria>
                        <Company_Name>$request->companyName</Company_Name>
                        <Reg_Number1>$request->RegNum1</Reg_Number1>
                        <Reg_Number2>$request->RegNum2</Reg_Number2>
                        <Reg_Number3>$request->RegNum3</Reg_Number3>
                        <Vat_Number>$request->vatNumber</Vat_Number>
                        <Tax_Number>$request->taxNumber</Tax_Number>
                        <Deeds_Data>$deedData</Deeds_Data>
                        <ResultType>XML</ResultType>
                        <Run_CompanyScore>$score</Run_CompanyScore>
                        <Run_Codix>$codix</Run_Codix>
                        <PosMatchEnq_Id>$request->postMatchEnquiry</PosMatchEnq_Id>
                        <CompanyId>$request->companyId</CompanyId>
                    </Search_Criteria>
                </Transactions>
        ";

        $options = array('trace' => 1, 'exceptions'  => 1);

        $wsdl = "https://webservices-uat.compuscan.co.za/CompanySearchService?wsdl";

        //Check if the PHP-SOAP module is installed
        if (!class_exists('SoapClient'))
        {
            die("Missing PHP-Soap module.");
        }
        //Create the webservice connection

        $webservice = new SoapClient($wsdl,$options);
        $response = $webservice->CompanyFullSearch($params);

        $result=$response->TransReplyClass;
        if($result->transactionCompleted){

            $results = $response->TransReplyClass->retData;
            $xml = simplexml_load_string($results);

            dd($xml);

        }
    }

    public function serverTransunionBusinessBankCode()
    {
        return View::make('credit-network.transunion-bank-code');
    }

    public function handleTransunionBusinessBankCode()
    {
        $validator = Validator::make(Input::all(),
            [
                'accountHolder' => 'required',
                'idNumber' => 'required',
                'bank' => 'required',
                'branch' => 'required',
                'branchName' => 'required',
                'accountNumber' => 'required',
                'accountType' => 'required',
                'amount' => 'required',
                'terms' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        //$email = 'koketso.maphopha@gmail.com';
        $accountHolder = Input::get('accountHolder');
        $idNumber = Input::get('idNumber');
        $bank = Input::get('bank');
        $country = Input::get('country');
        $branch = Input::get('branch');
        $accountNumber = Input::get('accountNumber');
        $accountType = Input::get('accountType');
        $amount = Input::get('amount');
        $terms = Input::get('terms');
        $branchName = Input::get('branchName');

        $url = 'https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$accountHolder.'&regNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branch.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=5022';

        try {
            $xml = simplexml_load_file($url);

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Transunion 24 Hour Bank Code')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Transunion 24 Hour Bank Code';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Transunion 24 Hour Bank Code')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->TU_bank_code
                        )
                    );
            }

        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial Bank Code Report will be sent to your email in the next 24 hours');
        }

        return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial Report will be sent to your email in the next 24 hours');
    }

    public function serverBusinessBankCode()
    {
        return View::make('credit-network.business-bank-code');
    }

    public function handleBusinessBankCode()
    {
        //From Compuscan
        $validator = Validator::make(Input::all(),
            [
                'accountHolder' => 'required',
                'idNumber' => 'required',
                'bank' => 'required',
                'country' => 'required',
                'branch' => 'required',
                'branchName' => 'required',
                'accountNumber' => 'required',
                'accountType' => 'required',
                'amount' => 'required',
                'terms' => 'required',
                'businessName' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        //$email = 'koketso.maphopha@gmail.com';
        $accountHolder = Input::get('accountHolder');
        $idNumber = Input::get('idNumber');
        $bank = Input::get('bank');
        $country = Input::get('country');
        $branch = Input::get('branch');
        $accountNumber = Input::get('accountNumber');
        $accountType = Input::get('accountType');
        $amount = Input::get('amount');
        $terms = Input::get('terms');
        $branchName = Input::get('branchName');
        $businessName = Input::get('businessName');

        $url = 'https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&regNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branch.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=NNB';

        try {
            $xml = simplexml_load_file($url);

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Compuscan 24 Hour Bank Code')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Compuscan 24 Hour Bank Code';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Compuscan 24 Hour Bank Code')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->CS_bank_code
                        )
                    );
            }


        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Bank Code Report will be sent to your email in the next 24 hours');
        }

        return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email in the next 24 hours');

    }

    public function serverIndividualBankCode()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $compuscanBankCodePrincipal = $prices->compuscan_24hr_principal_bank_code;

        return View::make('credit-network.individual-bank-code')
            ->with('compuscanBankCodePrincipal',$compuscanBankCodePrincipal)
            ->with('user',$user);
    }

    public function handleIndividualBankCode()
    {
        //From Compuscan
        $validator = Validator::make(Input::all(),
            [
                'accountHolder' => 'required',
                'idNumber' => 'required',
                'bank' => 'required',
                'branchName' => 'required',
                'branchCode' => 'required',
                'accountNumber' => 'required',
                'accountType' => 'required',
                'amount' => 'required',
                'terms' => 'required',
                'country' => 'required',
                'surname' => 'required',
                'forename1' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        //$email = 'koketso.maphopha@gmail.com';
        $accountHolder = Input::get('accountHolder');
        $idNumber = Input::get('idNumber');
        $bank = Input::get('bank');
        $branchName = Input::get('branchName');
        $branchCode = Input::get('branchCode');
        $accountNumber = Input::get('accountNumber');
        $accountType = Input::get('accountType');
        $amount = Input::get('amount');
        $terms = Input::get('terms');
        $country = Input::get('country');
        $surname = Input::get('surname');
        $forename1 = Input::get('forename1');

        if(Input::has('forename2'))
        {
            $forename2 = Input::get('forename2');
        }
        else
        {
            $forename2 = '';
        }

        if(Input::has('forename3'))
        {
            $forename3 = Input::get('forename3');
        }
        else
        {
            $forename3 = '';
        }

        $url = 'https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&surname='.$surname.'&firstname1='.$forename1.'&firstname2='.$forename2.'&firstname3='.$forename3.'&idNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branchCode.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=ANN';

        try {
            $xml = simplexml_load_file($url);

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Compuscan 24 Principal Bank Code')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Compuscan 24 Principal Bank Code';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Compuscan 24 Principal Bank Code')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->CS_principal_bank_code
                        )
                    );
            }

        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Individual Bank Code Report will be sent within 24 hours');
        }

        return Redirect::back()->with('view-success', 'SUCCESS: Your Individual Bank Code Report will be sent within 24 hours');

    }

    public function serverIndividualReport()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $compuscanPrincipalPrice = $prices->compuscan_principal_on_file;
        $xdsPrincipalPrice = $prices->xds_principal_on_file;


        return View::make('credit-network.individual-report')
            ->with('xdsPrincipalPrice',$xdsPrincipalPrice)
            ->with('compuscanPrincipalPrice',$compuscanPrincipalPrice)
            ->with('user',$user);
    }

    public function handleIndividualReport()
    {
        $validator = Validator::make(Input::all(),
            [
                'surname' => 'required',
                'forename1' => 'required',
                'idNumber' => 'required',
                'gender' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        //$email = Auth::user()->email;
        $surname = Input::get('surname'); //Goofy
        $forename1 = Input::get('forename1'); //Just

        /*if(Input::has('forename2'))
        {
            $forename2 = Input::get('forename2');
        }
        else
        {
            $forename2 = '';
        }

        if(Input::has('forename3'))
        {
            $forename3 = Input::get('forename3');
        }
        else
        {
            $forename3 = '';
        }*/

        $idNumber = Input::get('idNumber'); //7408285107080
        $dateOfBirth = '19'.substr($idNumber, 0, 6);

        $year = substr($dateOfBirth, 0, 4);
        $month = substr($dateOfBirth, 4, 2);
        $day = substr($dateOfBirth, 6, 2);

        $gender = Input::get('gender');

        if(Input::get('response')=='Compuscan') {

            $url = "https://webservices.compuscan.co.za/ConsumerCreditReportService?wsdl";

            $parameters = array("pUsername" => "28822-1",
                "pPassword" => '$t@tu$',
                "pMyOrigin" => "StatusData",
                "pVersion" => "1.0",
                "pInputType" => "xml",
                "pTransactionData" => base64_encode('
                <transactions>
                    <fullEnquiry> 
                    <Identity_number>' . $idNumber . '</Identity_number> 
                    <Surname>' . $surname . '</Surname> 
                    <Forename>' . $forename1 . '</Forename> 
                    <Enq_Purpose>12</Enq_Purpose> 
                    <ResultType>PDF</ResultType>
                    </fullEnquiry> 
                </transactions>'));


            $client = new SoapClient($url);
            $value = $client->doCCRFullEnquiry($parameters);

            if (!$value->TransactionReplyClass->transactionCompleted) {
                return Redirect::back()->with('view-error', $value->TransactionReplyClass->errorDescription);
            }

            $value2 = $value->TransactionReplyClass->returnData;

            $loadResult = simplexml_load_string($value2);

            $value3 = $loadResult->result->returnData;
            $decoded = base64_decode($value3);

            $file = 'Compuscan Consumer Credit Report.pdf';
            file_put_contents($file, $decoded);

            if (file_exists($file)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . basename($file) . '"');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                readfile($file);
                exit;
            }
        }
        else{

            //assign values to variables
            $strUser = "Statusdata_live";
            $strPwd = "uarivx";
            $dateOfBirth = $year.'-'.$month.'-'.$day;

            $client = new SoapClient ("https://www.web.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
            $parameters = array ("strUser"=>$strUser, "strPwd"=>$strPwd);
            $configQry = $client->Login ($parameters);
            //remove special characters
            $ticket = preg_replace ("~/~", "\\\\", $configQry->LoginResult);

            $ConnectTicket = $ticket;
            $EnquiryReason = "";
            $ProductId = "15";
            $IdNumber = $idNumber;
            $PassportNo = "";
            $FirstName = $forename1;
            $Surname = $surname;
            $BirthDate = $dateOfBirth;
            $YourReference = "";
            $VoucherCode = "";
            $client = new SoapClient ("https://www.web.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
            $parameters = array (
                "ConnectTicket"=>$ConnectTicket,"EnquiryReason"=>$EnquiryReason,"ProductId"=>$ProductId,"IdNumber"=>$IdNumber,"PassportNo"=>$PassportNo,"FirstName"=>$FirstName,"Surname"=>$Surname,"BirthDate"=>$BirthDate,"YourReference"=>$YourReference,
                "VoucherCode"=>$VoucherCode);
            $configQry = $client->ConnectConsumerMatch ($parameters);

            $result = $configQry->ConnectConsumerMatchResult;
            $loadResult = simplexml_load_string($result);
            $enquiryID = $loadResult->ConsumerDetails->EnquiryID;
            $enquiryResultID = $loadResult->ConsumerDetails->EnquiryResultID;
            $EnquiryID = $enquiryID;
            $EnquiryResultID = $enquiryResultID;
            $ProductID='15';
            $BonusXML ='';
            $client = new SoapClient ("https://www.web.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
            $parameters=array("ConnectTicket"=>$ConnectTicket,'EnquiryID'=>$EnquiryID,'EnquiryResultID'=>$EnquiryResultID,'ProductID'=>$ProductID,'EnquiryID'=>$EnquiryID,'BonusXML'=>$BonusXML);
            $configQry2 = $client->ConnectGetResultBinary($parameters);

            //$result2 = $configQry2->ConnectGetResultResult;
            //$loadResult2 = simplexml_load_string($result2);

            $pdfFile = $configQry2->ConnectGetResultBinaryResult;

            $file = 'XDS Consumer Credit Report.pdf';
            file_put_contents($file, $pdfFile);

            if (file_exists($file)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="'.basename($file).'"');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                readfile($file);
                exit;
            }
        }

        /*
        $url = 'https://cir.credit-network.biz/api/IndividualEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&surname='.$surname.'&forename1='.$forename1.'&forename2='.$forename2.'&forename3='.$forename3.'&idNumber='.$idNumber.'&dateOfBirth='.$dateOfBirth.'&gender='.$gender.'&reportCode=CCR';

        try {
            $xml = file_get_contents($url);

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Compuscan Principal Report')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Compuscan Principal Report';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Compuscan Principal Report')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->CS_principal_report
                        )
                    );
            }

        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Individual Credit Report will be sent to your email shortly');
        }*/

        return Redirect::back()->with('view-success', 'SUCCESS: Your Individual Credit Report has successfully retrieved.');
    }

    public function serverCompuscanReports()
    {
        return View::make('compuscan.compuscan-reports');
    }

    public function serverBusinessCommercialReport()
    {
        return View::make('credit-network.business-commercial-report');
    }

    public function handleBusinessCommercialReport()
    {
        $validator = Validator::make(Input::all(),
            [
                'businessName' => 'required',
                'registrationNumber' => 'required',
                'TAXNumber' => 'required',
                'VATNumber' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        //$email = 'koketso.maphopha@gmail.com';
        $businessName = Input::get('businessName');
        $registrationNumber = Input::get('registrationNumber');
        $TAXNumber = Input::get('TAXNumber');
        $VATNumber = Input::get('VATNumber');

        $url = 'https://cir.credit-network.biz/api/CommercialEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&registrationNumber='.$registrationNumber.'&VATnumber='.$VATNumber.'&TAXnumber='.$TAXNumber.'&reportCode=NN';

        try {
            $xml = simplexml_load_file($url);
            $transaction = new Transaction;
            $transaction->user = Auth::user()->name;
            $transaction->company = Auth::user()->companyName;
            $transaction->product = 'On file Report';
            $transaction->save();
        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email shortly');
            }


        return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email shortly');
    }

    public function serverCreditCheck2()
    {
        return View::make('credit-network.credit-check2');
    }

    public function handleCreditCheck2()
    {
        $validator = Validator::make(Input::all(),
        [
            'businessName' => 'required',
            'regNumber' => 'required'
        ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        $businessName = Input::get('businessName');
        $registrationNumber = Input::get('regNumber');

        $url = 'https://cir.credit-network.biz/api/CommercialEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&registrationNumber='.$registrationNumber.'&VATnumber=&TAXnumber=&reportCode=NN';

        try {
            $xml = simplexml_load_file($url);

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Compuscan On file Report')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Compuscan On file Report';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Compuscan On file Report')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->CS_OnFile_Report
                        )
                    );
            }


        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email shortly');
        }
    }

    public function serverCreditCheck2BCD()
    {
        return View::make('credit-network.credit-check2BCD');
    }

    public function handleCreditCheck2BCD()
    {
        $validator = Validator::make(Input::all(),
            [
                'businessName' => 'required',
                'regNumber' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        $businessName = Input::get('businessName');
        $registrationNumber = Input::get('regNumber');

        $url = 'https://cir.credit-network.biz/api/CommercialEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&registrationNumber='.$registrationNumber.'&VATnumber=&TAXnumber=&reportCode=TU';
        try {
            $xml = simplexml_load_file($url);
        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email shortly');
        }
    }

    public function serverDeeds()
    {
        return View::make('pages.deeds');
    }

    public function serverIndividualDeeds()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $transunionIndividualDeeds = $prices->transunion_principal_deeds;

        return View::make('credit-network.individual-deeds')
            ->with('transunionIndividualDeeds',$transunionIndividualDeeds)
            ->with('user',$user);
    }

    public function handleIndividualDeeds()
    {
        $validator = Validator::make(Input::all(),
            [
                'surname' => 'required',
                'idNumber' => 'required',
                'forename1' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        $surname = Input::get('surname');
        $idNumber = Input::get('idNumber');
        $forename1 = Input::get('forename1');

        if(Input::has('forename2'))
        {
            $forename2 = Input::get('forename2');
        }
        else
        {
            $forename2 = '';
        }

        if(Input::has('forename3'))
        {
            $forename3 = Input::get('forename3');
        }
        else
        {
            $forename3 = '';
        }

        $url = 'https://cir.credit-network.biz/api/IndividualEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&surname='.$surname.'&forename1='.$forename1.'&forename2='.$forename2.'&forename3='.$forename3.'&idNumber='.$idNumber.'&dateOfBirth=19911025&gender=F&reportCode=5455';

        try {
            $xml = file_get_contents($url);

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Transunion Principal Deeds')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Transunion Principal Deeds';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Transunion Principal Deeds')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->TU_Principal_Deeds
                        )
                    );
            }


            return Redirect::back()->with('view-success', 'SUCCESS: Your Deeds Report will be sent to your email shortly');
        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Deeds Report will be sent to your email shortly');
        }
    }

    public function serverBusinessSummary()
    {
        return View::make('credit-network.business-summary');
    }

    public function handleBusinessSummary()
    {
        $validator = Validator::make(Input::all(),
            [
                'businessName' => 'required',
                'regNumber' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        $businessName = Input::get('businessName');
        $registrationNumber = Input::get('regNumber');

        $url = 'https://cir.credit-network.biz/api/CommercialEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&registrationNumber='.$registrationNumber.'&VATnumber=&TAXnumber=&reportCode=5142';

        try {
            $xml = simplexml_load_file($url);
        } catch (Exception $e) {

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Transunion On-File Report')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Transunion On-File Report';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Transunion On-File Report')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->TU_OnFile_Report
                        )
                    );
            }

            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email shortly');
        }
    }

    public function serverFullBankCode()
    {
        return View::make('credit-network.full-bank-code');
    }

    public function handleFullBankCode()
    {
        $validator = Validator::make(Input::all(),
            [
                'accountHolder' => 'required',
                'idNumber' => 'required',
                'bank' => 'required',
                'branch' => 'required',
                'branchName' => 'required',
                'accountNumber' => 'required',
                'accountType' => 'required',
                'amount' => 'required',
                'terms' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        //$email = 'koketso.maphopha@gmail.com';
        $accountHolder = Input::get('accountHolder');
        $idNumber = Input::get('idNumber');
        $bank = Input::get('bank');
        $branch = Input::get('branch');
        $accountNumber = Input::get('accountNumber');
        $accountType = Input::get('accountType');
        $amount = Input::get('amount');
        $terms = Input::get('terms');
        $branchName = Input::get('branchName');

        $url = 'https://cir.credit-network.biz/api/CommercialEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&accountholder='.$accountHolder.'&regORidNumber='.$idNumber.'&spesificBankName='.$bank.'&bankCountry=ZAR&branchName='.$branchName.'&branchCode='.$branch.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=5022';
        //$xml = simplexml_load_file($url);

        try {
            $xml = simplexml_load_file($url);
            $transaction = new Transaction;
            $transaction->user = Auth::user()->name;
            $transaction->company = Auth::user()->companyName;
            $transaction->product = '24 Hour Bank Code';
            $transaction->save();
        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Bank Code Report will be sent to your email in the next 24 hours');
        }

        return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email in the next 24 hours');

}

    public function serverDebtorRanking()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        return View::make('pages.debtor-ranking-and-monitoring')
            ->with('user',$user);
    }

    public function serverViewUsers($companyName)
    {
        $users = DB::table('users')
            ->where('companyName','=',$companyName)
            ->orderBy('name','asc')
            ->paginate(10);

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $company = $companyName;

        return View::make('management.view-users')
            ->with('user',$user)
            ->with('users',$users)
            ->with('company',$company);
    }

    public function serverDMSupport()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.DMS-support')
            ->with('user',$user);
    }

    public function handleDMSSupport()
    {
        $validator = Validator::make(Input::all(), static::$rules2);

        if($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', '
        Oops! There was a problem with your entry, please try again.');
        }

        $id = Auth::user()->id;
        $currentUser = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $query = new Query;
        $query->query = Input::get('query');
        $query->email = $currentUser->email;
        $query->name = $currentUser->name;
        $query->save();

        $data = ['query' => $query];

        Mail::send('emails.query', $data, function($message)
        {
            $message->to('Admin1@DMSOL.co.za', 'Admin')->bcc('rachael@statusdata.co.za','Tech')->subject('Debtol Management Solutions Support Form');
            $message->from('Admin2@prestigeadvantage.co.za');
        });

        return Redirect::to('home')->with('view-success',' Thank you! Our Debtcol Management Solutions support team will get back to you as soon as possible.');

    }

    public function serverPrestigeSupport()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.prestige-support')
            ->with('user',$user);
    }

    public function handlePrestigeSupport()
    {
        $validator = Validator::make(Input::all(), static::$rules2);

        if($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator)->with('view-error', 'Oops! There was a problem with your entry, please try again.');
        }

        $id = Auth::user()->id;
        $currentUser = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $query = new Query;
        $query->query = Input::get('query');
        $query->name = $currentUser->name;
        $query->email = $currentUser->email;

        if (Input::hasFile('screenshot'))
        {
            $file = Input::file('screenshot');
            $file->move('img/support/', $file->getClientOriginalName());
            $query->screenshot = 'img/support/'.$file->getClientOriginalName();
        }

        $query->save();

        $data = ['query' => $query];

        Mail::send('emails.query', $data, function($message) use($query)
        {
            $message->to('Admin1@prestigeAdvantage.co.za', 'Admin')->to('Admin2@prestigeAdvantage.co.za','Admin2')->bcc('rachael@statusdata.co.za','Rachael')->subject('Prestige Advantage Support Form');
            $message->from('webmaster@prestigedata.co.za');
            $message->attach($query->screenshot);

        });

        return Redirect::to('home')->with('view-success',' Thank you! Our Prestige Advantage support team will get back to you as soon as possible.');

    }

    public function serverViewTransations($id)
    {
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $transactions = DB::table('transactions')
            ->where('user','=',$user->name)
            ->paginate(10);

        return View::make('management.user-transactions')
            ->with('user',$user)
            ->with('transactions',$transactions);
    }

    public function excel($company) {

        $transactions = DB::table('transactions')
            ->where('company','=',$company)
            ->get();

        $transactionsArray = [];

        $transactionsArray[] = ['id','User','Report','Created At','Price'];

        foreach ($transactions as $transaction) {
            //array_push($transactionsArray,$transaction);
            $transactionsArray[] = $transaction->toArray();
        }


        Excel::create('transactions', function($excel) use ($transactionsArray) {

            // Set the spreadsheet title, creator, and description
            $excel->setTitle('Transactions');
            $excel->setCreator('Rachael')->setCompany('Prestige Credit');
            $excel->setDescription('Transaction List');

            // Build the spreadsheet, passing in the payments array
            $excel->sheet('sheet1', function($sheet) use ($transactionsArray) {
                $sheet->fromArray($transactionsArray, null, 'A1', false, false);
            });

        })->download('xlsx');
    }

    public function serverCompuscanExpressBankCode()
    {
        return View::make('credit-network.compuscan-express-bank-code');
    }

    public function handleCompuscanExpressBankCode()
    {
        $validator = Validator::make(Input::all(),
            [
                'accountHolder' => 'required',
                'idNumber' => 'required',
                'bank' => 'required',
                'country' => 'required',
                'branch' => 'required',
                'branchName' => 'required',
                'accountNumber' => 'required',
                'accountType' => 'required',
                'amount' => 'required',
                'terms' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        //$email = 'koketso.maphopha@gmail.com';
        $accountHolder = Input::get('accountHolder');
        $idNumber = Input::get('idNumber');
        $bank = Input::get('bank');
        $country = Input::get('country');
        $branch = Input::get('branch');
        $accountNumber = Input::get('accountNumber');
        $accountType = Input::get('accountType');
        $amount = Input::get('amount');
        $terms = Input::get('terms');
        $branchName = Input::get('branchName');
        $businessName = Input::get('businessName');

        $url = 'https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&regNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branch.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=NNBXS';

        try {
            $xml = simplexml_load_file($url);

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Compuscan 4 Hour Bank Code Express')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Compuscan 4 Hour Bank Code Express';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Compuscan 4 Hour Bank Code Express')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->CS_bank_code_express
                        )
                    );
            }


        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial Express Bank Code Report will be sent to your email in the next 4 hours');
        }

        return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial Express Report will be sent to your email in the next 4 hours');

    }

    public function serverCompuscanPrincipalExpressBankCode()
    {
        return View::make('credit-network.compuscan-principal-express-bank-code');
    }

    public function handleCompuscanPrincipalExressBankCode()
    {
        $validator = Validator::make(Input::all(),
            [
                'accountHolder' => 'required',
                'idNumber' => 'required',
                'bank' => 'required',
                'branchName' => 'required',
                'branchCode' => 'required',
                'accountNumber' => 'required',
                'accountType' => 'required',
                'amount' => 'required',
                'terms' => 'required',
                'country' => 'required',
                'surname' => 'required',
                'forename1' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        //$email = 'koketso.maphopha@gmail.com';
        $accountHolder = Input::get('accountHolder');
        $idNumber = Input::get('idNumber');
        $bank = Input::get('bank');
        $branchName = Input::get('branchName');
        $branchCode = Input::get('branchCode');
        $accountNumber = Input::get('accountNumber');
        $accountType = Input::get('accountType');
        $amount = Input::get('amount');
        $terms = Input::get('terms');
        $country = Input::get('country');
        $surname = Input::get('surname');
        $forename1 = Input::get('forename1');

        if(Input::has('forename2'))
        {
            $forename2 = Input::get('forename2');
        }
        else
        {
            $forename2 = '';
        }

        if(Input::has('forename3'))
        {
            $forename3 = Input::get('forename3');
        }
        else
        {
            $forename3 = '';
        }


        $url = 'https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&surname='.$surname.'&firstname1='.$forename1.'&firstname2='.$forename2.'&firstname3='.$forename3.'&idNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branchCode.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=ANNXS';

        try {
            $xml = simplexml_load_file($url);
            $transaction = new Transaction;
            $transaction->user = Auth::user()->name;
            $transaction->company = Auth::user()->companyName;
            $transaction->product = '24 Principal Bank Code';
            $transaction->save();



        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Express Individual Bank Code Report will be sent within 4 hours');
        }

        return Redirect::back()->with('view-success', 'SUCCESS: Your Express Individual Bank Code Report will be sent within 4 hours');

    }

    public function serverTransunionPrincipalBankCode()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        return View::make('credit-network.transunion-principal-bank-code')
            ->with('user',$user);
    }

    public function handleTransunionPrincipalBankCode()
    {
       //From Transunion
        $validator = Validator::make(Input::all(),
            [
                'surname' => 'required',
                'firstname1' => 'required',
                'idNumber' => 'required',
                'bank' => 'required',
                'branchName' => 'required',
                'branchCode' => 'required',
                'accountNumber' => 'required',
                'accountType' => 'required',
                'amount' => 'required',
                'terms' => 'required',
                'country' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        $firstname1 = Input::get('$firstname1');

        if(Input::has('firstname2'))
        {
            $firstname2 = Input::get('firstname2');
        }
        else
        {
            $firstname2 = '';
        }

        if(Input::has('firstname3'))
        {
            $firstname3 = Input::get('firstname3');
        }
        else
        {
            $firstname3 = '';
        }
        $surname = Input::get('surname');
        $idNumber = Input::get('idNumber');
        $bank = Input::get('bank');
        $branchName = Input::get('branchName');
        $branchCode = Input::get('branchCode');
        $accountNumber = Input::get('accountNumber');
        $accountType = Input::get('accountType');
        $amount = Input::get('amount');
        $terms = Input::get('terms');
        $country = Input::get('country');
        $accountHolder = Input::get('$accountHolder');

        $url = ' https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&surname='.$surname.'&firstname1='.$firstname1.'&firstname2='.$firstname2.'&firstname3='.$firstname3.'&idNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branchCode.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=5022';

        //$xml = simplexml_load_file($url);
        try {
            $xml = simplexml_load_file($url);
            $transaction = new Transaction;
            $transaction->user = Auth::user()->name;
            $transaction->company = Auth::user()->companyName;
            $transaction->product = '24 Principal Bank Code';
            $transaction->save();
        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Principal Bank Code Report will be sent within 24 hours');
        }

        return Redirect::back()->with('view-success', 'SUCCESS: Your Principal Bank Code Report will be sent within 24 hours');

    }

    public function serverStatusDataResearchedReport()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.status-researched-report')
            ->with('user',$user);
    }

    public function handleStatusResearchedReport()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $request = new ResearchedReport;
        $request->clientName = Input::get('clientName');
        $request->ClientTel = Input::get('ClientTel');
        $request->clientEmail = Input::get('clientEmail');
        $request->companyName = Input::get('companyName');
        $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
        $request->debtorContacts = Input::get('debtorContacts');
        $request->DebtorEmail = Input::get('DebtorEmail');
        $request->refCompany1 = Input::get('refCompany1');
        $request->termRef1 = Input::get('termRef1');
        $request->creditLimitRef1 = Input::get('creditLimitRef1');
        $request->contact1 = Input::get('contact1');
        $request->contactPerson1 = Input::get('contactPerson1');
        $request->refCompany2 = Input::get('refCompany2');
        $request->termRef2 = Input::get('termRef2');
        $request->creditLimitRef2 = Input::get('creditLimitRef2');
        $request->contact2 = Input::get('contact2');
        $request->contactPerson2 = Input::get('contactPerson2');
        $request->refCompany3 = Input::get('refCompany3');
        $request->termRef3 = Input::get('termRef3');
        $request->creditLimitRef3 = Input::get('creditLimitRef3');
        $request->contact3 = Input::get('contact3');
        $request->contactPerson3 = Input::get('contactPerson3');
        $request->initials = Input::get('initials');
        $request->surname = Input::get('surname');
        $request->idNumber = Input::get('idNumber');
        $request->accountNumber = Input::get('accountNumber');
        $request->branchCode = Input::get('branchCode');
        $request->accountType = Input::get('accountType');
        $request->branchCode = Input::get('branchCode');
        $request->accountType = Input::get('accountType');
        $request->report = Input::get('report');

        if (Input::hasFile('creditApplication'))
        {
            $file = Input::file('creditApplication');
            $file->move('app/creditApplication/', $file->getClientOriginalName());
            $request->creditApplication = 'app/creditApplication/'.$file->getClientOriginalName();

        }

        $id = Auth::user()->id;
        $user = User::find($id);

        $request->save();

        $data = ['request' => $request, 'user' => $user];

        Mail::send('emails.researchedReport', $data, function($message) use ($request)
        {
            $message->to('sgilmore@statusdata.co.za','Stephen Gilmore')->to('stephen@collectionsonline.co.za','Stephen Gilmore')->cc('rachael@mybusinessvault.co.za','Rachael Maphopha')->subject('Researched Report Request');
            $message->from('no-reply@prestige.co.za');
            $message->attach($request->creditApplication);

        });

        return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Status Data');
    }

    public function serverTransunionResearchedReport()
    {
        return View::make('pages.transunion-researched-report');
    }

    public function handleTransunionResearchedReport()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $request = new ResearchedReport;
        $request->clientName = Input::get('clientName');
        $request->ClientTel = Input::get('ClientTel');
        $request->clientEmail = Input::get('clientEmail');
        $request->companyName = Input::get('companyName');
        $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
        $request->debtorContacts = Input::get('debtorContacts');
        $request->DebtorEmail = Input::get('DebtorEmail');
        $request->refCompany1 = Input::get('refCompany1');
        $request->termRef1 = Input::get('termRef1');
        $request->creditLimitRef1 = Input::get('creditLimitRef1');
        $request->contact1 = Input::get('contact1');
        $request->contactPerson1 = Input::get('contactPerson1');
        $request->refCompany2 = Input::get('refCompany2');
        $request->termRef2 = Input::get('termRef2');
        $request->creditLimitRef2 = Input::get('creditLimitRef2');
        $request->contact2 = Input::get('contact2');
        $request->contactPerson2 = Input::get('contactPerson2');
        $request->refCompany3 = Input::get('refCompany3');
        $request->termRef3 = Input::get('termRef3');
        $request->creditLimitRef3 = Input::get('creditLimitRef3');
        $request->contact3 = Input::get('contact3');
        $request->contactPerson3 = Input::get('contactPerson3');
        $request->initials = Input::get('initials');
        $request->surname = Input::get('surname');
        $request->idNumber = Input::get('idNumber');
        $request->accountNumber = Input::get('accountNumber');
        $request->branchCode = Input::get('branchCode');
        $request->accountType = Input::get('accountType');
        $request->branchCode = Input::get('branchCode');
        $request->accountType = Input::get('accountType');
        $request->report = Input::get('report');

        if (Input::hasFile('creditApplication'))
        {
            $file = Input::file('creditApplication');
            $file->move('app/creditApplication/', $file->getClientOriginalName());
            $request->creditApplication = 'app/creditApplication/'.$file->getClientOriginalName();

        }

        $id = Auth::user()->id;
        $user = User::find($id);

        $request->save();

        $data = ['request' => $request, 'user' => $user];

        Mail::send('emails.researchedReport', $data, function($message) use ($request)
        {
            $message->to('sgilmore@statusdata.co.za','Stephen Gilmore')->to('stephen@collectionsonline.co.za','Stephen Gilmore')->bcc('rachael@mybusinessvault.co.za','Rachael Maphopha')->subject('Researched Report Request');
            $message->from('no-reply@prestige.co.za');
            $message->attach($request->creditApplication);

        });

        return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
    }


    public function serverViewCompanyUsageLog($company)
    {
        $transactions = DB::table('transactions')
            ->where('company','=',$company)
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('management.view-company-usage-log')
            ->with('user',$user)
            ->with('company',$company)
            ->with('transactions',$transactions);
    }

    public function serverCompanyDeeds()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $compuscanCompanyDeeds = $prices->compuscan_company_deeds;

        return View::make('credit-network.compuscan-company-deeds')
            ->with('compuscanCompanyDeeds',$compuscanCompanyDeeds)
            ->with('user',$user);
    }

    public function handleCompanyDeeds()
    {
        $validator = Validator::make(Input::all(),
            [
                'businessName' => 'required',
                'regNumber' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        $businessName = Input::get('businessName');
        $registrationNumber = Input::get('regNumber');

        $url = 'https://cir.credit-network.biz/api/CommercialEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&registrationNumber='.$registrationNumber.'&VATnumber=&TAXnumber=&reportCode=NND1';

        try {
            $xml = simplexml_load_file($url);

            $transaction = new Transaction;
            $transaction->user = Auth::user()->name;
            $transaction->company = Auth::user()->companyName;
            $transaction->product = 'Compuscan Company Deeds Report';
            $transaction->save();

        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Company Deeds Report will be sent to your email shortly');
        }
    }

    public function serverBanner()
    {
        $image2 = DB::table('banner')
            ->where('id','=',2)
            ->first();
        $image2 = $image2->image;

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.banner')
            ->with('user',$user)
            ->with('image2',$image2);
    }

    public function serverBannerImage()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.banner-image')
            ->with('user',$user);
    }


    public function handleBannerPreview()
    {
        if (Input::hasFile('image'))
        {
            $file = Input::file('image');
            $file->move('img/', $file->getClientOriginalName());

            DB::table('banner')
                ->where('id','=', 2)
                ->update(array(
                        'image' => '/img/'.$file->getClientOriginalName()
                    )
                );

            $image2 = DB::table('banner')
                ->where('id','=',2)
                ->first();
            $image2 = $image2->image;

            return Redirect::to('banner')
                ->with('image2',$image2);

        }
    }

    public function handleBanner()
    {
        $images = DB::table('banner')
            ->get();

        $image2 = DB::table('banner')
            ->where('id','=',2)
            ->first();
        $image2 = $image2->image;

        DB::table('banner')
            ->where('id','=', 1)
            ->update(array(
                    'image' => $image2
                )
            );

        return Redirect::back()->with('view-success', 'SUCCESS: Main Banner image has been changed');

    }

    public function serverFAQs()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        return View::make('pages.FAQs')
            ->with('user',$user);
    }

    public function serverNewCompany()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        return View::make('management.new-company')
            ->with('user',$user);
    }

    public function handleNewCompany()
    {
        $validator = Validator::make(Input::all(),
            [
                'companyName' => 'required',
                'address' => 'required',
                'contact_person' => 'required',
                'email' => 'required',
                'telephone' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'Some information may be missing or incorrectly provided, please review below')->withInput()->withErrors($validator);
        }

        $company = new Company;
        $company->companyName = Input::get('companyName');
        $company->address = Input::get('address');

        if(Input::has('checkBox')) {
            $company->postal_address = Input::get('address');
        }
        else {
            $company->postal_address = Input::get('postal_address');
        }

        $company->contact_person = Input::get('contact_person');
        $company->email = Input::get('email');
        $company->VATNumber = Input::get('VATNumber');
        $company->registrationNumber = Input::get('registrationNumber');
        $company->telephone = Input::get('telephone');
        $company->FD_person = Input::get('FD_person');
        $company->FD_email = Input::get('FD_email');
        $company->FD_telephone = Input::get('FD_telephone');
        $company->FM_contact_person = Input::get('FM_contact_person');
        $company->FM_email = Input::get('FM_email');
        $company->FM_telephone = Input::get('FM_telephone');

        $company->save();

        /*

        $data = ['company' => $company];

        Mail::send('emails.new-company', $data, function($message)
        {
            $message->to(Input::get('email'),Input::get('contact_person'))->bcc('sgilmore@statusdata.co.za','Stephen Gilmore')->bcc('rachael@statusdata.co.za','Rachael Maphopha')->subject('Company Added to the Prestige Advantage System');
            $message->from('no-reply@prestigeAdvantage.co.za');

        }*/

        return Redirect::to('pricing/'.$company->id)->with('view-success', ' SUCCESS: New Company Added, set product pricing');
    }

    public function serverTransunionInvestigate()
    {
        return View::make('credit-network.transunion-investigate');
    }

    public function handleTransunionInvestigate()
    {
        $validator = Validator::make(Input::all(),
            [
                'accountHolder' => 'required',
                'idNumber' => 'required',
                'bank' => 'required',
                'branch' => 'required',
                'branchName' => 'required',
                'accountNumber' => 'required',
                'accountType' => 'required',
                'amount' => 'required',
                'terms' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        //$email = 'koketso.maphopha@gmail.com';
        $accountHolder = Input::get('accountHolder');
        $idNumber = Input::get('idNumber');
        $bank = Input::get('bank');
        $country = Input::get('country');
        $branch = Input::get('branch');
        $accountNumber = Input::get('accountNumber');
        $accountType = Input::get('accountType');
        $amount = Input::get('amount');
        $terms = Input::get('terms');
        $branchName = Input::get('branchName');

        $url = 'https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$accountHolder.'&regNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branch.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=5126';

        try {
            $xml = simplexml_load_file($url);

            $transaction = DB::table('transactions')
                ->where('user','=',Auth::user()->name)
                ->where('company','=',Auth::user()->companyName)
                ->where('product','=','Transunion Profile Investigate')
                ->first();

            $pricing = DB::table('products')
                ->where('company','=',Auth::user()->companyName)
                ->first();


            if($transaction==NULL)
            {
                $transaction = new Transaction;
                $transaction->user = Auth::user()->name;
                $transaction->company = Auth::user()->companyName;
                $transaction->product = 'Transunion Profile Investigat';
                $transaction->save();
            }

            else
            {
                DB::table('transactions')
                    ->where('user','=', Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Transunion Profile Investigate')
                    ->update(array(
                            'qty' => $transaction->qty+1,
                            'price' =>$transaction->price+$pricing->TU_investigative_report
                        )
                    );
            }

        } catch (Exception $e) {
            return Redirect::back()->with('view-success', 'SUCCESS: Your Investigative Report will be sent to your email in the next 24 hours');
        }

        return Redirect::back()->with('view-success', 'SUCCESS: Your Investigative Report will be sent to your email in the next 24 hours');
    }

    public function serverOnFileCommercial()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $compuscanOnfile = $prices->compuscan_on_file;
        $transunion = $prices->transunion_on_file;
        $xdsOnfile = $prices->xds_on_file;

        return View::make('pages.on-file-commercial')
            ->with('xdsOnfile',$xdsOnfile)
            ->with('compuscanOnfile',$compuscanOnfile)
            ->with('transunion',$transunion)
            ->with('user',$user);
    }

    public function handleOnFileCommercial()
    {
        $validator = Validator::make(Input::all(),
            [
                'businessName' => 'required',
                'regNumber' => 'required'
            ]);

        if ($validator->fails()) {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $email = Auth::user()->email;
        $businessName = Input::get('businessName');
        $registrationNumber = Input::get('regNumber');
        $registrationNumber = preg_replace("/[^a-zA-Z0-9]/", "", Input::get('regNumber'));

        $part1 = substr($registrationNumber, 0, 4);
        $part2 = substr($registrationNumber, 4, 6);
        $part3 = substr($registrationNumber, 7, 2);


        if (Input::get("response") == 'Compuscan') {
            $url = 'https://cir.credit-network.biz/api/CommercialEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&registrationNumber='.$registrationNumber.'&VATnumber=&TAXnumber=&reportCode=NN';

            try {
                $xml = simplexml_load_file($url);

                $transaction = DB::table('transactions')
                    ->where('user','=',Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Compuscan On file Report')
                    ->first();

                $pricing = DB::table('products')
                    ->where('company','=',Auth::user()->companyName)
                    ->first();


                if($transaction==NULL)
                {
                    $transaction = new Transaction;
                    $transaction->user = Auth::user()->name;
                    $transaction->company = Auth::user()->companyName;
                    $transaction->product = 'Compuscan On file Report';
                    $transaction->save();
                }
            } catch (Exception $e) {
                return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email shortly');
            }

            
            /*
            $params = new StdClass();
            $params->request = new StdClass();
            $params->request->pUsrnme = "28822-1"; //28822-1
            $params->request->pPasswrd = '$t@tu$'; //$t@tu$
            $params->request->pOrigin = "StatusData";
            $params->request->pVersion = "1.0";
            $params->request->pOrigin_Version = "2.3";
            $params->request->pResultType = "XML";
            $params->request->pTransaction = "<Transactions>
                                                <Search_Criteria>
                                                    <Company_Name>Prestige Credit</Company_Name>
                                                    <Reg_Number1>1997</Reg_Number1>
                                                    <Reg_Number2>209640</Reg_Number2>
                                                    <Reg_Number3>64</Reg_Number3>
                                                    <Tax_Number></Tax_Number>
                                                    <Vat_Number></Vat_Number>
                                                    <ResultType>XML</ResultType>
                                                </Search_Criteria>
                                            </Transactions>";

            $options = array('trace' => 1, 'exceptions' => 1);

            $wsdl = "https://webservices.compuscan.co.za/CompanySearchService?wsdl";

            //Create the webservice connection

            $webservice = new SoapClient($wsdl, $options);
            $response = $webservice->CompanyPossibleSearch($params);dd($response);

            if (!$response->TransReplyClass->transactionCompleted) {
                return Redirect::back()->with('view-error', $response->TransReplyClass->errorDescription);
            }

            $result = $response->TransReplyClass;
            $loadResult2 = simplexml_load_string($result->retData);

            $companyID =$loadResult2->POS_MATCHES->ROW[0]->COMPANY_ID;
            $EnquiryID = $loadResult2->ENQUIRY_ID[0];

            $params = new StdClass();
            $params->request = new StdClass();
            $params->request->pUsrnme = "28822-1";
            $params->request->pPasswrd = '$t@tu$';
            $params->request->pOrigin = "StatusData";
            $params->request->pVersion = "1.0";
            $params->request->pOrigin_Version = "2.3";
            $params->request->pTransaction = "<Transactions>
                                            <Search_Criteria>
                                                <Company_Name>$businessName</Company_Name>
                                                <Reg_Number1>$part1</Reg_Number1>
                                                <Reg_Number2>$part2</Reg_Number2>
                                                <Reg_Number3>$part3</Reg_Number3>
                                                <Vat_Number></Vat_Number>
                                                <Tax_Number></Tax_Number>
                                                <Deeds_Data>Y</Deeds_Data>
                                                <ResultType>PDF</ResultType>
                                                <Run_CompanyScore>Y</Run_CompanyScore>
                                                <Run_Codix>N</Run_Codix>
                                                <PosMatchEnq_Id>$EnquiryID</PosMatchEnq_Id>
                                                <CompanyId>$companyID</CompanyId>
                                            </Search_Criteria>
                                         </Transactions>";


            $options = array('trace' => 1, 'exceptions' => 1);

            $wsdl = "https://webservices.compuscan.co.za/CompanySearchService?wsdl";

            //Check if the PHP-SOAP module is installed
            if (!class_exists('SoapClient')) {
                die("Missing PHP-Soap module.");
            }
            //Create the webservice connection

            $webservice = new SoapClient($wsdl, $options);
            $response = $webservice->CompanyFullSearch($params);


            if (!$response->TransReplyClass->transactionCompleted) {
                return Redirect::back()->with('view-error', $value->TransactionReplyClass->errorDescription);
            }
            //dd($response->TransReplyClass->retData);
            $value = $response->TransReplyClass->retData;

            $decoded = base64_decode($value);


            //$decoded = base64_decode($base64);
            $file = 'Compuscan Business Credit Report.pdf';
            file_put_contents($file, $decoded);

            if (file_exists($file)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . basename($file) . '"');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                readfile($file);
                exit;
            }*/





        }

         elseif (Input::get("response") == 'xds') {

            //assign values to variables
            $strUser = "Statusdata_live";
            $strPwd = "uarivx";

            $client = new SoapClient ("https://www.web.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
            $parameters = array("strUser" => $strUser, "strPwd" => $strPwd);
            $configQry = $client->Login($parameters);
            $ticket = preg_replace("~/~", "\\\\", $configQry->LoginResult);

            //dd($ticket);
            $ticketNo = $ticket;
            $client = new SoapClient ("https://www.web.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
            $parameters = array ("XDSConnectTicket"=>$ticketNo); $configQry = $client->IsTicketValid ($parameters);
            
            $configXML = preg_replace("~/~", "\\\\", $configQry->IsTicketValidResult);
            //dd($configXML);

            $ConnectTicket = $ticket;
            $Reg1 = $part1;
            $Reg2 = $part2;
            $Reg3 = $part3;
            $BusinessName = $businessName;
            $VatNo = "";
            $SoleProID = "";
            $YourReference = "";
            $VoucherCode = "";

            $client = new SoapClient ("https://www.web.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
$parameters = array (
"ConnectTicket"=>$ConnectTicket,'Reg1'=>$Reg1,'Reg2'=>$Reg2,'Reg3'=>$Reg3,'BusinessName'=>$BusinessName,'VatNo'=>$VatNo,'SoleProID'=>$SoleProID,'YourReference'=>$YourReference);
$configQry = $client-> ConnectBusinessMatch ($parameters);

            dd($configQry);
            //ConnectBusinessMatchResult

            $result = $configQry->ConnectBusinessMatchResult;
            $loadResult = simplexml_load_string($result);
            $enquiryID = $loadResult->CommercialDetails->EnquiryID;
            $enquiryResultID = $loadResult->CommercialDetails->EnquiryResultID;
            $EnquiryID = $enquiryID;
            $EnquiryResultID = $enquiryResultID;
            $ProductID = '41';
            $BonusXML = '';
            $client = new SoapClient ("https://www.web.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
            $parameters = array("ConnectTicket" => $ConnectTicket, 'EnquiryID' => $EnquiryID, 'EnquiryResultID' => $EnquiryResultID, 'ProductID' => $ProductID, 'EnquiryID' => $EnquiryID, 'BonusXML' => $BonusXML);
            $configQry2 = $client->ConnectGetResultBinary($parameters);

            $pdfFile = $configQry2->ConnectGetResultBinaryResult;

            $file = 'XDS Business Credit Report.pdf';
            file_put_contents($file, $pdfFile);

            if (file_exists($file)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . basename($file) . '"');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                readfile($file);
                exit;
            }


        }
        elseif (Input::get("response") == 'Transunion') {


            $url = 'https://cir.credit-network.biz/api/CommercialEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto=' . $email . '&businessName=' . $businessName . '&registrationNumber=' . $registrationNumber . '&VATnumber=&TAXnumber=&reportCode=5142';

            try {
                $xml = simplexml_load_file($url);
            } catch (Exception $e) {

                $transaction = DB::table('transactions')
                    ->where('user', '=', Auth::user()->name)
                    ->where('company', '=', Auth::user()->companyName)
                    ->where('product', '=', 'Transunion On-File Report')
                    ->first();

                $pricing = DB::table('products')
                    ->where('company', '=', Auth::user()->companyName)
                    ->first();


                if ($transaction == NULL) {
                    $transaction = new Transaction;
                    $transaction->user = Auth::user()->name;
                    $transaction->company = Auth::user()->companyName;
                    $transaction->product = 'Transunion On-File Report';
                    $transaction->save();
                } else {
                    DB::table('transactions')
                        ->where('user', '=', Auth::user()->name)
                        ->where('company', '=', Auth::user()->companyName)
                        ->where('product', '=', 'Transunion On-File Report')
                        ->update(array(
                                'qty' => $transaction->qty + 1,
                                'price' => $transaction->price + $pricing->TU_OnFile_Report
                            )
                        );
                }

                return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email shortly');

            }
        }


        return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email shortly');
    }

    public function serverExpressBasicCommercial()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();


        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.express-basic-commercial')
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleExpressBasicCommercial()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if(Input::get("response")=='Status Data') {

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Basic Express 4hr Report';

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Express 4 hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Status Data');
        }
        else{
            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Basic Express 4hr Report';
            $request->response = Input::get('response');

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('pjacobs@compuscan.co.za','Pasha Jacobs')->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Express 4 hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
        }


    }

    public function serverExpressBasicPrincipal()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.express-basic-principal')
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleExpressBasicPrincipal()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if(Input::get("response")=='Status Data') {

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Basic Express 4hr Principal Report';

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Express 4 hr Principal Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Status Data');
        }
        else{
            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Basic Express 4hr Principal Report';
            $request->response = Input::get('response');

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('pjacobs@compuscan.co.za','Pasha Jacobs')->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Express 4 hr Principal Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
        }


    }

    public function serverBasicCommercial()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.basic-commercial')
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleBasicCommercial()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if(Input::get("response")=='Status Data') {

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Basic Commercial 24hr Report';

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Basic Commercial 24 hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Status Data');
        }
        else{
            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Basic Commercial 24hr Report';
            $request->response = Input::get('response');

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('pjacobs@compuscan.co.za','Pasha Jacobs')->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Commercial 24hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
        }


    }

    public function serverBasicPrincipal()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.basic-principal')
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleBasicPrincipal()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if(Input::get("response")=='Status Data') {

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Basic Principal 24hr Report';

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Basic Principal 24 hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Status Data');
        }
        else{
            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Basic Principal 24hr Report';
            $request->response = Input::get('response');

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('pjacobs@compuscan.co.za','Pasha Jacobs')->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Principal 24hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
        }


    }

    public function serverDetailedCommercial()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $inoxicoQuick = $prices->inoxico_quick;
        $inoxicoBasic = $prices->inoxico_basic;
        $inoxicoDetailed = $prices->inoxico_detailed;
        $inoxicoComprehensive = $prices->inoxico_comprehensive;


        return View::make('pages.detailed-commercial')
            ->with('inoxicoQuick',$inoxicoQuick)
            ->with('inoxicoBasic',$inoxicoBasic)
            ->with('inoxicoDetailed',$inoxicoDetailed)
            ->with('inoxicoComprehensive',$inoxicoComprehensive)
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleDetailedCommercial()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required',
                'report' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->report = Input::get('report');

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $request->save();

            $id = Auth::user()->id;
            $user = User::find($id);


            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('rachael@statusdata.co.za','Rach')->bcc('sgilmore@statusdata.co.za','Stephen')->bcc('koketso.maphopha@gmail.com', 'Rach')->bcc('sgilmorejhb@gmail.com','Stephen')->subject('Researched Report Request');
                $message->from('info@statusdata.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Inoxico');


    }

    public function serverDetailedPrincipal()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.detailed-principal')
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleDetailedPrincipal()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if(Input::get("response")=='Status Data') {

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Detailed Commercial (3-5 days) Report';

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Basic Commercial 24 hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Status Data');
        }
        else{
            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Detailed Commercial (3-5 days) Report';
            $request->response = Input::get('response');

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('pjacobs@compuscan.co.za','Pasha Jacobs')->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Commercial 24hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
        }


    }

    public function serverComprehensiveCommercial()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.comprehensive-commercial')
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleComprehensiveCommercial()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if(Input::get("response")=='Status Data') {

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Comprehensive Commercial (5 days) Report';

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Basic Commercial 24 hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Status Data');
        }
        else{
            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Comprehensive Commercial (5 days) Report';
            $request->response = Input::get('response');

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('pjacobs@compuscan.co.za','Pasha Jacobs')->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Commercial 24hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
        }


    }

    public function serverComprehensivePrincipal()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.comprehensive-principal')
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleComprehensivePrincipal()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if ($validator->fails()) {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id', '=', $id)
            ->first();

        if (Input::get("response") == 'Status Data') {

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Detailed Commercial (3-5 days) Report';

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Basic Commercial 24 hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Status Data');
        } else {
            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Detailed Commercial (3-5 days) Report';
            $request->response = Input::get('response');

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('pjacobs@compuscan.co.za', 'Pasha Jacobs')->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Commercial 24hr Researched Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Researched Report request has been submitted to Compuscan');
        }

    }

    public function serverQuickFixReport()
    {
        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('pages.quick-fix-report')
            ->with('user',$user)
            ->with('client',$client);
    }

    public function handleQuickFixReport()
    {
        $validator = Validator::make(Input::all(),
            [
                'creditApplication' => 'required'
            ]);

        if ($validator->fails()) {
            return Redirect::back()->with('view-error', 'There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id', '=', $id)
            ->first();

            $request = new ResearchedReport;
            $request->clientName = $client->name;
            $request->ClientTel = '012 799 6055';
            $request->clientEmail = $client->email;
            $request->companyName = Input::get('companyName');
            $request->DebtorsRegNumber = Input::get('DebtorsRegNumber');
            $request->debtorContacts = Input::get('debtorContacts');
            $request->DebtorEmail = Input::get('DebtorEmail');
            $request->refCompany1 = Input::get('refCompany1');
            $request->termRef1 = Input::get('termRef1');
            $request->creditLimitRef1 = Input::get('creditLimitRef1');
            $request->contact1 = Input::get('contact1');
            $request->contactPerson1 = Input::get('contactPerson1');
            $request->consent1 = Input::get('consent1');
            $request->refCompany2 = Input::get('refCompany2');
            $request->termRef2 = Input::get('termRef2');
            $request->creditLimitRef2 = Input::get('creditLimitRef2');
            $request->contact2 = Input::get('contact2');
            $request->contactPerson2 = Input::get('contactPerson2');
            $request->consent2 = Input::get('consent2');
            $request->refCompany3 = Input::get('refCompany3');
            $request->termRef3 = Input::get('termRef3');
            $request->creditLimitRef3 = Input::get('creditLimitRef3');
            $request->contact3 = Input::get('contact3');
            $request->contactPerson3 = Input::get('contactPerson3');
            $request->consent3 = Input::get('consent3');
            $request->initials = Input::get('initials');
            $request->surname = Input::get('surname');
            $request->idNumber = Input::get('idNumber');
            $request->accountNumber = Input::get('accountNumber');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->branchCode = Input::get('branchCode');
            $request->accountType = Input::get('accountType');
            $request->type = 'Detailed Commercial (3-5 days) Report';

            if (Input::hasFile('creditApplication')) {
                $file = Input::file('creditApplication');
                $file->move('app/creditApplication/', $file->getClientOriginalName());
                $request->creditApplication = 'app/creditApplication/' . $file->getClientOriginalName();

            }

            $id = Auth::user()->id;
            $user = User::find($id);

            $request->save();

            $data = ['request' => $request, 'user' => $user];

            Mail::send('emails.researchedReport', $data, function ($message) use ($request) {
                $message->to('sgilmore@statusdata.co.za', 'Stephen Gilmore')->cc('rachael@statusdata.co.za', 'Rachael Maphopha')->subject('Quick Fix Report Request');
                $message->from('no-reply@prestige.co.za');
                $message->attach($request->creditApplication);

            });

            return Redirect::back()->with('view-success', 'SUCCESS: Your Quick Fix Report request has been submitted to Status Data');
        }

    public function serverBankCodeCommercial()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $compuscanBankCode = $prices->compuscan_24hr_bank_code;
        $transunionBankCode = $prices->transunion_24hr_bank_code;


        return View::make('pages.bank-code-commercial')
            ->with('compuscanBankCode',$compuscanBankCode)
            ->with('transunionBankCode',$transunionBankCode)
            ->with('user',$user);
    }

    public function handleBankCodeCommercial()
    { //24 hours bank codes

        $id = Auth::user()->id;
        $client = DB::table('users')
            ->where('id', '=', $id)
            ->first();

        $providor = NULL;

        if (Input::get("response") == 'Compuscan') {

            $validator = Validator::make(Input::all(),
                [
                    'accountHolder' => 'required',
                    'idNumber' => 'required',
                    'bank' => 'required',
                    'country' => 'required',
                    'branch' => 'required',
                    'branchName' => 'required',
                    'accountNumber' => 'required',
                    'accountType' => 'required',
                    'amount' => 'required',
                    'terms' => 'required',
                    'businessName' => 'required'
                ]);

            if($validator->fails())
            {
                return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
            }

            $email = Auth::user()->email;
            //$email = 'koketso.maphopha@gmail.com';
            $accountHolder = Input::get('accountHolder');
            $idNumber = Input::get('idNumber');
            $bank = Input::get('bank');
            $country = Input::get('country');
            $branch = Input::get('branch');
            $accountNumber = Input::get('accountNumber');
            $accountType = Input::get('accountType');
            $amount = Input::get('amount');
            $terms = Input::get('terms');
            $branchName = Input::get('branchName');
            $businessName = Input::get('businessName');

            $url = 'https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$businessName.'&regNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branch.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=NNB';

            try {
                $xml = simplexml_load_file($url);

                $transaction = DB::table('transactions')
                    ->where('user','=',Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Compuscan 24 Hour Bank Code')
                    ->first();

                $pricing = DB::table('products')
                    ->where('company','=',Auth::user()->companyName)
                    ->first();


                if($transaction==NULL)
                {
                    $transaction = new Transaction;
                    $transaction->user = Auth::user()->name;
                    $transaction->company = Auth::user()->companyName;
                    $transaction->product = 'Compuscan 24 Hour Bank Code';
                    $transaction->save();
                }

                else
                {
                    DB::table('transactions')
                        ->where('user','=', Auth::user()->name)
                        ->where('company','=',Auth::user()->companyName)
                        ->where('product','=','Compuscan 24 Hour Bank Code')
                        ->update(array(
                                'qty' => $transaction->qty+1,
                                'price' =>$transaction->price+$pricing->CS_bank_code
                            )
                        );
                }


            } catch (Exception $e) {
                return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Bank Code Report will be sent to your email in the next 24 hours');
            }

            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial/Business Report will be sent to your email in the next 24 hours');

        } else {

            $validator = Validator::make(Input::all(),
                [
                    'accountHolder' => 'required',
                    'idNumber' => 'required',
                    'bank' => 'required',
                    'branch' => 'required',
                    'branchName' => 'required',
                    'accountNumber' => 'required',
                    'accountType' => 'required',
                    'amount' => 'required',
                    'terms' => 'required'
                ]);

            if($validator->fails())
            {
                return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
            }

            $email = Auth::user()->email;
            //$email = 'koketso.maphopha@gmail.com';
            $accountHolder = Input::get('accountHolder');
            $idNumber = Input::get('idNumber');
            $bank = Input::get('bank');
            $country = Input::get('country');
            $branch = Input::get('branch');
            $accountNumber = Input::get('accountNumber');
            $accountType = Input::get('accountType');
            $amount = Input::get('amount');
            $terms = Input::get('terms');
            $branchName = Input::get('branchName');

            $url = 'https://cir.credit-network.biz/api/BankCodeEnquiry?emailaddress=rachael@mybusinessvault.co.za&password=11TIEGO09&emailto='.$email.'&businessName='.$accountHolder.'&regNumber='.$idNumber.'&accountholder='.$accountHolder.'&spesificBankName='.$bank.'&bankCountry='.$country.'&branchName='.$branchName.'&branchCode='.$branch.'&accountNumber='.$accountNumber.'&accountType='.$accountType.'&amount='.$amount.'&terms='.$terms.'&reportCode=5022';

            try {
                $xml = simplexml_load_file($url);

                $transaction = DB::table('transactions')
                    ->where('user','=',Auth::user()->name)
                    ->where('company','=',Auth::user()->companyName)
                    ->where('product','=','Transunion 24 Hour Bank Code')
                    ->first();

                $pricing = DB::table('products')
                    ->where('company','=',Auth::user()->companyName)
                    ->first();


                if($transaction==NULL)
                {
                    $transaction = new Transaction;
                    $transaction->user = Auth::user()->name;
                    $transaction->company = Auth::user()->companyName;
                    $transaction->product = 'Transunion 24 Hour Bank Code';
                    $transaction->save();
                }

                else
                {
                    DB::table('transactions')
                        ->where('user','=', Auth::user()->name)
                        ->where('company','=',Auth::user()->companyName)
                        ->where('product','=','Transunion 24 Hour Bank Code')
                        ->update(array(
                                'qty' => $transaction->qty+1,
                                'price' =>$transaction->price+$pricing->TU_bank_code
                            )
                        );
                }

            } catch (Exception $e) {
                return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial Bank Code Report will be sent to your email in the next 24 hours');
            }

            return Redirect::back()->with('view-success', 'SUCCESS: Your Commercial Report will be sent to your email in the next 24 hours');

        }

    }

    public function serverPrincipalBankCode()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $compuscanBankCodePrincipal = $prices->compuscan_24hr_principal_bank_code;
        $transunionBankCodePrincipal = $prices->transunion_4hr_bank_code;

        return View::make('pages.principal-bank-code')
            ->with('compuscanBankCodePrincipal',$compuscanBankCodePrincipal)
            ->with('transunionBankCodePrincipal',$transunionBankCodePrincipal)
            ->with('user',$user);
    }

    public function handlePrincipalBankCode()
    {

    }

    public function serverBankCodeCommercialExpress()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $compuscanBankCodeExpress = $prices->compuscan_4hr_bank_code;
        $transunionBankCodeExpress = $prices->transunion_4hr_principal_bank_code;


        return View::make('pages.bank-code-commercial-express')
            ->with('compuscanBankCodeExpress',$compuscanBankCodeExpress)
            ->with('transunionBankCodeExpress',$transunionBankCodeExpress)
            ->with('user',$user);
    }

    public function handleBankCodeCommercialExpress()
    {

    }

    public function serverPrincipalBankCodeExpress()
    {
        return View::make('pages.principal-bank-code-express');
    }

    public function handlePrincipalBankCodeExpress()
    {

    }

    public function serverAllUser()
    {
        $users = DB::table('users')
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('users.all-users')
            ->with('user',$user)
            ->with('users',$users);
    }

    public function AddNewUser()
    {
        $companies = DB::table('companies')
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('management.add-new-user')
            ->with('user',$user)
            ->with('companies',$companies);
    }

    public function handleAddNewUser()
    {

        $validator = Validator::make(Input::all(),
            [
                'name' => 'required',
                'email' => 'required',
                'password' => 'required',
                'password1' => 'required',
                'companies' => 'required'
            ]);

        $users = DB::table('users')
            ->get();

        foreach($users as $user)
        {
            if($user->email==Input::get('email'))
            {
                return Redirect::back()->with('view-error', ' This email address already exists, rather link email address to multiple companies')->withInput()->withErrors($validator);
            }
        }

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        if((Input::get('password'))!=(Input::get('password1')))
        {
            return Redirect::back()->with('view-error', ' Passwords do not match')->withInput()->withErrors($validator);
        }

        $user = new User;
        $user->password = Hash::make(Input::get('password'));
        $user->email = Input::get('email');
        $user->name = Input::get('name');
        $user->role = 'user';
        $user->linkedCompanies = implode(',', Input::get('companies'));

        $user->save();

        $password =  Input::get('password');

        $data = ['user' => $user, 'password' => $password];

        Mail::send('emails.new-user', $data, function($message) use($user)
        {
            $message->to(Input::get('email'),'New User')->subject('New user account for the Prestige Advantage client system');
            $message->from('Admin2@prestigeadvantage.co.za');

        });
        $users = DB::table('users')
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('users.all-users')
            ->with('user',$user)
            ->with('users',$users)
            ->with('view-success', ' SUCCESS: New User Added');

    }

    public function serverUserSearch()
    {

    }

    public function handleUserSearch()
    {
        $validator = Validator::make(Input::all(),
            [
                'search' => 'required',
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'No search entered, please try again')->withInput()->withErrors($validator);
        }

        $query = Request::get('search');

        $users = DB::table('users')
            ->where('email', 'LIKE', '%' . $query . '%')//email
            ->orWhere('role', 'LIKE', '%' . $query . '%')//role
            ->orWhere('name', 'LIKE', '%' . $query . '%')//name
            ->get();

        $id = Auth::user()->id;
        $currentUser = DB::table('users')
            ->where('id','=',$id)
            ->first();

        if($users==NULL)
        {
            return Redirect::back()->with('view-search-error', '<i class="white fa fa-times"></i> <strong>Oops!</strong>  There where no results found, please try searching by user name or email or role.');
        }
        else
        {
            // multiple products search results
            return View::make('users.user-search')
                ->with('currentUser', $currentUser)
                ->with('users',$users);
        }

    }

    public function serverLinkUserMultipleCompanies($id)
    {
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $companies = DB::table('companies')
            ->get();

        return View::make('users.link-user')
            ->with('user',$user)
            ->with('companies',$companies);
    }

    public function handleLinkUserMultipleCompanies($id)
    {
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $companies = DB::table('companies')
            ->get();

        $validator = Validator::make(Input::all(),
            [
                'companies' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', ' There were errors in your submission please review below')->withInput()->withErrors($validator);
        }

        if(Input::has('companies')) {

            DB::table('users')
                ->where('id','=', $user->id)
                ->update(array(
                        'linkedCompanies' => implode(',', Input::get('companies'))
                    )
                );

        }

        return Redirect::to('all-users')->with('view-success', 'SUCCESS: User linked to companies');
    }

    public function serverCreditApplicationQuote()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        return View::make('pages.credit-application-quote')
            ->with('user',$user);
    }

    public function handleCreditApplicationQuote()
    {
        $validator = Validator::make(Input::all(),
            [
                'company_name' => 'required',
                'orders' => 'required',
                'termsOfPayment' => 'required',
                'quotations' => 'required',
                'goods' => 'required',
                'assemble' => 'required',
                'buyFromSupplier' => 'required',
                'warrantee' => 'required',
                'agreement' => 'required',
                'instructions' => 'required',
                'determinePurchasePrice' => 'required',
                'interest' => 'required',
                'interestCharge' => 'required',
                'suretyship' => 'required',
                'returnPolicy' => 'required',
                'dangerous' => 'required',
                'testCertificate' => 'required',
                'termsInvoice' => 'required',
                'termsDeliveryNote' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'Some information is missing, please review your answers and try again.')->withInput()->withErrors($validator);
        }


        $quote = new CreditApplicationQuote();
        $quote->company_name = Input::get('company_name');
        $quote->orders = Input::get('orders');
        $quote->termsOfPayment = Input::get('termsOfPayment');

        $quote->quotations = Input::get('quotations');
        $quote->goods = Input::get('goods');
        $quote->assemble = Input::get('assemble');

        $quote->buyFromSupplier = Input::get('buyFromSupplier');
        $quote->warrantee = Input::get('warrantee');
        $quote->agreement = Input::get('agreement');

        $quote->instructions = Input::get('instructions');
        $quote->determinePurchasePrice = Input::get('determinePurchasePrice');
        $quote->interest = Input::get('interest');

        $quote->dateInterest = Input::get('dateInterest');
        $quote->interestCharge = Input::get('interestCharge');
        $quote->suretyship = Input::get('suretyship');

        $quote->returnPolicy = Input::get('returnPolicy');
        $quote->returnPolicyDescription = Input::get('returnPolicyDescription');
        $quote->dangerous = Input::get('dangerous');
        $quote->testCertificate = Input::get('testCertificate');

        $quote->termsInvoice = Input::get('termsInvoice');
        $quote->termsDeliveryNote = Input::get('termsDeliveryNote');
        $quote->specialTerms = Input::get('specialTerms');

        if (Input::hasFile('creditApplication'))
        {
            $file = Input::file('creditApplication');
            $file->move('app/creditApplication/', $file->getClientOriginalName());
            $quote->creditApplication = 'app/creditApplication/'.$file->getClientOriginalName();

        }
        $quote->save();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $data2 = ['user' => $user];

        $data = ['quote' => $quote];


        if (Input::hasFile('creditApplication')) {
            Mail::send('emails.creditAppQuote', $data, function ($message) use ($quote) {
                $message->to('Admin1@prestigeAdvantage.co.za', 'Admin')->to('Admin2@prestigeAdvantage.co.za','Admin2')->to('rachael@statusdata.co.za', 'Tech')->subject('Credit Application Review request for ' . $quote->company_name);
                $message->from('Admin2@prestigeadvantage.co.za');
                $message->attach($quote->creditApplication);

            });

        }
        else{
            Mail::send('emails.creditAppQuote', $data, function ($message) use ($quote) {
                $message->to('Admin1@prestigeAdvantage.co.za', 'Admin')->to('Admin2@prestigeAdvantage.co.za','Admin2')->to('rachael@statusdata.co.za', 'Tech')->subject('Credit Application Review request for ' . $quote->company_name);
                $message->from('Admin2@prestigeadvantage.co.za');
            });

        }
;

        Mail::send('emails.quoteResponseUser', $data2, function($message) use($user)
        {
            $message->to($user->email, $user->name)->subject('Credit Application Review request');
            $message->from('Admin2@prestigeadvantage.co.za');
        });

        return Redirect::to('/home')->with('view-success',' Thank you! Our team will get back to you as soon as possible.');

    }

    public function serverGuarantee()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        return View::make('pages.guarantees')
            ->with('user',$user);
    }

    public function handleGuarantees()
    {
        $validator = Validator::make(Input::all(),
            [
                'overview' => 'required',
                'options' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'Some information is missing, please review your answers and try again.')->withInput()->withErrors($validator);
        }

        $guarantee = new Guarantee();
        $guarantee->options = implode(',', Input::get('options'));
        $guarantee->overview = Input::get('overview');
        $guarantee->save();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $selected = explode(',', $guarantee->options);

        $data = ['guarantee' => $guarantee,'selected' => $selected];

        Mail::send('emails.guaranteeRequest', $data, function($message) use ($user)
        {
            $message->to('rachael@statusdata.co.za','Tech')->to('Admin2@prestigeadvantage.co.za','Admin2')->cc('admin1@prestigeadvantage.co.za','Admin1')->subject('Guarantees request for '.$user->companyName);
            $message->from('Admin2@prestigeadvantage.co.za');

        });

        return Redirect::to('/home')->with('view-success',' Thank you for your Enquiry. One of our consultants will be in contact with you soon.');

    }

    public function serverTraining()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        return View::make('pages.training-on-legislation')
            ->with('user',$user);
    }

    public function handleTraining()
    {
        $validator = Validator::make(Input::all(),
            [
                'overview' => 'required',
                'options' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'Some information is missing, please review your answers and try again.')->withInput()->withErrors($validator);
        }

        $training = new Training();
        $training->options = implode(',', Input::get('options'));
        $training->overview = Input::get('overview');
        $training->save();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $selected = explode(',', $training->options);

        $data = ['training' => $training, 'selected' => $selected];

        Mail::send('emails.trainingRequest', $data, function($message) use ($user)
        {
            $message->to('rachael@statusdata.co.za','Tech')->to('Admin2@prestigeadvantage.co.za','Admin2')->cc('admin1@prestigeadvantage.co.za','Admin1')->subject('Legislation training request for '.$user->companyName);
            $message->from('Admin2@prestigeadvantage.co.za');

        });

        return Redirect::to('/home')->with('view-success',' Thank you for your Enquiry. One of our consultants will be in contact with you soon.');

    }

    public function serverDisclaimer()
    {
        return View::make('pages.disclaimer');
    }

    public function handleDisclaimer()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
    }

    public function serverSelectCompany()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $companies =  explode(',', $user->linkedCompanies);

        return View::make('pages.select-company')
            ->with('user',$user)
            ->with('companies',$companies);
    }

    public function serverChooseCompany($company)
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        DB::table('users')
            ->where('id','=', $user->id)
            ->update(array(
                    'companyName' => $company
                )
            );

        $email = Auth::user()->email;

        $user = DB::table('users')
            ->where('email','=',$email)
            ->first();

        return Redirect::to('/home')
            ->with('user',$user);
    }

    public function serverPricing($company)
    {
        $company = DB::table('companies')
            ->where('id','=',$company)
            ->first();

        $company = $company->companyName;

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('invoice.pricing')
            ->with('user',$user)
            ->with('company',$company);
    }

    public function setStandardPricing($company)
    {
        $pricing = new Pricing;
        $pricing->company = $company;
        $pricing->save();

        return Redirect::to('manage-users')->with('view-success','Standard pricing set successfully');

    }

    public function setToAdmin()
    {
        return Redirect::to('management-dashboard');
    }

    public function handleViewCompany($company)
    {
        $company = DB::table('companies')
            ->where('companyName','=',$company)
            ->first();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('management.view-company')
            ->with('user',$user)
            ->with('company',$company);
    }

    public function serverEditCompany($id)
    {
        $company = DB::table('companies')
            ->where('id','=',$id)
            ->first();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        return View::make('management.edit-company')
            ->with('company',$company)
            ->with('user',$user);
    }

    public function handleEditCompany($id)
    {
        $validator = Validator::make(Input::all(),
            [
                'companyName' => 'required',
                'address' => 'required',
                'contact_person' => 'required',
                'email' => 'required',
                'telephone' => 'required'
            ]);

        if($validator->fails())
        {
            return Redirect::back()->with('view-error', 'Some information may be missing or incorrectly provided, please review below')->withInput()->withErrors($validator);
        }


        if(Input::has('companyName')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'companyName' => Input::get('companyName')
                    )
                );
        }


        if(Input::has('address')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'address' => Input::get('address')
                    )
                );
        }

        if(Input::has('postal_address')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'postal_address' => Input::get('postal_address')
                    )
                );
        }

        if(Input::has('registrationNumber')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'registrationNumber' => Input::get('registrationNumber')
                    )
                );
        }

        if(Input::has('VATNumber')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'VATNumber' => Input::get('VATNumber')
                    )
                );
        }

        if(Input::has('contact_person')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'contact_person' => Input::get('contact_person')
                    )
                );
        }

        if(Input::has('email')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'email' => Input::get('email')
                    )
                );
        }

        if(Input::has('telephone')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'telephone' => Input::get('telephone')
                    )
                );
        }

        if(Input::has('FD_person')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'FD_person' => Input::get('FD_person')
                    )
                );
        }

        if(Input::has('FD_email')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'FD_email' => Input::get('FD_email')
                    )
                );
        }

        if(Input::has('FD_telephone')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'FD_telephone' => Input::get('FD_telephone')
                    )
                );
        }

        if(Input::has('FM_contact_person')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'FM_contact_person' => Input::get('FM_contact_person')
                    )
                );
        }

        if(Input::has('FM_email')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'FM_email' => Input::get('FM_email')
                    )
                );
        }


        if(Input::has('FM_telephone')) {
            DB::table('companies')
                ->where('id','=', $id)
                ->update(array(
                        'FM_telephone' => Input::get('FM_telephone')
                    )
                );
        }

        return Redirect::to('manage-users')->with('view-success', 'SUCCESS: Company Profile Updated');
    }

    public function exportToExcel($company)
    {
        $transactions = DB::table('transactions')
            ->where('company','=',$company)
            ->get();

        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();

        $transactions= json_decode( json_encode($transactions), true);

        Excel::create('transactions', function($excel) use($transactions) {
            $excel->sheet('Sheet 1', function($sheet) use($transactions) {
                $sheet->fromArray($transactions);
            });
        })->export('xls');
    }

    public function showXDS()
    {
        $id = Auth::user()->id;
        $user = DB::table('users')
            ->where('id','=',$id)
            ->first();
        $prices = DB::table('pricing')
            ->where('company','=',$user->companyName)
            ->first();

        $transunionIndividualDeeds = $prices->transunion_principal_deeds;
        return View::make('xds-test')
            ->with('transunionIndividualDeeds',$transunionIndividualDeeds)
            ->with('user',$user);
    }

    public function serverXDS()
    {
        //assign values to variables
        $strUser = "Statusdata_uat";
        $strPwd = "93eb1864";

        $client = new SoapClient ("https://www.uat.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
        $parameters = array ("strUser"=>$strUser, "strPwd"=>$strPwd);
        $configQry = $client->Login ($parameters);
        //remove special characters
        $ticket = preg_replace ("~/~", "\\\\", $configQry->LoginResult);

        $ConnectTicket = $ticket;
        $EnquiryReason = "bbbb";
        $ProductId = "15";
        $IdNumber = "9110250459086";
        $PassportNo = "";
        $FirstName = "Rachael";
        $Surname = "Maphopha";
        $BirthDate = '1991-10-25';
        $YourReference = "iiii";
        $VoucherCode = "jjjj";
        $client = new SoapClient ("https://www.uat.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
        $parameters = array (
            "ConnectTicket"=>$ConnectTicket,"EnquiryReason"=>$EnquiryReason,"ProductId"=>$ProductId,"IdNumber"=>$IdNumber,"PassportNo"=>$PassportNo,"FirstName"=>$FirstName,"Surname"=>$Surname,"BirthDate"=>$BirthDate,"YourReference"=>$YourReference,
            "VoucherCode"=>$VoucherCode);
        $configQry = $client-> ConnectConsumerMatch ($parameters);

        /*$ConnectTicket = $ticket;
        $Reg1 = '2017'; //year : 4 digits
        $Reg2 = "058369"; //6 digits
        $Reg3="07"; //type of business: 2 digit
        $BusinessName ="Status Data (Pty) Ltd";
        $VatNo ='';
        $ProductId = "12";
        $SolePropID ='9110250459086';
        $YourReference ='';
        $VoucherCode ='';
        $client = new SoapClient ("https://www.uat.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
        $parameters = array (
            "ConnectTicket"=>$ConnectTicket,'Reg1'=>$Reg1,'Reg2'=>$Reg2,'Reg3'=>$Reg3,"ProductId"=>$ProductId,'BusinessName'=>$BusinessName,'VatNo'=>$VatNo,'SoleProID'=>$SolePropID,'YourReference'=>$YourReference, 'VoucherCode' => $VoucherCode);
        $configQry = $client-> ConnectBusinessMatch ($parameters);
        //remove special characters
        //$configXML = preg_replace ("~/~", "\\\\", $configQry); */

        /*
        $ConnectTicket = $ticket;
        $Reg1 = '2017';
        $Reg2 = "058369";
        $Reg3="07";
        $BusinessName ="Status Data (Pty) Ltd";
        $VatNo ="";
        $SolePropID ="";
        $YourReference ="";
        $VoucherCode ="";
        $client = new SoapClient ("https://www.uat.xds.co.za/xdsconnect/XDSConnectWS.asmx?WSDL");
        $parameters = array (
            "ConnectTicket"=>$ConnectTicket,'Reg1'=>$Reg1,'Reg2'=>$Reg2,'Reg3'=>$Reg3,'BusinessName'=>$BusinessName,'VatNo'=>$VatNo,'SoleProID'=>$SolePropID,'YourReference'=>$YourReference);
        $configQry = $client-> ConnectBusinessMatch ($parameters); */

        dd(json_decode($configQry->getBody()->getContents()));

    }

    public function ConnectGetBankNames()
    {
        //assign values to variables
        $ticketNo = '123';
        $client = new SoapClient ('http://webserviceurl?WSDL');
        $parameters = array ("ConnectGetBankNames"=>$ticketNo);
        $configQry = $client-> ConnectTicket($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectTicketResult);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";
    }

    public function ConnectGetAccountTypes()
    {
        //assign values to variables
        $ticketNo = "xxxx";
        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectGetAccountTypes"=>$ticketNo);
        $configQry = $client-> ConnectTicket ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectTicketResult);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";
    }

    public function ConnectGetTerms()
    {
        //assign values to variables
        $ticketNo = "xxxx";
        $ProductID = 44;
        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectTicket"=>$ticketNo,$ProductID);
        $configQry = $client-> ConnectGetTerms ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectGetTermsResult);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";
    }

    public function ConnectGetCountryCodes()
    {
        //assign values to variables
        $ticketNo = "xxxx";
        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectGetCountryCodes"=>$ticketNo);
        $configQry = $client-> ConnectTicket ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectTicketResult);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";
    }

    public function ConnectGetBankCodeRequestType()
    {
        //assign values to variables
        $ticketNo = "xxxx";
        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectGetBankCodeRequestType"=>$ticketNo);
        $configQry = $client-> ConnectTicket ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectTicketResult);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";
    }

    public function ConnectBCGetBankNames()
    {
        //assign values to variables
        $ticketNo = "xxxx";
        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectBCGetBankNames"=>$ticketNo);
        $configQry = $client-> ConnectTicket ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectTicketResult);
        //To view you’re returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars ($configXML)."]."<br><br>";
    }

    public function ConnectGetResult()
    {
        //assign values to variables
        $ConnectTicket = "aaaa";
        $EnquiryID = "1111";
        $EnquiryResultID = "cccc";
        $ProductID = "dddd";
        $BonusXML = "eeee";
        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectTicket"=>$ConnectTicket,"EnquiryID"=>$EnquiryID,
        "EnquiryResultID"=>$EnquiryResultID,"ProductID"=>$ProductID,"BonusXML"=>$BonusXML);
        $configQry = $client-> ConnectGetResult ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectGetResultResult);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";
    }

    public function ConnectBankCodeRequest()
    {
        $ConnectTicket = "aaaa";
        $RequestType = "";
        $TypeOFVerification = "Individual";
        $Entity = "None";
        $IDno = "00000000000000";
        $Reg1 ="klmn";
        $Reg2 = "opqr";
        $Reg3 = "sty";
        $TrustNo = "zaab";
        $BankName = "ABSA";
        $BranchCode= "000";
        $Accno = "11111";
        $Accholder="XXXX";
        $Amount = "1234";
        $Terms = "7 Days";
        $Addinfo = "";
        $FirstName = "XXXX";
        $Surname = "XXX";
        $Company = "XXX";
        $ContactNo = "XXXX";
        $Email = "email@test.co.za";
        $VoucherCode = "";
        $ExternalRef = "";
        $Region = "Gauteng";
        $CountryCode = "ZAF";
        $sendemail = "rachael@statusdata.co.za";
        $BranchName = "Plumstead";

        $client = new SoapClient ("http://webserviceurl?WSDL"); $parameters =array ("ConnectTicket"=>$ConnectTicket,"
        BankCodeRequestType"=>$RequestType, "verficationType"=> $TypeOFVerification, "EntityType"=> $Entity," IDno"=> $IDno," Reg1"=> $Reg1,"Reg2"=> $Reg2,
        "Reg3"=> $Reg3, "TrustNo"=> $TrustNo,"BankName"=> $BankName,"BranchName"=> $BranchName, "BranchCode"=>$BranchCode,
        "Accno"=> $Accno,"AccHolderName"=> $Accholder,"Amount"=> $Amount, "Terms"=> $Terms,"Region"=>$Region,"BankCodeCountryCode"=>"ZAF","AdditionalInfo"=>$Addinfo," FirstName"=>$FirstName,"SurName"=>$Surname, "CompanyName"=>$Company,
        "Tel No"=>$ContactNo,"EmailAddress"=>$Email, "bsendEmail"=>$sendemail,"VoucherCode"=> $VoucherCode, "YourReference"=>$ExternalRef);

        $configQry = $client-> ConnectBankCodeRequest ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectBankCodesRequestResponse);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";


    }

    public function ConnectGetBankCodeResult()
    {
        //assign values to variables
        $ConnectTicket = "aaaa"; $EnquiryLogID = "1111";
        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectTicket"=>$ConnectTicket,"EnquiryLogID"=>$EnquiryLogID);
        $configQry = $client-> ConnectGetBankCodeResult ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectGetBankCodeResultResult);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";
    }

    public function ConnectAccountVerification()
    {
        //assign values to variables
        $ConnectTicket ="aaaa"; $TypeOFVerification ="Individual"; $Entity ="None";
        $Initial = "xx";
        $Surname = "XXX";
        $IDno = "00000000000000";
        $CompanyName ="";
        $Reg1 ="";
        $Reg2 = "";
        $Reg3 = "";
        $TrustNo = "";
        $Accno = "11111";
        $BranchCode= "000";
        $Acctype = "Savings Account";
        $BankName = "ABSA";
        $Addinfo = "";
        $CFirstName = "XXXX";
        $CSurname = "XXX";
        $CEmail = "email@test.co.za";
        $VoucherCode = "";
        $ExternalRef = "";
        $sendemail = 'rachael@statusdata.co.za';
        $BranchName = "Branch";

        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectTicket"=>$ConnectTicket,"verficationType"=> $TypeOFVerification,
            " EntityType"=> $Entity,"Initials" => $Initial,"SurName"=>$Surname," IDno"=> $IDno,
            "CompanyName"=>$CompanyName, "Reg1"=> $Reg1,"Reg2"=> $Reg2,"Reg3"=> $Reg3,
            "TrustNo"=> $TrustNo,"BranchName"=> $BranchName,"Accno"=> $Accno,
            "BranchCode"=> $BranchCode,"Acctype"=> $Acctype," BankName"=> $BankName,
            "ClientFirstName"=>$CFirstName,"ClientSurName"=>$CSurname,"EmailAddress"=>$CEmail,
            "bsendEmail"=>$sendemail,"VoucherCode"=> $VoucherCode,"YourReference"=>$ExternalRef);
    $configQry = $client-> ConnectAccountVerification ($parameters);
    //remove special characters
    $configXML = ereg_replace("&", "AND", $configQry->
    ConnectAccountVerificationResponse);
    //To view your returned results, use:
    //echo "<br><br>resultXML
    [".htmlspecialchars($configXML)."]."<br><br>";
        }

    public function ConnectGetAccountVerificationResult()
    {
        //assign values to variables
        $ConnectTicket = "aaaa"; $EnquiryLogID = "1111";
        $client = new SoapClient ("http://webserviceurl?WSDL");
        $parameters = array ("ConnectTicket"=>$ConnectTicket,"EnquiryLogID"=>$EnquiryLogID);
        $configQry = $client-> ConnectGetAccountVerificationResult ($parameters);
        //remove special characters
        $configXML = ereg_replace ("&", "AND", $configQry->ConnectGetAccountVerificationResultResult);
        //To view your returned results, use:
        //echo "<br><br>resultXML
        [".htmlspecialchars($configXML)."]."<br><br>";
    }

    public function slack()
    {

        $recipes = DB::table('recipies')
            ->get();

        foreach($recipes as $recipe)
        {
            $slack = str_replace(' ','-',$recipe->title);
            DB::table('recipies')
                ->where('id','=', $recipe->id)
                ->update(array(
                        'slack' => $slack
                    )
                );
        }

    }
}
