<?php
    header('Access-Control-Allow-Origin: *');
    if(count($_POST) == 0){
        http_response_code(404);
        die(json_encode(array("status"=>false,"message"=>"No Data Found")));
    }
    $vars = json_encode($_POST);
    $part = json_decode($vars);
    $phoneNumber = $part->from;
    $text = $part->text;
    require "vendor/autoload.php";
    use AfricasTalking\SDK\AfricasTalking;
    $username = 'wiaxydat'; 
    $apiKey   = '878ed2c602ec1eab94c42804e4f8529bf9f828432cdca48928d0e2f37d359999'; 
    $AT = new AfricasTalking($username, $apiKey);
    $sms = $AT->sms();
    include "../../api/konnection.php";
    include "../../api/func.php";
    $msg = $text;
    $sender = $phoneNumber;
    //FETCH AUTH DETAILS
    $entities = explode(" ",$msg);
    if(isset($entities[0])){
        $dataPin = $entities[0];
        if(!empty($dataPin) && is_numeric($dataPin) && strlen($dataPin) ==10){
            $check = mysqli_query($conn,"SELECT * FROM data_cards WHERE pin = '$dataPin'"); 
            if(mysqli_num_rows($check) > 0){
              while($row = mysqli_fetch_array($check)){
                  $status = $row["status"];
                  $data_plan = $row["pid"];
                  $network = $row["network"];
                  $plan_type = $row["ptype"];
              }
              if($status == "UNUSED"){
                $network2 = $network;
                $network = strtoupper($network);
                $service_tag = $network2."_".$plan_type;
                $priority = checkPriority($service_tag);
                $service = getAvalability($service_tag);
                $plan = getPlanDetails($data_plan);
                if($service != "ON"){
                   $sms->send(['to'=>$sender,'message' => 'Request couldn\'t be completed','from' => '34461']);
                   die(json_encode(array("status"=>false,"message"=>"Request couldn't be completed")));  
                }
                if($plan["pstatus"] != "available"){
                    $sms->send(['to'=>$sender,'message' => 'Request could not be completed','from' => '34461']);
                   die(json_encode(array("status"=>false,"message"=>"Request could not be completed")));  
                }
                $archi = checkArchi($priority);
                $getWebConfigs = getWebConfigs($service_tag);
                $url = $getWebConfigs["$priority"."_url"];
                if($archi == "MSORG"){
                  $token = $getWebConfigs["$priority"."_token"];
                  $auth["token"] = $token;
                }elseif($archi == "ADEX"){
                  $username = $getWebConfigs["$priority"."_username"];
                  $password = $getWebConfigs["$priority"."_password"];
                  $auth["username"] = $username;
                  $auth["password"] = $password;
                }else{
                   $sms->send(['to'=>$sender,'message' => 'Unfinished Setup, Contact Admin Support (ERR1)','from' => '34461']);
                   die(json_encode(array("status"=>false,"message"=>"Unfinished Setup, Contact Admin Support (ERR1)")));  
                }
                if(!filter_var($url,FILTER_VALIDATE_URL)){
                    $sms->send(['to'=>$sender,'message' => 'Unfinished Setup, Contact Admin Support (ERR2)','from' => '34461']);
                    die(json_encode(array("status"=>false,"message"=>"Unfinished Setup, Contact Admin Support (ERR2)"))); 
                }
                  mysqli_query($conn, "UPDATE data_cards SET status = 'USED', used_by = '$sender' WHERE pin = '$dataPin'");
                 if(isset($entities[1])){
                    if(!is_numeric($entities[1])){
                        $sms->send(['to'=>$sender,'message' => 'Beneficiary should be a valid number.','from' => '34461']);
                        die(json_encode(array("status"=>false,"message"=>"Beneficiary should be a valid number."))); 
                    }if(strlen($entities[1]) != 11){
                        $sms->send(['to'=>$sender,'message' => 'Beneficiary phone number should be 11 digit.','from' => '34461']);
                        die(json_encode(array("status"=>false,"message"=>"Beneficiary phone number should be 11 digit."))); 
                    }
                    $beneficiary = $entities[1];
                    $proxy = true;
                  }else{
                    $proxy = false;
                    $beneficiary = "0".substr($sender, 4); 
                  }
                  if($network == "MTN"){
                    $network_id = 1;
                    $initials = "0702 0703 0713 0704 0706 0716 0802 0803 0806 0810 0813 0814 0816 0903 0913 0906 0916 0804";
                  }elseif($network == "AIRTEL"){
                    $network_id = 2;
                    $initials = "0904 0802 0902 0702 0808 0908 0708 0918 0818 0718 0812 0912 0712 0801 0701 0901 0907 0917";
                  }elseif($network == "9MOBILE"){
                    $network_id = 4;
                    $initials = "0809 0909 0709 0819 0919 0719 0817 0917 0717 0718 0918 0818 0808 0708 0908";
                  }elseif($network == "GLO"){
                    $network_id = 3;
                    $initials = "0805 0705 0905 0807 0907 0707 0817 0917 0717 0715 0815 0915 0811 0711 0911";
                  }else{
                     $sms->send(['to'=>$sender,'message' => 'Network Unidentified','from' => '34461']);
                     die(json_encode(array("status"=>false,"message"=>"Network Unidentified"))); 
                  }
                  $init = explode(" ", $initials);
                  $beneficiaryInit = substr($beneficiary,0,4);
                   if(in_array($beneficiaryInit,$init) && strlen($beneficiary) == 11){
                      $checkForDataSize = mysqli_query($conn,"SELECT * FROM plans WHERE id = '$data_plan'"); 
                      if(mysqli_num_rows($checkForDataSize) > 0){
                         while($row = mysqli_fetch_array($checkForDataSize)){
                              $plan_name = $row["pslug"];
                              $plan_size = strtoupper($row["ptype"]);
                              $validity = strtoupper($row["pvalidity"]);
                              $check_balance = $row["checker"];
                         }
                        $dataRecharged = $plan_name." ".$plan_size;
                        // REQUIRE SWITCHING TECHNIQUE
                        $plans_holder = [
                          "msorg_a"  => "msorgA",
                          "msorg_b"  => "msorgB",
                          "msorg_c"  => "msorgC",
                          "msorg_d"  => "msorgD",
                          "adex_a"  => "adexA",
                          "adex_b"  => "adexB",
                        ];
                        $planID = $plan[$plans_holder[$priority]];

                        $networkID = getNetworkID($archi,$network2);
                        $payload = array(
                            'url' => $getWebConfigs[$priority."_url"],
                            'network' => $networkID,
                            'mobile' => $beneficiary,
                            'plan' => $planID,
                            'bypass' => true,
                            'request-id' => "DC|".$dataPin."|".date("his")
                         );
                        $vendData = new VendData();
                        if($archi == "MSORG"){
                            $purchase = $vendData->MSORGVEND($auth, $payload);
                        }elseif($archi == "ADEX"){
                            $purchase = $vendData->ADEXVEND($auth, $payload);
                        }
                        $resp = json_decode($purchase);
                        if(isset($resp->response->status) && $resp->response->status == "success"){
                            if($proxy){
                                $mes = "Data recharge of $dataRecharged to $beneficiary was successful valid for $validity. Dial $check_balance to check balance. Thanks for using our service!";
                            }else{
                                $mes = "Data recharge of $dataRecharged was successful valid for $validity. Dial $check_balance to check balance. Thanks for using our service!";
                            }
                            $sms->send(['to'=>$sender,'message' => $mes,'from' => '34461']);
                            mysqli_query($conn, "UPDATE data_cards SET status = 'USED', used_by = '$beneficiary' WHERE pin = '$dataPin'");
                            die(json_encode(array("status"=>true,"message"=>$mes)));
                        }else{
                            mysqli_query($conn, "UPDATE data_cards SET status = 'UNUSED', used_by = '$beneficiary' WHERE pin = '$dataPin'");
                            http_response_code(200);
                            $sms->send(['to'=>$sender,'message' => 'Sorry, Service unavailable, try again in a shorter while.','from' => '34461']);
                            die(json_encode(array("status"=>false,"message"=>"Sorry, Service unavailable, try again in a shorter while.")));                         }
                      }else{
                          $sms->send(['to'=>$sender,'message' => 'Contact Support, Something went wrong.','from' => '34461']);
                          die(json_encode(array("status"=>false,"message"=>"Contact Support, Something went wrong."))); 
                      }
                   }else{
                      $sms->send(['to'=>$sender,'message' => 'Phone number network not detected','from' => '34461']);
                      die(json_encode(array("status"=>false,"message"=>"Phone number network not detected"))); 
                   }
              }else{
                $sms->send(['to'=>$sender,'message' => 'PIN Already used','from' => '34461']);
                die(json_encode(array("status"=>false,"message"=>"PIN Already used")));
              }
            }else{
                $sms->send(['to'=>$sender,'message' => 'PIN is Invalid. Please try again!','from' => '34461']);
                die(json_encode(array("status"=>false,"message"=>"PIN is Invalid. Please try again!")));
            }
        }else{
            $sms->send(['to'=>$sender,'message' => 'PIN should be 10 digits length.','from' => '34461']);
            die(json_encode(array("status"=>false,"message"=>"PIN should be 10 digits length.")));
        }
    }

    
?>