<?php
class ModelPaymentUseepay extends Model {
    public function getMethod($address) {
        $this->load->language('payment/useepay');

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('useepay_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");

        if ($this->config->get('useepay_total') > 0 && $this->config->get('useepay_total') > $total) {
            $status = false;
        } elseif (!$this->config->get('useepay_geo_zone_id')) {
            $status = true;
        } elseif ($query->num_rows) {
            $status = true;
        } else {
            $status = false;
        }

        $method_data = array();

        if ($status) {
            $method_data = array(
                'code'         => 'useepay',
                'title'      => $this->config->get('useepay_payment_title'),
                'terms'      => '',
                'sort_order' => $this->config->get('useepay_sort_order')
            );
        }
        return $method_data;
    }


    /**
     * 写入对账表
     * @param $order_id
     * @param $useepay_order_id
     */
    public function addOrder($order_id, $useepay_order_id)
    {
        $this->db->query("insert into `" . DB_PREFIX . "useepay_order_map` 
            set `order_id` = " . (int)$order_id . ",
			`useepay_order_id` = '" . $useepay_order_id . "',
			`create_at` = now(), `update_at` = now();");
    }

    /**
     * 更新对账表
     * @param $order_id
     * @param $useepay_order_id
     */
    public function updateOrder($order_id, $useepay_order_id)
    {
        $this->db->query("update `" . DB_PREFIX . "useepay_order_map` set `useepay_order_id` = '" . $useepay_order_id . "',
			`update_at` = now() where `order_id` = " . (int)$order_id . ";");
    }

    /**
     * 根据orderId获取对账信息
     * @param $order_id
     * @return bool
     */
    public function getOrderById($order_id)
    {

        $result = $this->db->query("select * from `" . DB_PREFIX . "useepay_order_map` where `order_id` = " . (int)$order_id . " order by id desc limit 1;");

        if ($result->num_rows) {
            return $result->row;
        } else {
            return false;
        }
    }

    /**
     * 根据Useepay订单Id获取orderID
     * @param $useepay_order_id
     * @return bool
     */
    public function getOrderByUseepayId($useepay_order_id)
    {
        $result = $this->db->query("select * from `" . DB_PREFIX . "useepay_order_map` where `useepay_order_id` = " . $useepay_order_id . " order by id desc limit 1;");

        if ($result->num_rows) {
            return $result->row;
        } else {
            return false;
        }
    }
}
