<?php

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

use \Verifone\Core\DependencyInjection\CoreResponse\PaymentResponseImpl;
use \Verifone\Core\DependencyInjection\CoreResponse\Interfaces\Card;

class WC_Verifone_Observer
{

    /**
     *
     */
    public static function refreshSavedCards( $order = null )
    {
        if (WC_Verifone_Config::getInstance()->isAllowToSaveCC()) {
            try {
                $response = WC_Verifone_Core_SavedPaymentMethods::getListSavedPaymentMethods();

                if($response === null) {
                    return false;
                }

                $cards = $response->getBody();
                if (count($cards)) {
                    foreach ($cards as $card) {
                        WC_Verifone_Core_SavedPaymentMethods::addCard($card, $order);
                    }
                }
            } catch (Exception $e) {
                // no cards
            }
        }
    }

    /**
     * @param WC_Order $order
     * @param PaymentResponseImpl $body
     * @return array
     */
    public static function addMaskedPanNumber($order, $body)
    {
        $config = WC_Verifone_Config::getInstance();
        if (!$config->isSaveMaskedPanNumber()) {
            return [$order, $body];
        }

        /** @var Card $card */
        $card = $body->getCard();

        if (
            strlen($card->getFirst6()) &&
            $card->getFirst6() &&
            strlen($card->getLast2()) &&
            $card->getLast2()
        ) {

            if (empty($order->get_meta('masked_pan_number'))) {
                $maskedPanNumber = $card->getFirst6() . '********' . $card->getLast2();
                $order->add_meta_data('masked_pan_number', $maskedPanNumber);
            }

            return [$order, $body];
        }

        return [$order, $body];
    }

    /**
     * Add a custom action to order actions select box on edit order page
     * Only added for paid orders that haven't fired this action yet
     *
     * @param array $actions order actions array to display
     * @return array - updated actions
     */
    public static function addCheckOrderPaymentAction( $actions ) {
        /** @var WC_Order $theorder */
        global $theorder;

        if ( $theorder->get_payment_method() !== WC_VERIFONE_GATEWAY_ID ) {
            return $actions;
        }

        if ( $theorder->is_paid() ) {
            return $actions;
        }

        $actions['verifone_check_order_payment'] = esc_html__( 'Verifone: Check payment status', 'verifone-bluecommerce-for-woocommerce' );
        return $actions;

    }

    public static function executeCheckOrderPaymentAction( WC_Order $order, $cron = false ) {
        if ( $order->is_paid() ) {
            return true;
        }

		$wc_statuses = wc_get_order_statuses();

		try {
			$result = WC_Verifone_Payment::checkPaymentStatus( $order, $cron );
		} catch ( Exception $e ) {
			$message = sprintf( esc_html__( 'Payment status check failed: %s', 'verifone-bluecommerce-for-woocommerce' ), $e->getMessage() );
			if ( ! $cron ) {
				WC_Verifone_Notice::addError( $message, false, true );
			}
			$order->add_order_note( $message );
			return;
		}

        if ( $result === true ) {
            $status = $order->needs_processing() ? 'processing' : 'completed';
			$order->update_status( $status );

            $message = sprintf( esc_html__( 'Payment was found. Changed order status to %s.', 'verifone-bluecommerce-for-woocommerce' ), mb_strtolower( $wc_statuses[ 'wc-' . $status ] ) );
            if ( ! $cron ) {
                WC_Verifone_Notice::addSuccess( $message, false, true );
            }
        } elseif ( $result === null ) {
            $message = esc_html__( 'Payment has not been confirmed yet.', 'verifone-bluecommerce-for-woocommerce' );
            if ( ! $cron ) {
                WC_Verifone_Notice::addInfo( $message, false, true );
            }
        } else {
			$order->update_status( 'cancelled' );

            $message = sprintf( esc_html__( 'Payment was cancelled. Changed order status to %s.', 'verifone-bluecommerce-for-woocommerce' ), mb_strtolower( $wc_statuses[ 'wc-cancelled' ] ) );
            if ( ! $cron ) {
                WC_Verifone_Notice::addError( $message, false, true );
            }
        }

        if ( ! $cron ) {
            $note = esc_html__( 'Manual payment status check result: ', 'verifone-bluecommerce-for-woocommerce' );
        } else {
            $note = esc_html__( 'Automatic payment status check result: ', 'verifone-bluecommerce-for-woocommerce' );
        }
        $order->add_order_note($note . ' ' . $message);
    }


}
