<?php

class PagesController extends BaseController {

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

    ];

    protected static $rules2 = [
        'email' => 'required|email',
        'query' => 'required'

    ];

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

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

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

    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('rachael@mybusinessvault.co.za', 'Rachael')->subject('Prestige Enquiry');
            $message->from('no-reply@prestige.co.za');
        });

        return Redirect::to('/dashboard')->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;

            if(Input::get('email')=='admin@statusdata.co.za')
            {
                return Redirect::to('management-dashboard');
            }
            else
            {
                return Redirect::intended('/dashboard');
            }
        }

        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();
        return Redirect::to('/');
    }

    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 = "1.0";
        $params->request->pInputType = "XML";
        $params->request->pTranType = "BCS";
        $params->request->pRequestType = "BCE";
        $params->request->pEmailAddress = Input::get('email');
        $params->request->pTransaction = "<BANK_CODE_TRANSACTION>
                        <RECORDS>
                            <RECORD>
                                <BRANCH_CODE>$request->branchCode</BRANCH_CODE>
                                <ACCOUNT_NUMBER>$request->accountNumber</ACCOUNT_NUMBER>
                                <BANK>$request->bank </BANK>
                                <AMOUNT>$request->amount</AMOUNT>
                                <CLIENT_REF>$request->id</CLIENT_REF>
                                <TERMS>$request->terms</TERMS>
                                <BRANCH_NAME>$request->branchName</BRANCH_NAME>
                                <COUNTRY_SHORT_CODE>$request->country</COUNTRY_SHORT_CODE>
                                <RECORD_NUM>1</RECORD_NUM>
                                <CLIENT_NAME>$request->name</CLIENT_NAME>
                                <ID_NUMBER>$request->idNumber</ID_NUMBER>
                            </RECORD>
                        </RECORDS>
                    </BANK_CODE_TRANSACTION>";

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

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

        if($result->transactionCompleted){

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

            $request->jobId = $xml->JOB_ID;
            $request->status = $xml->JOB_STATUS_DES;
            $request->save();

        }

        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>62001636606</ACCOUNT_NUMBER>
                                <CLIENT_REF>1234</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;

        $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->request = new StdClass();
        $params->request->pUsername = "77802-1";
        $params->request->pPassword = "";
        $params->request->pMyOrigin = "StatusData";
        $params->request->pVersion = "1.0";
        $params->request->pSubmissionType = "RS";
        $params->request->pFileContent = "<AVS_TRANSACTION>
                    <VERSION>1.0</VERSION>
                    <DATE_CREATED>20171001</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_TRANSACTION>
        ";

        $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;
        dd($result);
        $jobId="";
        $jobStatusDescription="";
        $dateCreated="";

        if($result->transactionCompleted){

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

            $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);
        }
        dd($result);
        return Redirect::to('dashboard')->with('view-success', ' SUCCESS: AVRS request sent');

    }

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

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

    public function newUser()
    {
        return View::make('users.new-user');
    }

    public function CreateNewUser()
    {

        $validator = Validator::make(Input::all(),
            [
                'name' => 'required',
                'email' => 'required',
                'password' => 'required',
                'password1' => '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);
        }

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

        $user->save();

        return Redirect::to('manage-users')->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('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'))
                    )
                );
        }

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

    public function serveEditUser($user)
    {
        $user = DB::table('users')
            ->where('id','=',$user)
            ->first();
        return View::make('users.edit-user', compact('user'));
    }

    public function deleteUser($user)
    {
        DB::table('users')
            ->where('id','=',$user)
            ->delete();
        return Redirect::to('manage-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('name', 'LIKE', '%' . $query . '%')//name
            ->paginate(10);

        $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('admin.user-search')
                ->with('currentUser', $currentUser)
                ->with('users',$users);

        }

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

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

    public function serverSetPricing()
    {
        return View::make('invoice.set-pricing');
    }

    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('rachael@mybusinessvault.co.za','Rachael Maphopha')->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 = [
        'business_name' => 'required',
        'registration_number' => 'required',
        'industry' => 'required',
        'insured_book_amount' => 'required',
        'current_overdue_amount' => 'required',
        'percentage_overdue' => 'required',
        'contact_person' => 'required',
        'debtors' => 'required',
        'previous_insurer' => 'required',
        'current_insurer' => 'required',
        'telephone' => 'required',
        'cell' => 'required',
        'email' => 'required|email',
        'physical_address' => 'required',
        'postal_address' => '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->business_name = Input::get('business_name');
        $insuranceApplication->registration_number = Input::get('registration_number');
        $insuranceApplication->industry = Input::get('industry');
        $insuranceApplication->insured_book_amount = Input::get('insured_book_amount');
        $insuranceApplication->current_overdue_amount = Input::get('current_overdue_amount');
        $insuranceApplication->percentage_overdue = Input::get('percentage_overdue');
        $insuranceApplication->debtors = Input::get('debtors');
        $insuranceApplication->previous_insurer = Input::get('previous_insurer');
        $insuranceApplication->current_insurer = Input::get('current_insurer');
        $insuranceApplication->contact_person = Input::get('contact_person');
        $insuranceApplication->telephone = Input::get('telephone');
        $insuranceApplication->fax = Input::get('fax');
        $insuranceApplication->cell = Input::get('cell');
        $insuranceApplication->email = Input::get('email');
        $insuranceApplication->physical_address = Input::get('physical_address');
        $insuranceApplication->postal_address = Input::get('postal_address');

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

        }

        $insuranceApplication->save();
        /*

        if (count($insuranceApplication) < 1) {
            App::abort(404);
        }

        $pdf = \PDF::loadView('pdf.insuranceApplication', [
            'insuranceApplication' => $insuranceApplication
        ]);
        use($pdf)
        */

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

        Mail::send('emails.insuranceApplication', $data, function($message) use ($insuranceApplication)
        {
            $message->to('rachael@mybusinessvault.co.za','Rachael Maphopha')->to('insure@collectionsonline.co.za','Online Collections')->to('koketso.maphopha@gmail.com','Koketso')->subject('Insurance Quote Request');
            $message->from('no-reply@prestige.co.za');
            $message->attach($insuranceApplication->ageAnalysis);

        });



        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('no-reply@prestige.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()
    {
        return View::make('management.management-dashboard');
    }

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

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

    public function serverTransactionList($id)
    {
        $avsrs = DB::table('avsrs')
            ->where('user_id','=',$id)
            ->get();

        $bcss = DB::table('bcss')
            ->where('user_id','=',$id)
            ->get();

        $ofss = DB::table('ofss')
            ->where('user_id','=',$id)
            ->get();

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

        return View::make('management.transation-list')
            ->with('client',$client)
            ->with('avsrs',$avsrs)
            ->with('bcss',$bcss)
            ->with('ofss', $ofss);

    }

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

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

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

    public function handleEditPricing($id)
    {
        $validator = Validator::make(Input::all(),
            [
                'bcd' => 'required',
                'company_deeds' => '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('credit_check2_BCD')) {
            DB::table('pricing')
                ->where('id','=', $id)
                ->update(array(
                        'credit_check2_BCD' => Input::get('credit_check2_BCD')
                    )
                );
        }

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

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

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

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

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

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

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

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

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

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

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

        return Redirect::to('manage-invoices')->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);

            $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);
        }
        dd($result);
        return Redirect::to('dashboard')->with('view-success', ' SUCCESS: AVRS request sent');

    }

    public function serverGenerateInvoice($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 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);
        //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);

        if($webservice->pingServer())
        {

            $response = $webservice->CompanyPossibleSearch($params);
        }
        else{
            echo "Server offline. Please try again later";
        }

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

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

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

            DB::table('companies')
                ->where('id','=', $request->id)
                ->update(array(
                        'equiryID' => $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.possible-match-result')
            ->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>$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->CompanyFullSearch($params);

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

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

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

        }
    }

    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->refCompany2 = Input::get('refCompany2');
        $request->termRef2 = Input::get('termRef2');
        $request->creditLimitRef2 = Input::get('creditLimitRef2');
        $request->contact2 = Input::get('contact2');
        $request->refCompany3 = Input::get('refCompany3');
        $request->termRef3 = Input::get('termRef3');
        $request->creditLimitRef3 = Input::get('creditLimitRef3');
        $request->contact3 = Input::get('contact3');
        $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();

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

        Mail::send('emails.researchedReport', $data, function($message) use ($request)
        {
            $message->to('koketso.maphopha@gmail.com','Koketso')->to('sgilmore@statusdata.co.za','Stephen')->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 serverCompuscanReports()
    {
        return View::make('compuscan.compuscan-reports');
    }
    

}
