<?php

namespace Payment\Lib;

use Dever;

class Core
{
	/**
     * update order status
     */
    protected function updateOrder($order_id, $cash, $desc = '')
    {
        $db = Dever::db('payment/order');
        $info = $db->one(array('order_id' => $order_id, 'status' => 1));
        if ($info) {
            $param['where_id'] = $info['id'];
            $param['status'] = 2;
            $msg = '支付成功';
            if ($desc) {
                $lang = Dever::lang($desc);
                $param['status'] = 3;
                $param['status_desc'] = $desc;
                $msg = '支付失败||' . $desc;
            }
            $this->log($msg, $info);
            $db->update($param);

            if (isset($lang)) {
                return $this->out($lang);
            }
        } else {
            return $this->out('invalid_order');
        }
    }

    /**
     * update order param
     */
    protected function updateOrderParam($order_id, $param)
    {
        $db = Dever::db('payment/order');
        $info = $db->one(array('order_id' => $order_id, 'status' => 1));
        if ($info) {
            $param['where_id'] = $info['id'];
            $param['param'] = Dever::array_encode($param);
            $db->update($param);
        }
    }

    /**
     * create order
     */
    protected function createOrder($uid, $account, $product_name, $amount, $currency, $type_id, $type_name)
    {
        $db = Dever::db('payment/order');
        $order_id = Dever::order($account);
        $info = $db->one(array('order_id' => $order_id));
        if ($info) {
            return $this->createOrder();
        } else {
            $add['status'] = 1;
            $add['uid'] = $uid;
            $add['account'] = $account;
            $add['product_name'] = $product_name;
            $add['amount'] = $amount;
            $add['currency'] = $currency;
            $add['order_id'] = $order_id;
            $add['type'] = $type_id;
            $add['id'] = $db->insert($add);
            $msg = '发起支付';
            $this->log($msg, $add);
        }
        return $order_id;
    }

    /**
     * 获取回调url
     */
    protected function url($type)
    {
        $project = Dever::project('payment');
        return $project['url'] . 'daemon/notify/'.$type.'.php';
    }

    /**
     * 写日志
     */
    protected function log($msg, $data = array())
    {
        if ($data) {
            $data = Dever::json_encode($data);
            $msg .= '||' . $data;
        }

        Dever::log($msg, 'pay');
    }

    /**
     * result
     *
     * @return mixed
     */
    protected function out($msg)
    {
        $result = array();
        $result['status'] = 2;

        $refer = Dever::session('refer');
        if ($msg == 'ok') {
            $result['status'] = 1;
        }
        $result['msg'] = Dever::lang($msg);
        if (!$refer) {
            Dever::alert($msg);
        }
        
        return $result;
    }
}
