<?php
use Omnipay\Omnipay;

$api_key = get_option('mollie_api_key', 'payments');


$gateway = Omnipay::create('Mollie');
$gateway->setApiKey($api_key);

 
$formData = include(dirname(__DIR__).DS.'lib'.DS.'omnipay'.DS.'omnipay_populate_form_data.php');
try {
    // Send purchase request
    //$response = $gateway->purchase(
    $response = $gateway->purchase(
        array(
            'amount'   => $place_order['amount'],
            'currency' => $place_order['currency'],
			'description' => $place_order['item_name'],
			'transactionId' => $place_order['payment_verify_token'],

			
			'returnUrl' => $mw_return_url,
			'notifyUrl' => $mw_ipn_url,
			'cancelUrl' => $mw_cancel_url,
        )
    )->send();

    if ($response->isSuccessful()){
        $place_order['transaction_id'] = $response->getTransactionReference(); // a reference generated by the payment gateway
        $place_order['success'] = 'Your payment was successful! ' . $response->getMessage();


        $place_order['order_completed'] = 1;


        $response = $gateway->fetchTransaction(
            array(

                'transactionReference' => $place_order['transaction_id'],

            )
        )->send();
        if ($response->isSuccessful()) {
            $data = $response->getData();
            $place_order['is_paid'] = 0;

            if (isset($data['status'])) {

                if (isset($data['amount']) and is_array($data['amount'])) {
                    $data['payment_amount'] = $data['amount']['value'];
                    $data['payment_currency'] = $data['amount']['currency'];

                }
                $data['payment_status'] = $data['status'];
                if (isset($data['status']) and $data['status'] == 'paid') {
                    $place_order['is_paid'] = 1;


                } else {
                    $place_order['is_paid'] = 0;

                }
                if (isset($data['profileId'])) {
                    $place_order['payer_id'] = $data['profileId'];
                }
                $place_order['payment_data'] = $data;

            }

        }






    } elseif ($response->isRedirect()) {
        $place_order['transaction_id'] = $response->getTransactionReference(); // a reference generated by the payment gateway
		$place_order['order_completed'] = 1;
		$place_order['is_paid'] = 0;
		$place_order['redirect'] = $response->getRedirectUrl();
		
 
       // return $response->redirect();

    } else {
        $place_order['error'] = $response->getMessage();

    }
} catch (\Omnipay\Common\Exception\InvalidCreditCardException $e) {
    $msg = $e->getMessage();

    $place_order['error'] = $msg;

} catch (\Exception $e) {
    $msg = $e->getMessage();
    $place_order['error'] = $msg;


}


//$place_order['order_completed'] = 1;
//$place_order['is_paid'] = 0;
//$place_order['success'] = _e('Thank you for your order', true);
