<?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["quantity"])  || !isset($obj["soldId"])  || !isset($obj["desc"])  || !isset($obj["typeId"])  ) { 

    $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 retun product///////////////////////////////

    if (isset($obj["quantity"])  && isset($obj["soldId"])  && isset($obj["desc"])  && isset($obj["typeId"])   ) {


      @$qty=  mysql_prep($obj['quantity']);
      @$typeId = mysql_prep($obj['typeId']);

      @$soldId=  mysql_prep($obj['soldId']);
      @$desc = mysql_prep($obj['desc']);

      @$date=  date("Y-m-d");
      @$status = 1; 

      $token = uniqid();

      $saleData = find_sold_product_by_id($soldId);

      if(!$saleData  &&  ($decodeToken->LANGUAGE == 2) ){

        exit(json_encode(array("error" => "Igikorwa ntabwo kibashije kurangira, ongera ugerageze") ));

      }

      if(!$saleData  &&  ($decodeToken->LANGUAGE == 1) ){

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

      } 
      
      // transfer details
      $transferInfo = find_transfer_by_id($saleData->tbl_branch_productId);

      if(!$transferInfo  &&  ($decodeToken->LANGUAGE == 2) ){

        exit(json_encode(array("error" => "Igikorwa ntabwo kibashije kurangira, ongera ugerageze") ));

      }

      if(!$transferInfo  &&  ($decodeToken->LANGUAGE == 1) ){
        exit(json_encode(array("error" => "Something went wrong, please try again") ));
      } 



        if($qty > $saleData->tbl_sold_prodQty){

          exit("Quantity is greater than sold quantity");

        }else{

          $remainQty = $saleData->tbl_sold_prodQty - $qty;
          $goneQty = $saleData->tbl_sold_prodQty - $remainQty;

          //add to branch stock
          $branchStockQty = $transferInfo->tbl_branch_productAvail + $qty;

        }



        $currUser = $decodeToken->ID;



        //user information
        $logUserInfo = find_user_by_id($currUser);

        //add product quantity to the current qty
        $product = find_product_by_id($saleData->tbl_productId);

        //find product cateory by id
        $proCategInfo = find_prod_categ_by_id($product->tbl_product_categId);

        $availQty = $product->tbl_productQty;

        $additionQty = $availQty + $qty;
      
      //create record

      $stmt = $connectMe->prepare(" INSERT INTO  tbl_return_prod (tbl_sold_prodId, tbl_return_prodDate, tbl_return_prodDescr, tbl_employeeId, tbl_actionId, tbl_return_prodQty, tbl_brandId, tbl_return_prodToken, tbl_return_prodStatus)  VALUES (?,?,?, ?,?,?, ?,?,?) ");

        $stmt->bindParam(1, $soldId);
        $stmt->bindParam(2, $date);

        $stmt->bindParam(3, $desc);
        $stmt->bindParam(4, $logUserInfo->tbl_employeeId);

        $stmt->bindParam(5, $typeId);
        $stmt->bindParam(6, $qty);

        $stmt->bindParam(7, $transferInfo->tbl_brandId);
        $stmt->bindParam(8, $token);

        $stmt->bindParam(9, $status);

        if($stmt->execute()){
          
          // update transfer
          if(update_transfer_by_id($branchStockQty, $transferInfo->tbl_branch_productId)){

              //update  sales  
              if(update_sale_by_id($soldId, $remainQty, 1)){  


               //send notifications
                $allUsers = find_all_users_for_business($proCategInfo->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 =$qty." za ".$product->tbl_productBrand." zari zaragurishijwe zagarutse, USER = ".@$logUserInfo->tbl_userName;
                    NotifyMe(0, $title, $userData->tbl_userId);

                  }
                }


              }else {  // sales not updated


                //send notifications
                $allUsers = find_all_users_for_business($proCategInfo->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 =$qty." za ".$product->tbl_productBrand." zagarutse ariko ibyagurishijwe ntabwo byahindutse";
                    NotifyMe(0, $title, $userData->tbl_userId);

                  }

                }


              } 



          }else {  // not update transfer


              //send notifications
              $allUsers = find_all_users_for_business($proCategInfo->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 =$qty." za ".$product->tbl_productBrand." zagarutse ariko stock to ku ishami ntabwo yahindutse";
                  NotifyMe(0, $title, $userData->tbl_userId);

                }

              }



          }








          if( ($decodeToken->LANGUAGE == 2) ){

            exit(json_encode(array("message" => $qty." za ".$product->tbl_productBrand." zari zaragurishijwe zagarutse")));

          }else{

            exit(json_encode(array(
              "message" => $qty." of ".$product->tbl_productBrand." have been returned",
              "id" => $product->tbl_productId
            )));

          }


    }else {  // not return recorded

      exit(json_encode(array("message" => "Something went wrong")));


    } 


  }


  }else{

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


  }


