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

    $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>';


        // }

    }  
    




    
    ////////////////////////add sold product///////////////////////////////

    if (isset($obj["quantity"])  && isset($obj["type"])  && isset($obj["price"]) && isset($obj["sms"]) && isset($obj["customer"]) && isset($obj["phone"]) && isset($obj["transferId"])  && isset($obj["warranty"])  && isset($obj["date"])   ) {


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

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

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

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

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

      $str = "1234567890ABACDEFGHIJKLMNOPQRSTUVWXYZ";
      $str = str_shuffle($str);

      //generate company code
      $code = substr($str, 0,9); 

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

      //find transfer info
      $transferInfo = find_transfer_by_id(mysql_prep($transferId)); 

      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" => "1-Something went wrong, please try again") ));

      } 

       @$branchId=  mysql_prep($transferInfo->tbl_brandId);

      //check if quantities needed in the order are in db
      $Inventory = find_transaction_by_id($transferInfo->tbl_inventoryId);


      if($transferInfo->tbl_branch_productAvail < $quantity){

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

          exit(json_encode(array("error" => "Ibyo washijemo biruta ibyo dufite") ));

        }else{

          exit(json_encode(array("error" => "What you have added is greater than available quantity") ));

        }

      
      }else{  //produts are available




        $Product = find_product_by_id($Inventory->tbl_productId);

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



        // add order to the database
        $createSales = add_new_sold_products( $Product->tbl_productId,  $customer,  $type, $price, $decodeToken->EMPID, $quantity, $date, $token, $phone, $Inventory->tbl_inventoryId,  $transferId, $code, $warranty, $branchId );
        if( $createSales ){


          // update transfer by id
          if(update_transfer_by_id( number_format($transferInfo->tbl_branch_productAvail - $quantity), $transferId)){



            //employee info
            $soldEmpInfo = find_employee_by_id($decodeToken->EMPID);

            //your business
            $business = find_business_by_id($soldEmpInfo->tbl_businessId);

            if($sms == 1){

              $businessId = mysql_prep($soldEmpInfo->tbl_businessId);

              if($warranty > 0){

                //check if name is set

                if(!empty($customer) ){

                  $custName = mysql_prep($customer);

                  $message = 'Dear '.$custName.', You have bought '.$Product->tbl_productBrand.', Price: RWF '.$price.' and you have been given '.$warranty.' days of warranty.Tel:+250 788 872 889';

                }else{

                  $message = 'Dear customer, You have bought '.$Product->tbl_productBrand.', Price: RWF '.$price.' and you have been given '.$warranty.' days of warranty.Tel:+250 788 872 889';
                }

                

              }else{


                if(!empty($customer) ){

                  $custName = mysql_prep($customer);

                  $message = 'Dear '.$custName.', You have bought '.$Product->tbl_productBrand.', Price: RWF '.$price.', Tel: +250 788 872 889';

                }else{

                  $message = 'Dear customer, You have bought '.$Product->tbl_productBrand.', Price: RWF '.$price.', Tel: +250 788 872 889';
                }


              }

              //$message = 'Dear customer, Thank you for shopping with us. Contact us on '.$business->tbl_businessContact.' for ordering our products.';

              $compName = mysql_prep($business->tbl_businessCode);
              $date = date("Y-m-d");

              $time = date("h:i:s");
              $messageStatus = 1;

              saveSMS($businessId, $message, $date, $time, $messageStatus);

              //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, $value['telephone'])){
                      
                      $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";

                    }

                }

              }

            }


            //send notifications
             $allUsers = find_all_users_for_business($soldEmpInfo->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 = "Umukozi witwa: -".$soldEmpInfo->tbl_employeeFname." ".$soldEmpInfo->tbl_employeeLname." agurishije  - (".$quantity.") za: - ".$Product->tbl_productBrand.', kandi stock yahindutse';
                 NotifyMe(0, $title, $userData->tbl_userId);
                 
                  //SEND AN EMAIL   
                  $from ="worldsoftlimited@gmail.com";
                  $from2 = mysql_prep($business->tbl_businessEmail);
              
                  @$headers = mysql_prep($business->tbl_businessName)." Transaction";
                  @$txt = "You have received an e-mail \n\n ".$title;
        
                  $subject = 'Igicuruzwa cyagurishijwe via Mobile App';
                  $subject2 = 'Igicuruzwa cyagurishijwe';

                  // mail($from, $subject, $txt , $headers);
                  // mail($from2, $subject2, $txt , $headers);  


                }

              }


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

                exit(json_encode(array("message" => "Igicuruzwa cyagurishijwe") ));


              }else{

                exit(json_encode(
                  array(
                    "message" => "Product sold",
                    "id" => $createSales
                  ) 
                ));

              }




          }else{


            //employee info
            $soldEmpInfo = find_employee_by_id($decodeToken->EMPID);

            //your business
            $business = find_business_by_id($soldEmpInfo->tbl_businessId);


            //send notifications
            $allUsers = find_all_users_for_business($soldEmpInfo->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 = "Umukozi witwa: -".$soldEmpInfo->tbl_employeeFname." ".$soldEmpInfo->tbl_employeeLname." agerageje kugurisha  - (".$quantity.") za: - ".$Product->tbl_productBrand.', ariko stock ntabwo yahindutse';
                NotifyMe(0, $title, $userData->tbl_userId);
                

                  //SEND AN EMAIL   
                  $from ="worldsoftlimited@gmail.com";
                  $from2 = mysql_prep($business->tbl_businessEmail);
              
                  @$headers = mysql_prep($business->tbl_businessName)." Transaction";
                  @$txt = "You have received an e-mail \n\n ".$title;
        
                  $subject = 'Igikorwa ntabwo cyarangiye';

                  try {

                    mail($from, $subject, $txt , $headers);
                    mail($from2, $subject2, $txt , $headers);  
                    
                  } catch (Exception $e) {
                    
                  }
                

              }

            }
      

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

              exit(json_encode(array("error" => "Stock ntabwo yahindutse") ));

            }else{

              exit(json_encode(array("error" => "Stock does not change") ));

            }



          }

        }



      }







    } 


  }else{

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


  }


