<?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['email'])  || !isset($obj['firstName']) || !isset($obj['username'])  || !isset($obj['roleId'])  || !isset($obj['userId'])  || !isset($obj['phone'])   ){

    //http_response_code(400);

    $error = array("error"=> "Fill all fields");
    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") ));

    }



  //update user

  if (isset($obj['email'])  && isset($obj['firstName']) && isset($obj['username']) && isset($obj['userId'])  && isset($obj['phone']) && isset($obj['roleId'])  ) {


    $email = mysql_prep($obj['email']);
    $firstName = mysql_prep($obj['firstName']);

    $lastName = mysql_prep($obj['lastName']);
    $phone = mysql_prep($obj['phone']);

    $username = mysql_prep($obj['username']);
    $roleId = mysql_prep($obj['roleId']);

    $pass = mysql_prep($obj['password']);
    $userId = mysql_prep($obj['userId']);


        $sql = $connectMe->prepare("UPDATE tbl_user  SET tbl_userFname =?, tbl_userLname =?, tbl_userTel =?, tbl_userEmail =?, tbl_userName =?, tbl_roleId =? WHERE  tbl_userId =? " );
        
        $sql->bindParam(1, $firstName);
        $sql->bindParam(2, $lastName);

        $sql->bindParam(3, $phone);
        $sql->bindParam(4, $email);

        $sql->bindParam(5, $username);
        $sql->bindParam(6, $roleId);

        $sql->bindParam(7, $userId);
        if($sql->execute()){

          $message = array("message"=> 'Account updated');
          exit( json_encode($message) ); 

          

        }else{
            
            //http_response_code(500);

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

          
        }

      

 
  }



  }else{

    //http_response_code(401);

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

  }