<?php


if ($_SERVER["REQUEST_METHOD"] == "POST") {

    function clean($value = "") {
        $value = trim($value);
        $value = stripslashes($value);
        $value = strip_tags($value);
        $value = htmlspecialchars($value);
        $value = str_replace(";", ",", $value);
        return $value;
    }

    function _isCurl(){
        return function_exists('curl_version');
    }

    // if (is_file(realpath('../system/index.php'))) {
     //    require_once(realpath('../system/index.php'));
    // }

    $API_LINKS = [
        "verify" => "http://newapi.quiktrak.co/Common/V1/Activation/Verify",
        "activation" => "http://newapi.quiktrak.co/Common/v1/Activation/Activation",
    ];


    $today=date("Y-m-d");
    $time=date("H:i:s");
    $file = "../logs/log_activation.csv";
    $fileError = "../logs/log_error.csv";

    $projectTypeNumber  = clean($_POST["projectTypeNumber"]);
    $dealerToken    = clean($_POST["dealerToken"]);
    $dealerName     = clean($_POST["dealerName"]);
    $account        = clean($_POST["account"]);
    //$password       = clean($_POST["password"]);
    $imei           = $_POST["imei"];
    $name           = clean($_POST["name"]);
    $registration   = clean($_POST["registration"]);
    $describe1      = clean($_POST["describe1"]);
    $describe2      = clean($_POST["describe2"]);
    $describe3      = clean($_POST["describe3"]);
    $describe4      = clean($_POST["describe4"]);
    $servicePlanCode= clean($_POST["servicePlanCode"]);
    $servicePlan    = clean($_POST["servicePlan"]);
    $servicePlanType= clean($_POST["servicePlanType"]);
    $countryCode    = clean($_POST["countryCode"]);
    $country        = clean($_POST["country"]);
    $phoneCode      = clean($_POST["phoneCode"]);
    $mobile         = clean($_POST["mobile"]);
    $email          = clean($_POST["email"]);
    $domain         = clean($_POST["domain"]); //"quikprotect.co";

    $paymentTypeCode    = clean($_POST["paymentTypeCode"]);
    $paymentType        = clean($_POST["paymentType"]);

    $payment1           = clean($_POST["payment1"]);
    $payment2           = clean($_POST["payment2"]);
    $payment3           = clean($_POST["payment3"]);
    $payment4           = clean($_POST["payment4"]);
    if(!empty($_POST["payment5"])){
		$payment5       = clean($_POST["payment5"]);
	}else{
		$payment5       = null;
	}
    $autosuspend = clean($_POST["autosuspend"]);
    $solutionCode = clean($_POST["solutionCode"]);
    $solution = clean($_POST["solution"]);
    //$deviceType = clean($_POST["deviceType"]);
    $fitoptions = clean($_POST["fitoptions"]);

    $assetType = clean($_POST["assetType"]);
    $instalLocation = clean($_POST["instalLocation"]);
    $notes = clean($_POST["notes"]);
    $isDeviceInstalled = clean($_POST["isDeviceInstalled"]);
    $initialMileage = clean($_POST["initialMileage"]);
    $initialEngineHours = clean($_POST["initialEngineHours"]);

  $Input1 = clean($_POST["Input1"]);
  $Input1MaskTime = clean($_POST["Input1MaskTime"]);
  $Input1Type = clean($_POST["Input1Type"]);

  $Input2 = clean($_POST["Input2"]);
  $Input2MaskTime = clean($_POST["Input2MaskTime"]);
  $Input2Type = clean($_POST["Input2Type"]);

  $LowerPower = clean($_POST["LowerPower"]);
  $DisconnectPower = clean($_POST["DisconnectPower"]);
  $IgnitionPower = clean($_POST["IgnitionPower"]);

    if (_iscurl()){

        $postfields = [
            "IMEI" => $imei,
            "Account" => $account,
            "ServiceProfile" => $servicePlanCode,
            "Solution" => $solutionCode
        ];
        if (!empty($dealerToken)) {
            $postfields['DealerToken'] = $dealerToken;
        }
        if ($paymentTypeCode == '4') { //voucher
            $postfields['Voucher'] = $payment1;
        }

        $data = [
            "url" => $API_LINKS['verify'],
            "postfields" => $postfields,
        ];

        $result = Request($data);

        $MajorCode = $result->{'MajorCode'};
        if ($MajorCode == '100') {    //unSuccess

            /*$Data = $result->{"Data"};
            $dealerToken = $Data->{"DEALER_TOKEN"};
            $CustomerToken = $Data->{"CUSTOMER_TOKEN"}; */
            $Data = $result->{"Data"};
            $dealerTokenCheck = $Data->{"DEALER_TOKEN"};
            $customerType = $Data->{"CUSTOMER_TYPE"};
            $voucherCheck = $Data->{"VOUCHER"};
            $errorMsg = '';

            if ($dealerTokenCheck == 'NO AUTHORIZATION' ) {
                echo json_encode( [ 'replyCode' => '1005', 'msg'=>'Current IMEI not authorized to be activated with selected Solution Type', 'postfields'=>$postfields, 'serverResult'=>$result ] );
                exit;
            }
            if ($dealerTokenCheck == 'ERROR' ) {
              echo json_encode( [ 'replyCode' => '1005', 'msg'=>'Dealer Error', 'postfields'=>$postfields, 'serverResult'=>$result ] );
              exit;
            }
            if ($customerType == "CUSTOMER_TYPE_ERROR") {
               echo json_encode( [ 'replyCode' => '1005', 'msg'=>'Client Account Type Error', 'postfields'=>$postfields, 'serverResult'=>$result ] );
                exit;
            }
            if ($Data->{"SIMNO"} == "INCORRECT") {
               echo json_encode( [ 'replyCode' => '1005', 'msg'=>'Asset Device has incorrect SIM number', 'postfields'=>$postfields, 'serverResult'=>$result ] );
                exit;
            }
            if ($Data->{"SOLUTION"} == "NO PERMISSION") {
              echo json_encode( [ 'replyCode' => '1005', 'msg'=>'No permission to activate selected solution', 'postfields'=>$postfields, 'serverResult'=>$result ] );
              exit;
            }
            if ($voucherCheck) {
                switch ($voucherCheck) {
                    case 'ERROR_NUMBER':
                        $errorMsg = 'Invalid Subscription Code.</br>';
                        break;

                    case 'ERROR_STATE':
                        $errorMsg = 'Subscription Code has been activated.</br>';
                        break;

                    case 'ERROR_SOLUTION':
                        $errorMsg = 'Subscription Solution Type is different from selected Solution Type.</br>';
                        break;

                    case 'ERROR_SERVICE':
                        $errorMsg = 'Subscription Service Plan is different from selected Service Plan.</br>';
                        break;

                    case 'ERROR_NULL':
                        $errorMsg = 'Subscription Code has been removed.</br>';
                        break;

                    case 'ERROR_NOSTOCK':
                        $errorMsg = 'IMEI cannot be activated with subscription code.</br>';
                        break;
                }
                if ($errorMsg) {
                    echo json_encode( [ 'replyCode' => '1005', 'msg'=>$errorMsg, 'postfields'=>$postfields, 'serverResult'=>$result ] );
                    exit;
                }
            }

            echo json_encode( [ 'replyCode' => '1005', 'msg'=>'Wrong Login Name', 'serverResult'=>$result, 'postfields' => $postfields] );
            exit;
        }else if ($MajorCode == '000'){   // Success

            $Data = $result->{"Data"};
            $StatusIMEI = $Data->{"IMEI"};
            $dealerTokenCheck = $Data->{"DEALER_TOKEN"};
            $CustomerToken = $Data->{"CUSTOMER_TOKEN"};
            $UserToken = $Data->{"USER_TOKEN"};
            $StatusAccount = $Data->{"ACCOUNT"};
            $Operator = $Data->{"OPERATOR"};
            $DeviceType = $Data->{"DEVICETYPE"};

            if ($StatusIMEI == "UNFOUND") {
                echo json_encode( [ 'replyCode' => '1002', 'msg'=>'IMEI not found', 'serverResult'=>$result ] );
                exit;
            }else if($StatusIMEI == "ACTIVATED"){
                echo json_encode( [ 'replyCode' => '1002', 'msg'=>'This device has already been activated. If you require further assistance, please contact your agent, or lodge a support ticket.', 'serverResult'=>$result ] );
                exit;
            }

            if ($dealerTokenCheck == "ERROR") {
                echo json_encode( [ 'replyCode' => '1002', 'msg'=>'Sorry, but IMEI do not belong to current dealer', 'serverResult'=>$result ] );
                exit;
            }

            if ($CustomerToken == "ERROR") {
                echo json_encode( [ 'replyCode' => '1002', 'msg'=>'No permission', 'serverResult'=>$result ] );
                exit;
            }

            if ($StatusAccount == "UNFOUND") {
                echo json_encode( [ 'replyCode' => '1005', 'msg'=>'Login Name not registered', 'serverResult'=>$result ] );
                exit;
            }

            $postfields = [
                "IMEI" => $imei,
                "Name" => $name,
                "Registration" => $registration,
                "Describe1" => $describe1,
                "Describe2" => $describe2,
                "Describe3" => $describe3,
                "Describe4" => $describe4,
                "ServiceProfile" => $servicePlanCode,
                "CustomerToken" => $CustomerToken,
                "DealerToken" => $dealerToken,
                "UserToken" => $UserToken,
                "CustomVal5" => $servicePlan,
                "CustomVal7" => $domain,
                //"Description" => 0,
                "AutoSuspend" => $autosuspend,
                "Solution" =>  $solutionCode,
                "Features" =>  $fitoptions,
                "DeviceInstalled" => $isDeviceInstalled,
            ];



            if ($servicePlanCode != '0000000000000' && $servicePlanCode != 'QUIKLOC800000' ) {
            	$postfields["PaymentType"] = $paymentType;
                $postfields["CustomField1"] = $payment1;
                $postfields["CustomField2"] = $payment2;
                $postfields["CustomField3"] = $payment3;
                $postfields["CustomField4"] = $payment4;
                $postfields["CustomField5"] = $payment5;
            }

            if(isset($assetType)){
                $postfields["AssetType"] = $assetType;
            }
            if(isset($instalLocation)){
                $postfields["InstallLocation"] = $instalLocation;
            }
            if(isset($notes)){
                $postfields["Notes"] = $notes;
            }
            if(isset($initialMileage)){
                $postfields["InitMileage"] = $initialMileage;
            }
            if(isset($initialEngineHours)){
                $postfields["InitAccHours"] = $initialEngineHours;
            }

          if(isset($_POST["Input1"])){
            $postfields["Input1Name"] = $Input1;
          }
          if(isset($_POST["Input1MaskTime"])){
            $postfields["Input1Mask"] = $Input1MaskTime;
          }
          if(isset($_POST["Input1Type"])){
            $postfields["Input1Type"] = $Input1Type;
          }
          if(isset($_POST["Input2"])){
            $postfields["Input2Name"] = $Input2;
          }
          if(isset($_POST["Input2MaskTime"])){
            $postfields["Input2Mask"] = $Input2MaskTime;
          }
          if(isset($_POST["Input2Type"])){
            $postfields["Input2Type"] = $Input2Type;
          }
          if(isset($_POST["LowerPower"])){
            $postfields["LowerPower"] = $LowerPower;
          }
          if(isset($_POST["DisconnectPower"])){
            $postfields["DisconnectPower"] = $DisconnectPower;
          }
          if(isset($_POST["IgnitionPower"])){
            $postfields["IgnitionPower"] = $IgnitionPower;
          }


            /*echo json_encode( [ 'replyCode' => '1002', 'msg'=>'Activation Form on maintaining, please try again in 30 min', 'prevPostData'=>$data, 'serverResult'=>$result, 'nextPostFields' => $postfields ] );
            exit;*/

            $data = [
                "url" => $API_LINKS['activation'],
                "postfields" => $postfields,
            ];
            $result = Request($data);
            /*switch ($servicePlanCode) {
                case '0000000000000':
                    $letter = 'letter/protect/v3/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    break;

                case 'QUIKLOC800000':
                    $letter = 'letter/quikloc8/v3/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    break;

                default:
                    $letter = 'letter/live/v3/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    if ($dealerName == 'GPS Tracking WA' || $Operator == 'gpswa') {
                        $letter = 'letter/live/gpstrackingwa/v2/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    }
                    break;
            }*/
            switch ($solutionCode) {
                case 'Protect':
                case 'WiTiProtect':
                case 'WiTiQProtect':
                    $letter = 'letter/protect/v3/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    break;

                case 'Loc8':
                    $letter = 'letter/quikloc8/v3/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    break;

                case 'QProtect':
                    $letter = 'letter/protect/v3/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    break;

                default:
                    $letter = 'letter/live/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    if ($dealerName == 'GPS Tracking WA' || $Operator == 'gpswa') {
                        $letter = 'letter/live/gpstrackingwa/v2/?p=h&ac='.$account.'&at='.$assetType.'&st='.$solution.'&sp='.$servicePlan;
                    }
                    break;
            }

            $MajorCode = $result->{'MajorCode'};
            if ($MajorCode == '100') {    //unSuccess
                $Data = $result->{'Data'};
                $errorMsg = '';
                if (!empty($Data)) {
                    foreach ($Data as $key => $value){
                        if ($value->Key == 'IMEI') {
                            foreach ($value->Messages as $key1 => $value1){
                                if ($value1 == "PRODUCT_TYPE_ERROR") {
                                    $errorMsg .= 'The device type is incorrect, refer to your dealer, please.</br>';
                                }
                            }
                        }else if($value->Key == 'VOUCHER'){
                            foreach ($value->Messages as $key1 => $value1){
                                switch ($value1) {
                                    case 'ERROR_NUMBER':
                                        $errorMsg .= 'Invalid Subscription Code.</br>';
                                        break;

                                    case 'ERROR_STATE':
                                        $errorMsg .= 'Subscription Code has been activated.</br>';
                                        break;

                                    case 'ERROR_SOLUTION':
                                        $errorMsg .= 'Subscription Solution Type is different from selected Solution Type.</br>';
                                        break;

                                    case 'ERROR_SERVICE':
                                        $errorMsg .= 'Subscription Service Plan is different from selected Service Plan.</br>';
                                        break;

                                    case 'ERROR_NULL':
                                        $errorMsg .= 'Subscription Code has been removed.</br>';
                                        break;

                                    case 'ERROR_NOSTOCK':
                                        $errorMsg .= 'IMEI cannot be activated with subscription code.</br>';
                                        break;

                                }
                            }
                        }
                    }
                    if (!empty($errorMsg)) {
                        //SaveErrorToLog($result, $data);
                        echo json_encode( [ 'replyCode' => '1000', 'msg'=>$errorMsg, 'serverResult'=>$result, 'postfields' => $postfields ] );
                        exit;
                    }else{
                        //SaveErrorToLog($result, $data);
                        echo json_encode( [ 'replyCode' => '9999', 'msg'=>'Device has issues with preset data', 'serverResult'=>$result, 'postfields' => $postfields ] );
                        exit;
                    }
                }else{
                    //SaveErrorToLog($result, $data);
                    echo json_encode( [ 'replyCode' => '1000', 'msg'=>'Device has issues with preset data', 'serverResult'=>$result, 'postfields' => $postfields ] );
                    exit;
                }
            }else if($MajorCode == '000'){
                echo json_encode( [ 'replyCode' => '000', 'msg'=>'Thanks for choosing us. Your device is now being activated!', 'serverResult'=>$result, 'letter'=>$letter, 'postfields' => $postfields ] );
              //  seaveToDB();
            }else{
                //SaveErrorToLog($result, $data);
                echo json_encode( [ 'replyCode' => '9999', 'msg'=>'Device has issues with preset data', 'serverResult'=>$result, 'postfields' => $postfields ] );
            }


        }else{
            //SaveErrorToLog($result, $data);
            echo json_encode( [ 'replyCode' => '1005', 'msg'=>$MajorCode = $result->{'MajorCode'}, 'serverResult'=>$result ] );
            exit;
        }
    }else{
      echo json_encode( [ 'replyCode' => '1000', 'msg'=>'Set up Curl'] );
    }

}

function SaveErrorToLog($param1, $param2){
    global $today, $time, $fileError;

    if(file_exists($fileError)){$fp = fopen("$fileError","a")or die("файл не открылся");}else{$fp = fopen("$fileError","w") or die("файл не создался");}

    $txt = $today . ';' . $time . ';' . json_encode($param1, JSON_UNESCAPED_UNICODE) . ';' . json_encode($param2, JSON_UNESCAPED_UNICODE) . "\r\n"; // Исходная строка

    $csv = fwrite($fp, $txt); // Запись в файл
    fclose($fp); //Закрытие файла
}


function Request($args){
    $url = $args['url'];
    $postfields = $args['postfields'];

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 90,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => http_build_query($postfields),
        CURLOPT_HTTPHEADER => array(
          "content-type: application/x-www-form-urlencoded"
        ),
    ));

    $jsonResult = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        echo json_encode( array( 'replyCode' => '1000', 'msg'=>$err, 'requestUrl'=> $url, 'requestFields' => $postfields ) );
        exit;
    } else {
        $response = json_decode($jsonResult);
        return $response;
    }


   /* $request = new HttpRequest();
    $request->setUrl($args['url']);
    $request->setMethod(HTTP_METH_POST);

    $request->setHeaders(array(
      'cache-control' => 'no-cache',
      'Connection' => 'keep-alive',
      'content-length' => '142',
      'accept-encoding' => 'gzip, deflate',
      'Host' => 'newapi.quiktrak.co',
      'Postman-Token' => 'd18e46c2-09a4-47cd-b960-1e2aa8d3ce68,401cef2a-780d-476a-8277-5c3c73093ff3',
      'Cache-Control' => 'no-cache',

      'User-Agent' => 'PostmanRuntime/7.15.0',
      'Content-Type' => 'application/x-www-form-urlencoded'
    ));

    $request->setContentType('application/x-www-form-urlencoded');
    $request->setPostFields($args['postfields']);

    try {
      //$response = $request->send();

      //echo $response->getBody();
        $response = json_decode($jsonResult);
        return $response;
    } catch (HttpException $ex) {
      //echo $ex;
         echo json_encode( array( 'replyCode' => '1001', 'msg'=>$err, 'requestUrl'=> $url, 'requestFields' => $postfields ) );
        exit;
    }*/

}

function seaveToDB(){
    global $file, $today, $time, $projectTypeNumber, $dealerToken, $dealerName, $account, $imei, $name, $describe1, $describe2, $describe3, $describe4, $servicePlanCode, $servicePlanType, $servicePlan, $countryCode, $country, $mobile, $phoneCode, $email, $Operator, $db, $paymentTypeCode, $paymentType, $payment1, $payment2, $payment3, $payment4, $payment5, $DeviceType, $autosuspend, $solutionCode, $solution, $fitoptions, $assetType;

    if(file_exists($file)){$fp = fopen("$file","a")or die("файл не открылся");}else{
      $fp = fopen("$file","w") or die("файл не создался");
    }
    $txt = $today.";".$time.";".$projectTypeNumber.";".$dealerToken.";".$dealerName.";".$account.";".$imei.";"
        .$name.";".$describe1.";".$describe2.";".$describe3.";".$describe4.";"
        .$servicePlanCode.";".$servicePlan.";".$servicePlanType.";".$countryCode.";".$country.";".$phoneCode.";".$mobile.";".$email.";"
        .$paymentTypeCode.";".$paymentType.";".$payment1.";".$payment2.";".$payment3.";".$payment4.";".$payment5.";"
        .$Operator.";".$DeviceType.";".$autosuspend.";".$solutionCode.";".$solution.";".$fitoptions.";".$assetType.";\r\n"; // Исходная строка
    $csv = fwrite($fp, $txt); // Запись в файл
    fclose($fp); //Закрытие файла


    if (is_file(realpath('../system/index.php'))) {
       require_once(realpath('../system/index.php'));
    }

    $Operator = strtolower($Operator);
    $phone = $phoneCode.$mobile;

    if ($servicePlanCode == '0000000000000') {  //Protect

        switch ($Operator) {
            case 'mep':
                $sql = "INSERT INTO motorone_quikprotect_activations (activation_date,imei,email,account,phone,country_code,country,registration_number,vehicle_make,vehicle_model,vehicle_color,vehicle_year,dealer_name, device_type,dealer_token,operator,autosuspend,solution_code,solution) VALUES ( '".time()."','".$imei."','".$email."','".$account."','".$phone."','".$countryCode."','".$country."','".$name."','".$describe1."','".$describe2."','".$describe3."','".$describe4."','".$dealerName."','".$DeviceType."','".$dealerToken."','".$Operator."','".$autosuspend."','".$solutionCode."','".$solution."' )";
                break;

            default:
                $sql = "INSERT INTO quikprotect_activations (activation_date,imei,email,account,phone,country_code,country,registration_number,vehicle_make,vehicle_model,vehicle_color,vehicle_year,dealer_name, device_type,dealer_token,operator,autosuspend,solution_code,solution) VALUES ( '".time()."','".$imei."','".$email."','".$account."','".$phone."','".$countryCode."','".$country."','".$name."','".$describe1."','".$describe2."','".$describe3."','".$describe4."','".$dealerName."','".$DeviceType."','".$dealerToken."','".$Operator."','".$autosuspend."','".$solutionCode."','".$solution."' )";
                break;
        }



        $query = $db->query($sql);
       /* echo json_encode( [ 'replyCode' => '1002', 'msg'=>'All OK!', 'sql' => $sql ] );
        exit;*/

    }else{                                      //Live
        $purchsed_date_conv = strtotime($today);   // convert date to int format

        switch ($Operator) {
            case 'easytrack':
                $projectTypeNumber = 6;
                break;
            case 'ttcadmin':
                $projectTypeNumber = 11;
                break;
            case 'cubevoice':
                $projectTypeNumber = 10;
                break;
            case 'ispygpsagent':
                $projectTypeNumber = 7;
                break;
            case 'autofidelityagent':
                $projectTypeNumber = 14;
                break;
            case 'quiktrakchile':
                $projectTypeNumber = 4;
                break;
            case 'quiktrakukraine':
                $projectTypeNumber = 3;
                break;
            //case 'quiktrakcolombia':
            //    $projectTypeNumber = 5;
            //    break;

        }


        switch ($Operator) {
            case 'mep':
                $projectTypeNumber = 4;
                $chosenPlanType = '1'; // Track only Annual
                switch ($servicePlanCode) {
                    case '1C783FA4TRAK':
                    case '1C8D3EDEMOTI':
                        $chosenPlanType = '1'; // 12 month
                        break;
                    case '2Y6Z8YPFC8P2Y':
                        $chosenPlanType = '2'; // 24 month
                        break;
                    case '4Y6Z8YPFC8P4Y':
                        $chosenPlanType = '3'; // 36 month
                        break;
                    default:
                        $chosenPlanType = '1'; // 12 month
                }
                $sql = "INSERT INTO motorone_live_upgrade (project_type_number,upgrade_date,account_name,email,phone,country,dealer_name,purchsed_date,chosen_plan,chosen_plan_type,device_type,dealer_token,operator,autosuspend,solution_code,solution) VALUES ( '".$projectTypeNumber."','".time()."','".$account."','".$email."','".$phone."','".$country."','".$dealerName."','".$purchsed_date_conv."','".$servicePlan."','".$chosenPlanType."','".$DeviceType."','".$dealerToken."','".$Operator."','".$autosuspend."','".$solutionCode."','".$solution."' )";
                $query = $db->query($sql);
                $UserId = $db->getLastId();  //get current user id

                $sql_devices =  "INSERT INTO motorone_live_upgrades_devices (id ,imei, vehicle_device) VALUES ( '" .$UserId."','".$imei."','".$name."' )";

                $query = $db->query($sql_devices);    // seve user devices using user id in database

                break;

            default:
                $sql = "INSERT INTO upgrades (project_type_number,upgrade_date,login_name,payment_type,email,country,phone,purchsed_from,purchsed_date,chosen_plan,chosen_plan_type, device_type,dealer_token,operator,autosuspend,solution_code,solution) VALUES ( '".$projectTypeNumber."','".time()."','".$account."','".$paymentTypeCode."','".$email."','".$country."','".$phone."','".$dealerName."','".$purchsed_date_conv."','".$servicePlan."','".$servicePlanType."','".$DeviceType."','".$dealerToken."','".$Operator."','".$autosuspend."','".$solutionCode."','".$solution."' )";

                $query = $db->query($sql);
                $UserId = $db->getLastId();  //get current user id

                $sql_devices =  "INSERT INTO upgrades_devices VALUES ( '".$UserId."','".$imei."','".$name."' )";
                $query = $db->query($sql_devices);    // seve user devices using user id in database

                switch ($paymentTypeCode) {
                    case '1':
                        $sql_payment_type = "INSERT INTO upgrades_credit_cards VALUES ('".$UserId."','".$payment1."','".$payment2."','".$payment3."','".$payment4."' )";
                        break;
                    case '2':
                        $sql_payment_type = "INSERT INTO upgrades_bank_direct VALUES ('".$UserId."','".$payment1."','".$payment2."','".$payment3."','".$payment4."' )";
                        break;
                    case '4':
                        $sql_payment_type = "INSERT INTO upgrades_by_voucher (id,voucher_code) VALUES ('".$UserId."','".$payment1."' )";
                        break;
                    default:
                        $sql_payment_type = "INSERT INTO upgrades_by_invoice VALUES ('".$UserId."','".$payment1."','".$payment2."','".$payment3."','".$payment4."' )";
                        break;
                }
                $query = $db->query($sql_payment_type);

                break;
        }


    }
}

