<?php

/* ========================================================================
 * $Id: order.php 2118 2017-05-20 06:04:53Z onez $
 * 
 * Email: www@onez.cn
 * QQ: 6200103
 * HomePage: http://www.onezphp.com
 * ========================================================================
 * Copyright 2016-2017 佳蓝科技.
 * 
 * ======================================================================== */

!defined('IN_ONEZ') && exit('Access Denied');
class onezphp_order extends onezphp{
  function __construct(){
    
  }
  function orderno($price,$subject,$extra=false){
    $orderno=date('YmdHis').rand(100000,999999);
    $order=array();
    $order['price']=$price;
    $order['status']='wait';
    $order['subject']=$subject;
    $order['addtime']=time();
    $order['lasttime']=time();
    if($extra && is_array($extra)){
      foreach($_REQUEST as $k=>$v){
        if(strpos($k,'data-')===0){
          $extra[substr($k,5)]=$v;
        }
      }
      foreach($extra as $k=>$v){
        $order[$k]=$v;
      }
    }
    foreach(onez('cache')->find('order/nopay/*') as $v){
      if(filemtime($v)<time()-86400){
        @unlink($v);
      }
    }
    onez('cache')->set('order/nopay/'.$orderno,$order);
    return $orderno;
  }
  function update($orderno,$extra){
    if($extra){
      $order=onez('cache')->get('order/nopay/'.$orderno);
      if($order){
        foreach($extra as $k=>$v){
          $order[$k]=$v;
        }
        onez('cache')->set('order/nopay/'.$orderno,$order);
      }
    }
  }
  function load($token, $id = 0){
    $orderno=$token;
    $order=onez('cache')->get('order/nopay/'.$orderno);
    if(!$order){
      $order=onez('cache')->get('order/payok/'.$orderno);
    }
    $order['orderno']=$orderno;
    return $order;
  }
  function payback($orderno,$price,$extra){
    $order=onez('cache')->get('order/nopay/'.$orderno);
    if($order){//未支付
      if($price==$order['price']){
        $order['status']='payok';
        $order['paytime']=time();
        $order['extra']=$extra;
      }else{
        $order['status']='payerr';
        $order['error']='支付金额不符';
      }
      onez('cache')->remove('order/nopay/'.$orderno);
      onez('cache')->set('order/payok/'.$orderno,$order);
      $order['orderno']=$orderno;
      return $order;
    }
    $order=onez('cache')->get('order/payok/'.$orderno);
    if($order){//已处理
      $order['orderno']=$orderno;
      return $order;
    }
    return array(
      'error'=>'订单号不存在或已超时',
    );
  }
}