<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly

add_action('wp_ajax_nopriv_wpgv_klarna_webhook', 'wpgv_klarna_webhook');
add_action('wp_ajax_wpgv_klarna_webhook', 'wpgv_klarna_webhook');

function wpgv_klarna_webhook()
{
    // Read raw body
    $body = file_get_contents('php://input');
    $data = json_decode($body, true);

    // Get Authorization header
    $headers = function_exists('getallheaders') ? getallheaders() : array();
    $auth = '';
    if (!empty($headers['Authorization'])) {
        $auth = $headers['Authorization'];
    } elseif (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
        $auth = $_SERVER['HTTP_AUTHORIZATION'];
    }

    // Load stored credentials
    $demo_mid = get_option('wpgv_klarna_demo_merchant_id', '');
    $demo_secret = get_option('wpgv_klarna_demo_shared_secret', '');
    $live_mid = get_option('wpgv_klarna_live_merchant_id', '');
    $live_secret = get_option('wpgv_klarna_live_shared_secret', '');

    $authorized = false;
    if ($auth && stripos($auth, 'basic') === 0) {
        $b64 = trim(substr($auth, 6));
        $decoded = base64_decode($b64);
        if ($decoded) {
            $parts = explode(':', $decoded, 2);
            $user = isset($parts[0]) ? $parts[0] : '';
            $pass = isset($parts[1]) ? $parts[1] : '';
            if (($user === $demo_mid && $pass === $demo_secret) || ($user === $live_mid && $pass === $live_secret)) {
                $authorized = true;
            }
        }
    }

    // Simple logging for debug (log file inside wp-content)
    $logfile = WP_CONTENT_DIR . '/klarna_webhook.log';
    @file_put_contents($logfile, date('c') . " auth=" . ($authorized ? 'ok' : 'fail') . " body=" . $body . "\n", FILE_APPEND);

    if (!$authorized) {
        status_header(401);
        echo 'Unauthorized';
        wp_die();
    }

    // Determine merchant reference/order id from payload
    $merchant_ref = '';
    if (!empty($data['merchant_reference'])) {
        $merchant_ref = $data['merchant_reference'];
    } elseif (!empty($data['order']) && !empty($data['order']['merchant_reference'])) {
        $merchant_ref = $data['order']['merchant_reference'];
    } elseif (!empty($data['merchant_reference']) && is_array($data['merchant_reference'])) {
        $merchant_ref = json_encode($data['merchant_reference']);
    }

    // Update order/payment status if possible
    if ($merchant_ref) {
        global $wpdb;
        $orders_table = $wpdb->prefix . 'giftvouchers_list';

        // Try to find by id or order_number
        $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$orders_table} WHERE id=%s OR order_number=%s", $merchant_ref, $merchant_ref));
        if ($row) {
            // Map Klarna event/status to local payment_status
            $statusVal = '';
            if (!empty($data['payment_status'])) $statusVal = strtoupper($data['payment_status']);
            if (!empty($data['status'])) $statusVal = strtoupper($data['status']);
            if (!empty($data['event_type'])) $statusVal = strtoupper($data['event_type']);
            $new_status = '';
            if (strpos($statusVal, 'PAID') !== false || strpos($statusVal, 'CAPTURE') !== false || strpos($statusVal, 'AUTH') !== false || strpos($statusVal, 'AUTHORIZED') !== false) {
                $new_status = 'Paid';
            } elseif (strpos($statusVal, 'CANCEL') !== false || strpos($statusVal, 'CANCELLED') !== false || strpos($statusVal, 'VOID') !== false) {
                $new_status = 'Cancelled';
            }
            if ($new_status) {
                $wpdb->update($orders_table, array('payment_status' => $new_status), array('id' => $row->id));
                // Optionally record activity
                if (class_exists('WPGV_Gift_Voucher_Activity')) {
                    WPGV_Gift_Voucher_Activity::record($row->id, 'transaction', 0, 'Klarna webhook: ' . $new_status);
                }
            }
        }
    }

    status_header(200);
    echo 'OK';
    wp_die();
}
