<?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["name"])  || !isset($obj["brandId"])) {

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

    if( isset($obj['name'])  &&  isset($obj['brandId'])   ){

 	  @$name=  htmlentities($obj['name']);
    @$addproSpec = mysql_prep($obj['brandId']);

    @$token =  uniqid();
    @$qty =  0;

    //find specification by id
    $specInfo = find_specification_by_id($addproSpec);

    //find product cateory by id
    $proCategInfo = find_prod_categ_by_id($specInfo->tbl_product_categId);
    
      //check if products is already exists
      $sql = $connectMe->prepare(" SELECT * FROM tbl_product WHERE (tbl_productBrand = ?)  AND (tbl_product_categId = ?) AND (tbl_specificationId =?)   "); 

      $sql->bindParam(1, $name);
      $sql->bindParam(2, $proCategInfo->tbl_product_categId);

      $sql->bindParam(3, $addproSpec);
      $sql->execute();

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


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

          $error = array("error"=> $name.' isanzwe irimo');
          exit( json_encode($error) ); 

        }else{ //English

          $error = array("error"=> $name.' is already exist');
          exit( json_encode($error) ); 

        }


        

      }else{

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

        $stmt = $connectMe->prepare("INSERT INTO  tbl_product ( 
        tbl_product_categId,  tbl_productBrand, tbl_productDate, tbl_productQty, tbl_productToken, tbl_specificationId, tbl_productStatus, tbl_businessId)  VALUES (?,?,?, ?,?,?, ?,?) ");  
       
        $stmt->bindParam(1, $proCategInfo->tbl_product_categId);
        $stmt->bindParam(2, $name);

        $stmt->bindParam(3, $date);
        $stmt->bindParam(4, $qty);

        $stmt->bindParam(5, $token);
        $stmt->bindParam(6, $addproSpec);

        $stmt->bindParam(7, $status);
        $stmt->bindParam(8, $proCategInfo->tbl_businessId);

        if($stmt->execute()){

          $prodId = $connectMe->lastInsertId();

          //send notification

          $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 =$name.' yongewe mubicuruzwa ';
              NotifyMe(0, $title, $userData->tbl_userId);

            }

          }

          //DO BACKUP
          //doBackup();


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

            $error = array("message"=> $name.' yongewe mubicuruzwa');
            exit( json_encode($error) ); 

          }else{ //English

            $error = array("message"=> $name.' has been added as new model');
            exit( json_encode($error) ); 

          }

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


  }


