
<?php

  define('SHOPIFY_APP_SECRET', '0a8235dd3483869d56d9e7fa1a3768b32908d84d14e9585759ec453d8afd1950');

  function verify_webhook($data, $hmac_header)
  {
    $calculated_hmac = base64_encode(hash_hmac('sha256', $data, SHOPIFY_APP_SECRET, true));
    return hash_equals($hmac_header, $calculated_hmac);
  }

  $hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];
  $data = file_get_contents('php://input');
  file_put_contents('order.json', $data );
  $data_array = json_decode($data, true);

  // $data = file_get_contents('test2.json'); 
  // $data_array = json_decode($data, true);


  $verified = verify_webhook($data, $hmac_header);
  error_log('Webhook verified: '.var_export($verified, true)); //check error.log to see the result

  // $verified = true;
  if ( $verified == true ) {

    $order_array = array();
    $results_array = array();
    $business_card = false;

    foreach( $data_array as $key => $value ) {

      if( $key == 'id' ){
        $order_array[$key] =  $value ;
      } else if( $key == 'line_items' ){
        foreach( $value as $line_item ) {
          if ( $line_item['title'] == 'Business Cards'  ){
            $business_card = true;
            foreach($line_item['properties'] as $value ) {
              $order_array[$value['name']] = $value['value'];
            }
            $results_array[] = $order_array;
          }
        }
      }
    }
  } // verified 



  $file = 'json/export.json';
  $export_array = array();

  if ( $business_card == true ){
    if ( file_exists( $file ) ) {
      $export_json = file_get_contents( $file );
      if ( ! empty( $export_json ) && $export_json !== 'null' ){
        $export_array = json_decode( $export_json, true );
        foreach( $export_array as $single_array ) {
          $results_array[] = $single_array;
        }
      }
    }

    $results = json_encode( $results_array , true);
    file_put_contents('json/export.json', $results );
  }

  

?>