<?php
/**
 * Klarna Payments v1 Authorization Handler - Standard Widget Flow
 * Processes authorization tokens from Klarna.Payments.authorize() and captures the payment
 */

if (!defined('ABSPATH')) exit;

function wpgv_klarna_authorize_handler() {
	// Verify nonce
	$nonce = isset($_POST['nonce']) ? sanitize_text_field($_POST['nonce']) : '';
	if (empty($nonce) || !wp_verify_nonce($nonce, 'wpgv_klarna_authorize')) {
		wp_send_json_error(array('message' => 'Security check failed'));
		wp_die();
	}

	$session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
	$authorization_token = isset($_POST['authorization_token']) ? sanitize_text_field($_POST['authorization_token']) : '';
	$billing_address_json = isset($_POST['billing_address']) ? stripslashes($_POST['billing_address']) : '';

	if (empty($session_id) || empty($authorization_token)) {
		wp_send_json_error(array('message' => 'Missing session_id or authorization_token'));
		wp_die();
	}

	// Decode billing address from frontend (used in authorize() call)
	$billing_address_from_auth = !empty($billing_address_json) ? json_decode($billing_address_json, true) : array();

	error_log('Klarna: authorization handler called for session ' . $session_id);

	// Get Klarna credentials
	$klarna_mode = get_option('wpgv_klarna_mode') ? get_option('wpgv_klarna_mode') : 'sandbox';
	if ($klarna_mode === 'live') {
		$merchant_id = get_option('wpgv_klarna_live_merchant_id');
		$shared_secret = get_option('wpgv_klarna_live_shared_secret');
		$klarna_create_order_url = 'https://api.klarna.com/payments/v1/authorizations';
	} else {
		$merchant_id = get_option('wpgv_klarna_demo_merchant_id');
		$shared_secret = get_option('wpgv_klarna_demo_shared_secret');
		$klarna_create_order_url = 'https://api.playground.klarna.com/payments/v1/authorizations';
	}

	if (empty($merchant_id) || empty($shared_secret)) {
		wp_send_json_error(array('message' => 'Klarna credentials not configured'));
		wp_die();
	}

	// Find the voucher/item/giftcard record by session_id to get session data
	global $wpdb;
	$postmeta_table = $wpdb->postmeta;

	// Search for records with this session_id in meta
	$records = $wpdb->get_results($wpdb->prepare(
		"SELECT pm.post_id FROM $postmeta_table pm
		WHERE pm.meta_key = %s AND pm.meta_value = %s",
		'wpgv_klarna_session_id',
		$session_id
	));

	if (empty($records)) {
		wp_send_json_error(array('message' => 'Session not found in database'));
		wp_die();
	}

	$post_id = $records[0]->post_id;
	$session_data_json = get_post_meta($post_id, 'wpgv_klarna_session_data', true);
	$session_data = json_decode($session_data_json, true);

	if (empty($session_data)) {
		wp_send_json_error(array('message' => 'Session data not found'));
		wp_die();
	}

	// Create Klarna order using authorization token
	// Per Klarna Step 3: POST /payments/v1/authorizations/{authorization_token}/order
	// Must include same data as session creation (order_lines, order_amount, etc.)
	// CRITICAL: Must also include billing_address that matches authorize() call
	$create_order_endpoint = $klarna_create_order_url . '/' . $authorization_token . '/order';

	// Build payload matching session creation
	$payload = array(
		'purchase_country' => $session_data['purchase_country'],
		'purchase_currency' => $session_data['purchase_currency'],
		'locale' => $session_data['locale'],
		'order_amount' => $session_data['order_amount'],
		'order_tax_amount' => $session_data['order_tax_amount'],
		'order_lines' => $session_data['order_lines']
	);

	// Get billing_address from authorize() - stored in session or reconstructed
	// The billing_address MUST match what was sent in authorize() call (Step 2)
	// Otherwise Klarna will return BAD_VALUE error

	// Only add billing_address if we have complete data from authorize() call
	// If authorize() didn't send billing_address, Klarna collected it in widget
	// and we should NOT send it in create order to avoid mismatch
	if (!empty($billing_address_from_auth) && isset($billing_address_from_auth['email'])) {
		$payload['billing_address'] = $billing_address_from_auth;
		error_log('Klarna: including billing_address in create order: ' . wp_json_encode($billing_address_from_auth));
	} else {
		error_log('Klarna: no billing_address sent - Klarna widget collected customer data');
	}

	// Add merchant_urls if exists
	if (!empty($session_data['merchant_urls'])) {
		$payload['merchant_urls'] = $session_data['merchant_urls'];
	}	$args = array(
		'headers' => array(
			'Authorization' => 'Basic ' . base64_encode($merchant_id . ':' . $shared_secret),
			'Content-Type' => 'application/json'
		),
		'body' => wp_json_encode($payload),
		'timeout' => 30,
	);

	error_log('Klarna: sending create order request with authorization token');
	error_log('Klarna: Create order endpoint: ' . $create_order_endpoint);

	$response = wp_remote_post($create_order_endpoint, $args);

	if (is_wp_error($response)) {
		wp_send_json_error(array('message' => 'Klarna API request failed: ' . $response->get_error_message()));
		wp_die();
	}

	$code = wp_remote_retrieve_response_code($response);
	$body = wp_remote_retrieve_body($response);
	$data = json_decode($body, true);

	if ($code >= 200 && $code < 300) {
		// Order created successfully
		if (!empty($data['order_id'])) {
			$klarna_order_id = sanitize_text_field($data['order_id']);
			error_log('Klarna: order created successfully with ID: ' . $klarna_order_id);

			// Update payment metadata (we already have $post_id from earlier)
			update_post_meta($post_id, 'wpgv_klarna_order_id', $klarna_order_id);
			update_post_meta($post_id, 'wpgv_klarna_authorized', 'yes');
			update_post_meta($post_id, 'wpgv_klarna_authorized_at', current_time('mysql'));

			// Auto-capture the order immediately
			// This ensures the payment is collected even if user closes browser
			$capture_success = false;
			if (function_exists('wpgv_klarna_capture_order')) {
				error_log('Klarna: Attempting auto-capture for order ' . $klarna_order_id);
				$capture_result = wpgv_klarna_capture_order($klarna_order_id, null);
				$capture_success = !empty($capture_result['success']);
				if ($capture_success) {
					error_log('Klarna: Auto-capture successful for order ' . $klarna_order_id);
					update_post_meta($post_id, 'wpgv_klarna_captured', 'yes');
					update_post_meta($post_id, 'wpgv_klarna_captured_at', current_time('mysql'));
				} else {
					error_log('Klarna: Auto-capture failed: ' . ($capture_result['message'] ?? 'Unknown error'));
				}
			}

			// Full order processing - update payment status, generate PDF, create balance, send emails
			if (function_exists('wpgv_process_klarna_order_complete')) {
				error_log('Klarna: Processing complete order for post_id ' . $post_id);
				wpgv_process_klarna_order_complete($post_id, $klarna_order_id);
			} else {
				// Fallback: just update payment status
				update_post_meta($post_id, 'wpgv_payment_status', 'Completed');
				$voucher_table = $wpdb->prefix . 'giftvouchers_list';
				if ($wpdb->get_var("SHOW TABLES LIKE '$voucher_table'")) {
					$wpdb->update(
						$voucher_table,
						array('payment_status' => 'Paid'),
						array('id' => $post_id),
						array('%s'),
						array('%d')
					);
				}
			}

			error_log('Klarna: completed processing for post_id ' . $post_id);

			// Return success with redirect URL - use configured success page or fallback
			$klarna_success_page_id = get_option('wpgv_klarna_success_page');
			if ($klarna_success_page_id && $klarna_success_page_id > 0) {
				$success_url = get_permalink($klarna_success_page_id);
				// Append order_id parameter
				$success_url = add_query_arg('order_id', urlencode($klarna_order_id), $success_url);
			} else {
				// Fallback to default URL
				$success_url = get_site_url() . '/voucher-payment-successful/?order_id=' . urlencode($klarna_order_id);
			}

			wp_send_json_success(array(
				'message' => 'Payment completed successfully',
				'order_id' => $klarna_order_id,
				'captured' => $capture_success,
				'redirect_url' => $success_url
			));
		} else {
			error_log('Klarna: order created but no order_id in response: ' . wp_json_encode($data));
			wp_send_json_error(array('message' => 'Order created but no order_id returned'));
		}
	} else {
		$error_msg = !empty($data['error_message']) ? $data['error_message'] : (!empty($data['error_code']) ? $data['error_code'] : $body);
		error_log('Klarna: authorization/order capture failed - HTTP ' . $code . ' - ' . $error_msg);
		error_log('Klarna: full error response: ' . wp_json_encode($data));
		wp_send_json_error(array(
			'message' => 'Payment authorization failed: ' . $error_msg,
			'error_code' => $data['error_code'] ?? 'UNKNOWN'
		));
	}

	wp_die();
}

add_action('wp_ajax_nopriv_wpgv_klarna_authorize', 'wpgv_klarna_authorize_handler');
add_action('wp_ajax_wpgv_klarna_authorize', 'wpgv_klarna_authorize_handler');
