<?php
    declare(strict_types=1);
    header('Access-Control-Allow-Origin: *');
    use Firebase\JWT\JWT;
    require_once('vendor/autoload.php');
    require_once('vends/Exams.php');
    $head =  json_encode(getallheaders());
	$unhead = json_decode($head, true);
	if(!isset($unhead["Authorization"])){
	    http_response_code(400);
	    die(json_encode(array("message"=>"NO_AUTH_HEADER_FOUND")));
	}
    $head = $unhead["Authorization"];
    $matches = explode(' ',$head);
    if(!isset($matches[0]) && $matches[0] != "Bearer"){
        http_response_code(400);
	    die(json_encode(array("message"=>"PATTERN_NOT_SET")));
    }
    if(!isset($matches[1])){
        http_response_code(400);
	    die(json_encode(array("message"=>"TOKEN_NOT_FOUND")));
    }
    $jwt = $matches[1];
    if(empty($jwt)){
        http_response_code(400);
	    die(json_encode(array("message"=>"TOKEN_EMPTY")));
    }
    $secretKey  = 'wt4es0cj6BIN1pokBJEVLvOGdqa3q8dBYbvzpf9MKlvllqNBdQhYbmHt8Q0TNDDzfCWAynTcKtwk50WJsi8vVOpexkMP6uqIjRLd92eWqaJupsAc9qbZ3rLZIV8qIeps';
    $token = JWT::decode($jwt, $secretKey, ['HS512']);
    $now = new DateTimeImmutable();
    $serverName = "ksbdata.com";

    $vars = json_decode(file_get_contents("php://input"));
    if(!isset($vars->exam)){
        die(json_encode(array("message"=>"Exam Not Found")));
    }if(empty($vars->exam)){
        die(json_encode(array("message"=>"Exam Empty")));
    }
    if(!isset($vars->quantity)){
        die(json_encode(array("message"=>"Quantity Not Found")));
    }if(empty($vars->quantity)){
        die(json_encode(array("message"=>"Quantity Empty")));
    }
    if(!isset($vars->cardName)){
        die(json_encode(array("message"=>"Card Name Not Found")));
    }if(empty($vars->cardName)){
        die(json_encode(array("message"=>"Card Name Empty")));
    }
    if(!isset($vars->pin)){
        die(json_encode(array("status"=>"caption","message"=>"Transaction PIN not supplied")));
    }
    $device = false;
    if(isset($vars->dev) && $vars->dev == true){
        $device = true;
    }else{
        if(strlen($vars->pin) != 4){
            die(json_encode(array("status"=>"caption","message"=>"Transaction PIN Should be 4 digits long")));
        }  
    }
    
    
    if($vars->exam == "neco"){
        $img = "img/assets/neco.png";
    }if($vars->exam == "waec"){
        $img = "img/assets/waec.png";
    }
    include "konnection.php";
    include "func.php";
    $email = $token->data->wxt;
    $now = date("Y-m-d H:i:s");
    $bal = getBal($email);
    $user = getUserDetails($email);
    $exams = getExams($vars->exam);

    if($user["status"] == 0){
      die(json_encode(array("status"=>"caption","message"=>"You've to be verified to use this service")));   
    }if($user["isban"] == 1){
      die(json_encode(array("status"=>"caption","message"=>"You're banned from using our services. Contact admin")));   
    }
    if($user["canPrintExam"] == 0){
      die(json_encode(array("status"=>"caption","message"=>"Service not available for your account. Contact admin")));   
    }
    if(!is_array($exams)){
       die(json_encode(array("status"=>"caption","message"=>"Invalid Exam ID"))); 
    }
    if($device === true){
        $hash=substr(sha1(md5($vars->pin)), 3, 10);
        if($user["password"] != $hash && strtolower($user["password"]) != strtolower($vars->pin)){
          die(json_encode(array("status"=>"caption","message"=>"Unable to validate your credentials")));   
        }
    }else{
        if($user["pin"] == ""){
          die(json_encode(array("status"=>"caption","message"=>"Transaction PIN Not Set Yet, Go to Settings to Setup your PIN")));   
        }
        $isCorrect = isTransactionPinCorrect($user["pin"],$vars->pin);
        if(!$isCorrect){
            die(json_encode(array("status"=>"caption","message"=>"Transaction PIN Invalid"))); 
        }   
    }
    $service_tag = "exam";
    $service = getAvalability($service_tag);
    if($service != "ON"){
       die(json_encode(array("status"=>"caption","message"=>"Exam PIN is not available currently")));  
    }
    
    $rolePrice = getExamRolePrice($user["role"]);
    $amount = $exams[$rolePrice];
    $amount = (int)$amount * (int)$vars->quantity;
    if($exams["estatus"] != "available"){
       die(json_encode(array("status"=>"caption","message"=>"Exam Selected Not Available")));  
    }
    $checkPriority = checkPriority($service_tag);
    $getWebConfigs = getWebConfigs();
    $archi = checkArchi($checkPriority);
    $url = $getWebConfigs["$checkPriority"."_url"];
    if($archi == "MSORG"){
      $token = $getWebConfigs["$checkPriority"."_token"];
      $auth["token"] = $token;
    }elseif($archi == "ADEX"){
      $username = $getWebConfigs["$checkPriority"."_username"];
      $password = $getWebConfigs["$checkPriority"."_password"];
      $auth["username"] = $username;
      $auth["password"] = $password;
    }elseif($archi == "VTPASS"){
      $username = $getWebConfigs["$checkPriority"."_username"];
      $password = $getWebConfigs["$checkPriority"."_password"];
      $auth["username"] = $username;
      $auth["password"] = $password;
    }else{
       die(json_encode(array("status"=>"caption","message"=>"Unfinished Setup, Contact Admin Support (ERR1)")));  
    }
    if(!filter_var($url,FILTER_VALIDATE_URL)){
        die(json_encode(array("status"=>"caption","message"=>"Unfinished Setup, Contact Admin Support (ERR2)"))); 
    }
    $examID = getExamID($archi, $vars->exam);
    $payload = [
        "url" => $url,
        "exam" => $vars->exam,
        "email" => $email,
        "id" => $examID,
        "phone" => $user["phone"],
        "quantity" => $vars->quantity,
        "date" => $now,
        "card_name" => $vars->cardName,
    ];

    if($bal >= (int)$amount){
        $new = (int)$bal - (int)$amount;
        mysqli_query($conn, "UPDATE balance SET amount = '$new' WHERE user = '$email'");
        $payExam = new VendExam();
        if($archi == "MSORG"){
            $purchase = $payExam->MSORGVEND($auth, $payload);
        }elseif($archi == "ADEX"){
            $purchase = $payExam->ADEXVEND($auth, $payload);
        }elseif($archi == "VTPASS"){
            $purchase = $payExam->VTPASSVEND($auth, $payload);
        }
        $resp = json_decode($purchase);
        if($resp->status === true){
            $pure = $resp->response;
            $id = $pure->id;
            $status = $pure->status;
            $plan_amount = $pure->amount;
            $message = $pure->response;
            $profit = (float)$amount-(float)$plan_amount;
            $slug = "(".$vars->quantity .") " . "exams";
            if($status == "success"){
                mysqli_query($conn, "INSERT INTO transactions (user,transaction_id,type,amount,balance_before,amount_charged,balance_after,profit,beneficiary,whenn,status,serviceImg,message)
                VALUES('$email','$id','Exam Purchase','$slug','$bal','$amount','$new','$profit','$vars->cardName','$now','Completed','$img','$message')");
                die(json_encode(array("status"=>true,"message"=>"Exam PIN Purchase Successful","transID"=>$id)));  
            }else{
                mysqli_query($conn, "UPDATE balance SET amount = '$bal' WHERE user = '$email'");
                mysqli_query($conn, "INSERT INTO transactions (user,transaction_id,type,amount,balance_before,amount_charged,balance_after,profit,beneficiary,whenn,status,serviceImg,message)
                VALUES('$email','$id','Exam Purchase','$slug','$bal','$amount','$bal','$profit','$vars->cardName','$now','$status','$img','$message')");
                die(json_encode(array("status"=>true,"message"=>"Exam PIN Purchase Failed, Retry Again","transID"=>$id))); 
            }
        }else{
            mysqli_query($conn, "UPDATE balance SET amount = '$bal' WHERE user = '$email'");
           die(json_encode(array("status"=>"caption","message"=>$resp->response->response)));   
        }
    }else{
       die(json_encode(array("status"=>"caption","message"=>"InSufficient Fund to perform operation")));   
    }

?>