<?php
header('Content-Type: application/json');
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'));
//}

if ($_SERVER["REQUEST_METHOD"] != "POST") {
  exit();
}

if (!_iscurl()){
  echo json_encode( [ 'replyCode' => '1000', 'msg'=>'Set up Curl'] );
  exit;
}




// retrieve JSON from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);

$API_LINKS = [
    "verify" => "https://newapi.quiktrak.co/Common/V1/Activation/VerifyTesting",
];


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

$imei               = $json_obj->imei; //$_POST["imei"];
$account            = strtolower(clean($json_obj->account)); //strtolower(clean($_POST["account"]));
$email              = clean($json_obj->email); //clean($_POST["email"]);
$servicePlanCode    = clean($json_obj->servicePlanCode); //clean($_POST["servicePlanCode"]);
$solutionCode       = clean($json_obj->solutionCode); //clean($_POST["solutionCode"]);
$dealerToken        = clean($json_obj->dealerToken); //clean($_POST["dealerToken"]);
$paymentTypeCode    = clean($json_obj->paymentTypeCode); //clean($_POST["paymentTypeCode"]);
$payment1           = clean($json_obj->payment1); //clean($_POST["payment1"]);



$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"};
  $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 ($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'=>'Asset not in inventory!', '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'=>'IMEI has already been activated', '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;
  }

  //all ok
  echo json_encode( [ 'replyCode' => '000', 'msg' =>'All OK', 'serverResult'=>$result ] );


}else{
  //SaveErrorToLog($result, $data);
  echo json_encode( [ 'replyCode' => '1006', 'msg'=>'An undefined issue has been experienced, please check the information and try again', 'url'=>$data['url'], 'postfields' => $postfields, 'serverResult'=>$result ] );
  exit;
}




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) );
        exit;
    } else {
        $response = json_decode($jsonResult);
        return $response;
    }
}