<?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($_GET["from"])  || !isset($_GET["to"])  ) {

    $error = array('error' => 'something went wrong');
    exit( json_encode($error) ); 

  }


  //exit(json_encode( array('headers' => getallheaders() )));


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

    }

    //exit(json_encode(array("total" => number_format(0), "profit" => 0)));



    //sales report

    if (isset($_GET["from"]) && isset($_GET["to"])  ) {

      @$status = 1;

      @$from = mysql_prep($_GET['from']);
      @$to = mysql_prep($_GET['to']);

      $repairAmt = array();

 

      if($decodeToken->UT== 'admin'){

        $branchSet = all_branches_for_business_and_type("SELLING", $decodeToken->BUSID, 1); 
    
      }else if($decodeToken->UT== 'manager'){

        $branchSet = all_branches_for_type_and_branch("SELLING", 1, $decodeToken->BID); 
        
      }else{
        exit(json_encode(
          array()
        ));
      }

      foreach ($branchSet as $branch) {

        $amount = (float)calculateRepairAmountForBranch(1, $from, $to , $branch->tbl_brandId)->amount;

        array_push(
          $repairAmt, 
          array(
            "branch" => $branch->tbl_brandName,
            "amount" => $amount
          )
        );
      }

      exit(json_encode($repairAmt));

                   


    }else{

      exit(json_encode(
        array()
      ));
    }

  
  }else{

    //http_response_code(401);

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

  }
