<?php

/**
 * NMI Direct Post Helper
 * 
 * Lightweight helper for Direct Post transactions when public tokenization key is not available.
 * PCI SAQ-A compliance requires that card data is never stored or logged.
 *
 * @package PeachPay
 */

if (!defined('PEACHPAY_ABSPATH')) {
    exit;
}

class PeachPay_NMI_Direct_Post
{
    private $private_key;

    /**
     * Constructor
     *
     * @param string $private_key Private security key from NMI
     */
    public function __construct($private_key)
    {
        $this->private_key = $private_key;
    }

    /**
     * Get the API endpoint URL.
     *
     * @return string
     */
    private function get_endpoint()
    {
        return PeachPay_NMI_Integration::get_api_endpoint();
    }

    /**
     * Charge an order using Direct Post
     *
     * @param WC_Order $order WooCommerce order object
     * @param array    $card_data Card data array with keys: number, exp, cvv
     * @param string   $transaction_type 'sale' or 'auth'
     * @return array|WP_Error Response from NMI API or WP_Error on failure
     */
    public function charge(WC_Order $order, array $card_data, $transaction_type = 'sale')
    {
        $body = array(
            'security_key' => $this->private_key,
            'type'         => $transaction_type,
            'amount'       => number_format($order->get_total(), 2, '.', ''),
            'ccnumber'     => $card_data['number'],
            'ccexp'        => $card_data['exp'],
            'cvv'          => $card_data['cvv'],
            'orderid'      => $order->get_order_number(),
            'email'        => $order->get_billing_email(),
            'firstname'    => $order->get_billing_first_name(),
            'lastname'     => $order->get_billing_last_name(),
            'address1'     => $order->get_billing_address_1(),
            'address2'     => $order->get_billing_address_2(),
            'city'         => $order->get_billing_city(),
            'state'        => $order->get_billing_state(),
            'zip'          => $order->get_billing_postcode(),
            'country'      => $order->get_billing_country(),
            'phone'        => $order->get_billing_phone(),
        );

        // Add shipping information if available
        if ($order->has_shipping_address()) {
            $body['shipping_firstname'] = $order->get_shipping_first_name();
            $body['shipping_lastname']  = $order->get_shipping_last_name();
            $body['shipping_company']   = $order->get_shipping_company();
            $body['shipping_address1']  = $order->get_shipping_address_1();
            $body['shipping_address2']  = $order->get_shipping_address_2();
            $body['shipping_city']      = $order->get_shipping_city();
            $body['shipping_state']     = $order->get_shipping_state();
            $body['shipping_zip']       = $order->get_shipping_postcode();
            $body['shipping_country']   = $order->get_shipping_country();
        }

        // Add receipt email if enabled
        $gateway_settings = get_option('woocommerce_peachpay_nmi_card_settings', array());
        if (isset($gateway_settings['receipt']) && $gateway_settings['receipt'] === 'yes') {
            $body['email_receipt'] = '1';
        }

        // Make API request
        $response = wp_remote_post($this->get_endpoint(), array(
            'body'    => $body,
            'timeout' => 45,
            'headers' => array(
                'Content-Type' => 'application/x-www-form-urlencoded'
            )
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        // Parse response
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        if ($response_code !== 200) {
            return new WP_Error('nmi_api_error', sprintf(__('NMI API error (HTTP %d)', 'peachpay-for-woocommerce'), $response_code));
        }

        // Parse NMI response (format: response=1&responsetext=SUCCESS&transactionid=...)
        parse_str($response_body, $parsed_response);
        return $parsed_response;
    }
}
