<?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["currencyId"])  || !isset($obj["modelId"])  || !isset($obj["quantity"]) || !isset($obj["cost"]) || !isset($obj["supplierId"]) || !isset($obj["madeId"]) || !isset($obj["branchId"])  || !isset($obj["colorId"]) ) {

    $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") ));

    }


    //add puchase

  if (isset($obj["currencyId"])  && isset($obj["modelId"])  && isset($obj["quantity"]) && isset($obj["cost"]) && isset($obj["supplierId"]) && isset($obj["madeId"]) && isset($obj["branchId"])  && isset($obj["colorId"]) ) {

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

      @$cost =  mysql_prep($obj['cost']);
      @$date =  mysql_prep(date("Y-m-d"));

      @$supplId =  mysql_prep($obj['supplierId']);
      @$empId =  mysql_prep($decodeToken->EMPID);

      @$branch = mysql_prep($obj['branchId']);
      $branchInfo = find_branch_by_id($branch);

      @$prodMade = mysql_prep($obj['madeId']);
      @$prodColor = mysql_prep($obj['colorId']);

      @$prodCurrency = mysql_prep($obj['currencyId']);


      @$addTransProCode = uniqid();
      @$token =  str_replace("/","", mysql_prep(password_hash(uniqid(), PASSWORD_BCRYPT, ['cost' => 10])));


      //add product quantity to the current qty
      $product = find_product_by_id($prodId);

      if(!isset($product)){
        $error = array("error"=> 'product does not exist');
        exit( json_encode($error) ); 
      }

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

      if($proCategInfo->tbl_product_categCode == 1 ){

        $quantity = 1;

        if(empty(trim($addTransProCode))){

          $error = array("error"=> 'Serial number is required');
          exit( json_encode($error) ); 
        }

      }else{

        $addTransProCode = uniqid()."".uniqid();

      }


      //find transaction by code
      $foundTransInfo = find_transaction_by_code($addTransProCode);

      if(isset($foundTransInfo)){

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

          $error = array("error"=> 'Kode isanzwemo');
          exit( json_encode($error) ); 

        }else{ //ENGLISH

          $error = array("error"=> 'Serial number is already found');
          exit( json_encode($error) ); 

        }
      }


      
      $buyingCost = 0;

      //find currency by id
      $currencyInfo = find_currency_by_id($prodCurrency);

      if(!isset($currencyInfo)){

        $error = array("error"=> 'Please try again');
        exit( json_encode($error) ); 

      }

      //find formula for currency
      $formulaInfo = find_formula_by_currencyId_and_categ($currencyInfo->tbl_currecyId, $proCategInfo->tbl_product_categId);
      
      if(isset($formulaInfo)){

        $buyingCost = ( ($cost / $formulaInfo->tbl_formulaDivider) * $currencyInfo->tbl_currecyValue) + $formulaInfo->tbl_currecyExp;
        

      }else{

        $buyingCost = $cost;


      }


        $status = 1;

        $stmt = $connectMe->prepare(" INSERT INTO  tbl_inventory (tbl_productId, tbl_employeeId, tbl_inventoryQty, tbl_inventoryCost, tbl_inventoryDate, tbl_supplierId, tbl_inventoryToken, tbl_brandId, tbl_inventoryStatus, tbl_inventoryAvailQty, tbl_madeId, tbl_colorId, tbl_inventoryCode)  VALUES (?,?, ?,?, ?,?, ?,?, ?,?, ?,?, ?) ");  
       
        $stmt->bindParam(1, $prodId);
        $stmt->bindParam(2, $empId);

        $stmt->bindParam(3, $quantity);
        $stmt->bindParam(4, $buyingCost);

        $stmt->bindParam(5, $date);
        $stmt->bindParam(6, $supplId);
        
        $stmt->bindParam(7, $token);
        $stmt->bindParam(8, $branchInfo->tbl_brandId);

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

        $stmt->bindParam(11, $prodMade);
        $stmt->bindParam(12, $prodColor);

        $stmt->bindParam(13, $addTransProCode);

        if($stmt->execute()){


          $lastId = $connectMe->lastInsertId();


          //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 =" Haranguwe : - (".$quantity .") za ".$product->tbl_productBrand." ku ishami rya: ".$branchInfo->tbl_brandName;
              NotifyMe(0, $title, $userData->tbl_userId);

            }

          }


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

            $message = array("message"=> "Haranguwe : - (".$quantity .") za ".$product->tbl_productBrand." ku ishami rya: ".$branchInfo->tbl_brandName);

            exit( json_encode($message) ); 

          }else{  //ENGLISH


            $message = array(
              "message"=> "You have purchased : - (".$quantity .") of ".$product->tbl_productBrand." at: ".$branchInfo->tbl_brandName,
              "id" => $lastId
            );

            exit( json_encode($message) ); 


          }
      
        }else{

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

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

          }else{


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

          }

        }



    
    }








  }else{


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


  }