<?php header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: *");  

  header('Content-Type: application/json');

  $json = file_get_contents('php://input');
  $obj = json_decode($json, true);

  include '../db/connectMe.php';   
  include '../function/function.php';  

  // (C) GENERATE JWT TOKEN
  require "../vendor/autoload.php";
  use Firebase\JWT\JWT;

  // (A) NO data
  if (!isset($obj["repairToken"])  ) { 

    $error = array("error"=> "no");
    exit( json_encode($error) ); 

  }

  if( AuthorizeMe(@substr(getallheaders()["Authorization"], 7)) ){

    $jwt = substr(getallheaders()["Authorization"], 7);

    //Decoding data
    $decodeToken = (json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $jwt)[1]))))->data);

    if(!isset($decodeToken)){

      exit(json_encode(array("error" => "unauthorised") ));

    }
    
    
    

    $smsData = find_sms_token_by_id();  

    $last = date( "h", strtotime($smsData->tbl_sms_dataTime));
    $current = date( "h");

    $diff = $current - $last; 

    $message = '';

    if(date("Y-m-d") ==  $smsData->tbl_sms_dataDate ){

      if($diff == 0){

        //send SMS
        //$message = 'send SMS';

      }else{

        //request new token

        if(RequestSMSToken() != 'FAILED'){
           
          //$message = '<i class="fa fa-warning text-warning"></i>';

        }else{

          //$message = '<i class="fa fa-check text-success"></i>';


        }

      }

    }else{

      //request new token
        if(RequestSMSToken() != 'FAILED'){
           
          //$message = '<i class="fa fa-warning text-warning"></i>';

        }else{

          //$message = '<i class="fa fa-check text-success"></i>';


        }

    }  
    




    
    ////////////////////////approve taken repair//////////////////////////////

    if (isset($obj["repairToken"])) {

      @$repairToken=  mysql_prep($obj['repairToken']);

      $repairedSet = find_repaired_by_token($repairToken);

      $date = date("Y/m/d"); 
      $taken = 1;

      $empl = find_employee_by_id($repairedSet->tbl_employeeId); 
      $currentSMSData = find_sms_token_by_id();  


      $stmt = $connectMe->prepare(" 
        UPDATE  tbl_repair_device SET  tbl_repair_deviceTaken =?, tbl_repair_deviceTkDate =? 
        WHERE tbl_repair_deviceId =? 
      ");  

      $date = date("Y-m-d");
     
      $stmt->bindParam(1, $taken);
      $stmt->bindParam(2, $date);

      $stmt->bindParam(3, $repairedSet->tbl_repair_deviceId);
      if($stmt->execute()){

        //your business
        $business = find_business_by_id($empl->tbl_businessId);
        $compName = mysql_prep($business->tbl_businessName);

        $model = mysql_prep($repairedSet->tbl_repair_deviceName);

        $message = 'Dear Client, Thank you for trusting CELLFIX, Your '.$model.' is fixed. Call us on Tel:+250 788 872 889 for more information';
        $phone = mysql_prep($repairedSet->tbl_repair_deviceTel);

        //find sms api account by email
        $smsAccountInfo = findSMSUserByEmail($business->tbl_businessEmail);

        //FIND BALANCE FOR SMS USER
        $SMSBalanceInfo = findSMSBalanceByUserId($smsAccountInfo->tbl_userId, 1);

        //countSMSForApi
        $messageNumber = countSMSForApi($message);

        if(!isset($SMSBalanceInfo)){
          $messageText="Message not sent";
          $balanceText="No Balance registered";

        }




              //if balance is enough to send a message, send it
              if(isset($SMSBalanceInfo) && ($SMSBalanceInfo->tbl_balanceSms >= $messageNumber) ){

                $balance =  $SMSBalanceInfo->tbl_balanceSms - $messageNumber;

                $currentSMSData = find_sms_token_by_id();  
                $resp = sendSMSToClient($compName, $message, $phone, $currentSMSData->tbl_sms_dataToken);
  
                $resArray = json_decode($resp); 
  
                if(isset($resArray)){

                    ///////saveUserSMSForApi
                    if(saveUserSMSForApi($smsAccountInfo->tbl_userId, $compName, $message, $phone)){
                      
                      $messageText="Message Saved";
                      //update balance
                      if(updateSMSUserBalance($smsAccountInfo->tbl_userId, $balance)){

                        $balanceText="Balance Changed";

                      }else{ //end of update balance

                        $balanceText="Balance not Changed";
                      }
  
                    }else{ //end of save smsapi

                      $messageText="Message not Saved";

                    }
      
                }
                
                //else{ 
      
                  //echo '<script> alert("Order has been successfully sent"); </script>';
                //}


              }  
        
        //send notification

        $allUsers = find_all_users_for_business($empl->tbl_businessId, 1);
        foreach ($allUsers as $userData) {    

          //find user type by id
          $UserType =  find_user_categ_by_id(mysql_prep($userData->tbl_user_categId));


          //if he/she is admin or director 
          if( (strtolower(mysql_prep($UserType->tbl_user_categName)) =="admin") || (strtolower(mysql_prep($UserType->tbl_user_categName)) =="director")  ){  

          
            $title =" Divayisi yitwa - ".mysql_prep($repairedSet->tbl_repair_deviceName).' ya: -'.mysql_prep($repairedSet->tbl_repair_deviceClient).' yayitwaye';
            NotifyMe(0, $title, $userData->tbl_userId);

          }

        }

        exit(json_encode(array("message" => "Repair updated and message sent") ));

    
      }else{

        exit(json_encode(array("error" => "Something went wrong, please try again") ));

      }









    } 


  }else{

    exit(json_encode(array("error" => "unauthorised") ));


  }


