<?php
/**
 * @package     Reporter for VirtueMart
 * @subpackage  Reporter for VirtueMart - Due Date
 * @copyright   Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @author      Abhishek Das <info@virtueplanet.com> - https://www.virtueplanet.com
 */

defined ('_JEXEC') or die;

/**
* Reporter for VirtueMart - Due Date Plugin
*/
class plgVmreporterDuedate extends JPlugin
{
	public function onPrepareSortableFields(&$sortableFields, $template_id)
	{
		if(isset($sortableFields['created_on']))
		{
			unset($sortableFields['reporter_order_due_date']);

			$keys = array_keys($sortableFields);
			$vals = array_values($sortableFields);

			$insertAfter = array_search('created_on', $keys) + 1;

			$keys2 = array_splice($keys, $insertAfter);
			$vals2 = array_splice($vals, $insertAfter);

			$keys[] = 'reporter_order_due_date';
			$vals[] = $this->params->get('field_name', 'Due Date');

			$sortableFields = array_merge(array_combine($keys, $vals), array_combine($keys2, $vals2));
		}
		else
		{
			$sortableFields['reporter_order_due_date'] = $this->params->get('field_name', 'Due Date');
		}
	}
	
	public function onPrepareReportItems(&$items, $template_id)
	{
		$params = JComponentHelper::getParams('com_vmreporter');
		
		foreach($items as &$item)
		{
			if(isset($item['created_on']) && $item['created_on'] > 0)
			{
				$due_date = JFactory::getDate($item['created_on']);
				$interval = (int) $this->params->get('interval', 30);
				
				if($interval < 0)
				{
					$due_date->modify('-' . $interval . ' days');
				}
				elseif($interval == 1)
				{
					$due_date->modify('+1 day');
				}
				else
				{
					$due_date->modify('+' . $interval . ' days');
				}
				
				if($params->get('date_format', 0))
				{
					$item['reporter_order_due_date'] = $due_date->format('Y-m-d');
				}
				else
				{
					$item['reporter_order_due_date'] = $due_date->toSql();
				}
				
			}
			else
			{
				if($params->get('date_format', 0))
				{
					$item['reporter_order_due_date'] = '0000-00-00';
				}
				else
				{
					$item['reporter_order_due_date'] = '0000-00-00 00:00:00';
				}
			}
		}
	}
}