<?php
namespace Sts\SmartRoute\Cron;

use Psr\Log\LoggerInterface;
use Sts\SmartRoute\Model\PaymentMethod as SmartRoutePaymentMethod;
use Magento\Sales\Model\Order;

class InquiryPendingOrders{
    
    /**
     *
     * @var \Psr\Log\LoggerInterface 
     */
    private $logger;
    
    /**
     *
     * @var SmartRoutePaymentMethod 
     */
    private $_paymentMethod;
    
    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
     */
    protected $_orderCollectionFactory;    

    public function __construct(LoggerInterface $logger, 
            SmartRoutePaymentMethod $paymentMethod,
            \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory) {
        $this->logger = $logger;
        $this->_paymentMethod = $paymentMethod;
        $this->_orderCollectionFactory = $orderCollectionFactory;
    }

/**
   * Write to system.log
   *
   * @return void
   */

    public function execute() {
        $this->logger->info('smartroute start processing inquiry for pending orders');
    
        
        
        /*@var $orderColl \Magento\Sales\Model\ResourceModel\Order\Collection */
     	$orderColl = $this->_orderCollectionFactory->create();        
        $orderColl->getSelect()->join(
                array(/* joined table alias = */ 
                    'order_payment' => $orderColl->getTable('sales_order_payment')),
                    'main_table.entity_id = order_payment.parent_id',
                    /* array of columns */ array()
                );                
        

        //$dateFrom = date('Y-m-d H:i:s', time() - $this->_paymentMethod->getConfigData('inquiry_in_minutes')*60*2);                        
        $dateTo = date('Y-m-d H:i:s', time() - $this->_paymentMethod->getConfigData('inquiry_in_minutes')*60);
    	$orderColl->addAttributeToFilter('state', array('neq' => $this->_paymentMethod->getConfigData('complete_order_status')));
    	$orderColl->addAttributeToFilter('status', array('neq' => Order::STATE_CANCELED));
    	$orderColl->addAttributeToFilter('status', array('neq' => Order::STATE_CLOSED));
    	$orderColl->addAttributeToFilter('status', array('neq' => Order::STATE_COMPLETE));
    	$orderColl->addAttributeToFilter('state', array('neq' => Order::STATE_CLOSED));
        $orderColl->addAttributeToFilter('order_payment.created_at', array('to'=>$dateTo));    	
        $orderColl->addFieldToFilter('order_payment.method', $this->_paymentMethod->getCode());    	
                        
    	$orders = $orderColl->getItems();
        
        $this->logger->info('smartroute found '.count($orders).' to inquire');
        
    	foreach($orders as $order)
    	{
            /*@var $order Mage_Sales_Model_Order */
            $this->logger->info('smartroute calling inquiry method on order#'.$order->getId());
            $this->_paymentMethod->processAPIInquiry($order);
    	}
         
    }


}