<?php

// If called directly by Stripe, bootstrap WordPress so we can use plugin functions
if (!defined('ABSPATH')) {
    $wp_load = dirname(__FILE__, 4) . '/wp-load.php';
    if (file_exists($wp_load)) {
        require_once $wp_load;
    } else {
        // Cannot bootstrap WP; log and exit
        error_log('WPGV: stripewebhook.php could not locate wp-load.php');
        http_response_code(500);
        exit();
    }
}

global $wpdb;

$setting_table  = $wpdb->prefix . 'giftvouchers_setting';
$setting_options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

$wpgv_stripe_webhook_key = get_option('wpgv_stripe_webhook_key') ? get_option('wpgv_stripe_webhook_key') : '';

// include Stripe PHP library using force loader
require_once(WPGIFT__PLUGIN_DIR . '/include/stripe-force-loader.php');
wpgv_force_load_stripe_library();

// set api key
$stripe = array(
  "publishable_key" => $setting_options->stripe_publishable_key,
  "secret_key"      => $setting_options->stripe_secret_key,
  "webhook_key"     => $wpgv_stripe_webhook_key
);

\Stripe\Stripe::setApiKey($stripe['secret_key']);

// You can find your endpoint's secret in your webhook settings
$endpoint_secret = $stripe['webhook_key'];

$payload = @file_get_contents('php://input');
$sig_header = isset($_SERVER['HTTP_STRIPE_SIGNATURE']) ? $_SERVER['HTTP_STRIPE_SIGNATURE'] : '';
$event = null;

try {
  $event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret);
} catch (\UnexpectedValueException $e) {
  // Invalid payload
  http_response_code(400);
  exit();
} catch (\Stripe\Error\SignatureVerification $e) {
  // Invalid signature
  http_response_code(400);
  exit();
}

// Handle the checkout.session.completed event
if ($event && isset($event->type) && $event->type == 'checkout.session.completed') {
  $session = $event->data->object;

  // Try to locate voucher by saved session meta
  $session_id = is_object($session) ? ($session->id ?? '') : (is_array($session) ? ($session['id'] ?? '') : '');
  $voucher_id = 0;

  if (!empty($session_id)) {
    $meta = $wpdb->get_row($wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s LIMIT 1", 'wpgv_stripe_session_key', $session_id));
    if ($meta && isset($meta->post_id)) {
      $voucher_id = intval($meta->post_id);
    }
  }

  // Fallback: try client_reference_id or metadata.order_id
  if (!$voucher_id) {
    $client_ref = is_object($session) ? ($session->client_reference_id ?? '') : '';
    if (!empty($client_ref) && is_numeric($client_ref)) {
      $voucher_id = intval($client_ref);
    } elseif (is_object($session) && isset($session->metadata) && !empty($session->metadata->order_id)) {
      $voucher_id = intval($session->metadata->order_id);
    } elseif (is_array($session) && isset($session['metadata']['order_id'])) {
      $voucher_id = intval($session['metadata']['order_id']);
    }
  }

  if ($voucher_id && function_exists('wpgv_process_successful_order')) {
    // idempotent processing
    wpgv_process_successful_order($voucher_id);
  } else {
    error_log('WPGV: stripewebhook could not find voucher for session: ' . $session_id);
  }
}

http_response_code(200);
