<?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["categName"]) || !isset($obj["businessId"])  || !isset($obj["code"])) {

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

    }


    if(isset($obj['categName']) && isset($obj['businessId'])  && isset($obj['code']) ){

      @$name =  mysql_prep($obj['categName']);
      @$businessId =  mysql_prep($obj['businessId']);

      @$code =  mysql_prep($obj['code']);
    
      //check if category is already exists
      $sql = $connectMe->prepare(" SELECT * FROM tbl_product_categ WHERE (tbl_product_categName = ?) AND (tbl_businessId = ?) "); 

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

      $sql->execute();
      if($sql->rowCount() > 0){ 
        
        if($decodeToken->LANGUAGE == 2){    //KINYARWANDA

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

        }else{ //English

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

        }

      
      }else{

        $status = 1;
        $stmt = $connectMe->prepare("INSERT INTO  tbl_product_categ ( tbl_product_categName, tbl_product_categStatus, tbl_businessId, tbl_product_categCode)  VALUES ( ?,?, ?,? ) ");  

        $stmt->bindParam(1, $name);
        $stmt->bindParam(2, $status);

        $stmt->bindParam(3, $businessId);
        $stmt->bindParam(4, $code);

        if($stmt->execute()){

          
          //send notifications
          $allUsers = find_all_users_for_business($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 =" Ubwoko bushya - ".$name." bwongewe muri system";
              NotifyMe(0, $title, $userData->tbl_userId);

            }

          }
          

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

            $message = array("message"=> "Ubwoko bushya - ".$name." bwongewe muri system");
            exit( json_encode($message) ); 
        
            exit();

          }else{  //English

            $message = array("message"=> "Category - ".$name." saved");
            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{

    $error = array("error" => "UNAUTHORIZED");

    exit(json_encode($error));
  }