<?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["model"])  || !isset($obj["price"])  || !isset($obj["sms"]) || !isset($obj["phone"]) || !isset($obj["customer"]) || !isset($obj["problem"]) ||  !isset($obj["branchId"])  ||  !isset($obj["warranty"])  ||  !isset($obj["date"]) 
   ) { 

    $error = array("error"=> "Fill all information"); 
    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>';


      //   }

    }  
    




    
    ////////////////////////add new repair///////////////////////////////

    if (isset($obj["model"])  && isset($obj["price"])  && isset($obj["sms"]) && isset($obj["customer"]) 
      && isset($obj["phone"]) && isset($obj["problem"]) && isset($obj["imei"]) && isset($obj["branchId"])
      && isset($obj["warranty"])  && isset($obj["date"])
    ) {
      

      @$model=  mysql_prep($obj['model']);
      @$price = mysql_prep($obj['price']);

      @$sms=  mysql_prep($obj['sms']);
      @$customer = mysql_prep($obj['customer']);

      @$phone=  mysql_prep($obj['phone']);
      @$problem = mysql_prep($obj['problem']);

      @$imei = mysql_prep($obj['imei']);
      @$branchId = mysql_prep($obj['branchId']);

      @$warranty = mysql_prep($obj['warranty']);
      @$date = mysql_prep($obj['date']);

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

      $employeeId = mysql_prep($decodeToken->EMPID);  
      $taken = 0;
    
      //check if products is already exists
      $sql = $connectMe->prepare(" SELECT * FROM tbl_repair_device WHERE (tbl_repair_deviceClient = ?)  
        AND (tbl_repair_deviceName = ?) AND (tbl_repair_deviceDate =?)  AND (tbl_repair_deviceFee =?) 
        AND (tbl_repair_deviceTel =?)
      "); 
      $sql->bindParam(1, $customer);
      $sql->bindParam(2, $model);

      $sql->bindParam(3, $date);
      $sql->bindParam(4, $price);

      $sql->bindParam(5, $phone);
      $sql->execute();

      if($sql->rowCount() > 0){ 

        exit(json_encode(array("error" => $model.' is already exist, Please check') ));


      }else{

        $status = 1;
        $empl = find_employee_by_id($employeeId);  

        //page token
        $id = uniqid();
        $token = str_replace("/","", password_hash($id, PASSWORD_BCRYPT, ['cost' => 10]));
        

        $stmt = $connectMe->prepare(" 
        INSERT INTO  tbl_repair_device ( 
        tbl_repair_deviceClient,  tbl_repair_deviceTel, tbl_repair_deviceName, tbl_repair_deviceProblm, 
        tbl_repair_deviceFee, tbl_repair_deviceDate, tbl_repair_deviceTkDate, tbl_repair_deviceTaken, 
        tbl_employeeId, tbl_repair_deviceToken, tbl_repair_deviceStatus, tbl_repair_deviceSerial, 
        tbl_repair_deviceWarranty, tbl_brandId )  
        VALUES (?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?) ");  

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

        $stmt->bindParam(3, $model);
        $stmt->bindParam(4, $problem);

        $stmt->bindParam(5, $price);
        $stmt->bindParam(6, $date);

        $stmt->bindParam(7, $date);
        $stmt->bindParam(8, $taken);

        $stmt->bindParam(9, $employeeId);
        $stmt->bindParam(10, $token);

        $stmt->bindParam(11, $status);
        $stmt->bindParam(12, $imei);

        $stmt->bindParam(13, $warranty);
        $stmt->bindParam(14, $branchId);

        if($stmt->execute()){ 
          

          //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 - ".$model.' ya: -'.$customer.' yongewe muzigiye gukorwa';
              NotifyMe(0, $title, $userData->tbl_userId);

            }

          }


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

          if($sms == 1){       /////////////// send SMS

            $message = 'Dear Client, Thank you for trusting CELLFIX, We will let you know when '.$model.' is fixed. Call us on Tel:+250 788 872 889 for more information';

            //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)){
      
                    //if($resArray->statusCode == 200){
          
                        //echo '<script> alert("Order has been successfully sent and Message sent to Client"); </script>';
          
                    //}else{
          
                        //echo '<script> alert("Order has been successfully sent and Message not sent"); </script>';
                    //}
      
                    ///////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>';
                //}


              }    
          
          
          }

    

          exit(json_encode(array("message" => 'Device: '.$model.' has been added') ));

      
        }else{

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

        }
      
      }





    }




  }else{

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


  }


