<?php
// This is fallback if native getallheaders() is not supported
if (!function_exists('getallheaders')) {
  function getallheaders()
  {
    $headers = [];
    foreach ($_SERVER as $name => $value) {
      if (substr($name, 0, 5) === 'HTTP_') {
        $header_name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
        $headers[$header_name] = $value;
      } elseif ($name === 'CONTENT_TYPE') {
        $headers['Content-Type'] = $value;
      } elseif ($name === 'CONTENT_LENGTH') {
        $headers['Content-Length'] = $value;
      }
    }
    return $headers;
  }
}

function tzp_webhook_payment_status_change()
{
  $raw_input = file_get_contents("php://input");
  $headers = getallheaders();

  $signature = isset($headers['Signature']) ? $headers['Signature'] : '';

  if (!tzp_verify_webhook_signature($raw_input, $signature)) {
    http_response_code(401);
    header('HTTP/1.1 401 Unauthorized');
    exit;
  }

  $response = json_decode($raw_input, true);

  if (!isset($_GET['order_id'])) {
    http_response_code(400);
    header('HTTP/1.1 400 Bad Request');
    exit;
  }

  $order_id = (int) sanitize_text_field($_GET['order_id']);

  $order = wc_get_order($order_id);

  if (!$order || !is_a($order, 'WC_Order')) {
    http_response_code(400);
    header('HTTP/1.1 400 Bad Request');
    exit;
  }

  http_response_code(200);

  $paymentMethod = $order->get_payment_method();

  if ($paymentMethod == 'tazapay') {

    if (is_null($response)) {
      exit;
    }

    $payment_status = $response['data']['payment_status'];
    $orderStatus = $order->get_status();

    $order->add_order_note('Current status is ' . $orderStatus . '. TZ Payment Webhook received with ' . $payment_status);
    $payment_done = (int) $order->get_meta('payment_done', true);

    if ($payment_done == 1) {
      exit;
    }

    $state = tzp_process_getCheckoutResponse($response, $order_id);

    switch ($state) {
      case SUCCEEDED:
        return tzp_thankyou_page($order_id);
      case PROCESSING:
        return tzp_thankyou_page($order_id);
      case FAILED:
      // return tzp_thankyou_page($order_id);
    }
  }
}

function tzp_webhook_refund_status_change()
{
  $raw_input = file_get_contents("php://input");
  $headers = getallheaders();

  $signature = isset($headers['Signature']) ? $headers['Signature'] : '';
  if (!tzp_verify_webhook_signature($raw_input, $signature)) {
    http_response_code(401);
    header('HTTP/1.1 401 Unauthorized');
    exit;
  }

  $response = json_decode($raw_input, true);

  if (!isset($_GET['order_id'])) {
    http_response_code(400);
    header('HTTP/1.1 400 Bad Request');
    exit;
  }

  $order_id = (int) sanitize_text_field($_GET['order_id']);

  $order = wc_get_order($order_id);

  if (!$order || !is_a($order, 'WC_Order')) {
    http_response_code(400);
    header('HTTP/1.1 400 Bad Request');
    exit;
  }

  http_response_code(200);

  $paymentMethod = $order->get_payment_method();

  if ($paymentMethod == 'tazapay') {

    if (is_null($response)) {
      exit;
    }

    $payment_status = $response['data']['status'];
    $orderStatus = $order->get_status();

    $order->add_order_note('Current status is ' . $orderStatus . '. TZ Refund Webhook received with ' . $payment_status);

    if ($orderStatus == PROCESSING || $orderStatus == COMPLETED) {

      $state = tzp_process_getRefundResponse($response, $order_id);

      switch ($state) {
        case APPROVED:
          # code...
          break;
        case FAILED:
          # code...
          break;
        case PENDING:
          # code...
          break;
        default:
          # error handler
          # code...
          break;
      }
    }
  }
}
