<?php
/**
 * FW Food menu 5.1.1
 * @copyright (C) 2020 Fastw3b
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 * @link http://www.fastw3b.net/ Official website
 **/

defined( '_JEXEC' ) or die( 'Restricted access' );

class TableOrder extends JTable {
    var $id = null,
		$created = null,
        $booked_on = null,
    	$name = null,
    	$email = null,
    	$phone = null,
    	$comments = null,
    	$amount = null,
        $tax = null,
        $delivery = null,
        $address = null,
        $payment_gate_id = null,
        $paid = null,
        $status = null,
        $status_updated = null,
        $delivery_code = null,
        $delivery_option = null,
        $params = null,
        $lang = null;

    var $_items_qty = 0,
        $_items = array(),
        $_now = null,
        $_orders_qty = null,
        $_prev_status = null,
        $_status_name = null,
        $_payment_option = null,
        $_statuses_qty = null,
        $_statuses = array();

    function __construct(&$db) {
        parent::__construct('#__fwfoodmenu_order', 'id', $db);
    }

	function load($oid = null, $reset = null) {
		if ($oid) {
            $db = JFactory::getDBO();
            $db->setQuery('
SELECT
    o.*,
    NOW() AS _now,
    (SELECT COUNT(*) FROM `#__fwfoodmenu_order_items` AS oi WHERE oi.order_id = o.id) AS _items_qty,
    (SELECT COUNT(*) FROM `#__fwfoodmenu_order_statuschage` AS oi WHERE oi.order_id = o.id) AS _statuses_qty,
	(SELECT COUNT(*) FROM `#__fwfoodmenu_order` AS oo WHERE oo.created <= o.created AND ((o.phone IS NOT NULL AND o.phone <> \'\' AND oo.phone = o.phone) OR (o.email IS NOT NULL AND o.email <> \'\' AND oo.email = o.email))) AS _orders_qty
FROM
    `#__fwfoodmenu_order` AS o
WHERE
    o.id = '.(int)$oid
            );
            if ($obj = $db->loadObject()) {
                foreach ($obj as $key=>$val) {
                    $this->$key = $val;
                }
                $this->_prev_status = $this->status;
                $this->_status_name = JText::_('FWFM_ORDER_STATUS_'.$this->status);
                $this->_payment_option = JText::_('FWFM_PAYMENT_GATE'.($this->payment_gate_id?$this->payment_gate_id:1));
                if ($this->_items_qty) {
                    $db->setQuery('SELECT * FROM `#__fwfoodmenu_order_items` WHERE order_id = '.(int)$this->id);
                    if ($this->_items = $db->loadObjectList()) {
                        foreach ($this->_items as $i=>$item) {
                            $this->_items[$i]->_formatted_price = fwFoodMenuHelper::formatPrice($item->price);
                            $this->_items[$i]->params = new JRegistry($item->params);
                        }
                    }
                }
                if ($this->_statuses_qty) {
                    $db->setQuery('SELECT * FROM `#__fwfoodmenu_order_statuschage` WHERE order_id = '.(int)$this->id.' ORDER BY created');
                    $this->_statuses = $db->loadObjectList();
                }
                $this->params = new JRegistry($this->params);
	            return true;
            }
		}
    }

    function bind($data, $skip=array()) {
        if ($data) {
            $app = JFactory::getApplication();
            $app->triggerEvent('onBindOrder', array('com_fwfoodmenu', $data, &$skip, $this));

            $keys = array_keys($this->getProperties());
            foreach ($data as $key=>$val) {
                if (!in_array($key, $keys) or ($skip and in_array($key, $skip))) {
                    continue;
                }
                $this->$key = $val;
            }
        }
        return true;
    }
    function check() {
        if (!$this->amount) {
			$this->setError(JTExt::_('FWFM_NO_MEAL_IN_THE_ORDER'));
            return;
        }
		if (!$this->name) {
			$this->setError(JTExt::_('FWFM_ENTER_YOUR_NAME'));
			return;
		}
		if (!$this->phone) {
			$this->setError(JTExt::_('FWFM_ENTER_YOUR_PHONE'));
			return;
		}
        if ($this->status and !in_array($this->status, array('pending', 'confirmed', 'prepared', 'shipped', 'delivered', 'completed', 'cancelled', 'refunded'))) {
			$this->setError(JTExt::_('FWFM_UNKNOWN_STATUS'));
			return;
        }
		if (!$this->booked_on) {
			$this->setError(JTExt::_('FWFM_ENTER_ORDER_DATE_TIME'));
			return;
		} else {
            $time = strtotime(fwFoodMenuHelper::encodeDate($this->booked_on));
            $this->booked_on = JFactory::getDate($time)->toSql();
        }
        if (!$this->id) {
            $this->created = JFactory::getDate()->toSql();
        }
        $app = JFactory::getApplication();
        $results = $app->triggerEvent('onCheckOrder', array('com_fwfoodmenu', $this));
        if ($results) {
            foreach ($results as $result) {
                if (!$result) {
                    return;
                }
            }
        }
        $params = new JRegistry($this->params);
        $this->params = $params->toString();
        if ($this->id and $this->_prev_status != $this->status) {
            $db = JFactory::getDBO();
            $db->setQuery('INSERT INTO `#__fwfoodmenu_order_statuschage` SET order_id = '.$this->id.', created = '.$db->quote(JFactory::getDate()->toSql()).', status = '.$db->quote($this->status));
            $db->execute();
        }
        return true;
    }
    function delete($id=null) {
        if (parent::delete($id)) {
            $db = JFactory::getDBO();
            $db->setQuery('DELETE FROM `#__fwfoodmenu_order_items` WHERE order_id = '.(int)$id);
            $db->execute();
            $db->setQuery('DELETE FROM `#__fwfoodmenu_order_statuschage` WHERE order_id = '.(int)$id);
            $db->execute();
            $app = JFactory::getApplication();
            $app->triggerEvent('onDeleteOrder', array('com_fwfoodmenu', $id, $this));
            return true;
        }
    }
}
