<?php
/**
* @file cart.php
* @copyright (c) 2005 - 2011 eifr.com
* @license http://www.gnu.org/copyleft/gpl.html gnu/gpl
* eifr is free software
*/

require_once(dirname(__FILE__).'/includes/inc_general.php');
require_once(EIFR_ROOT . 'admin/mod_order/order.config.php');

function getOrderNumber($num = 0)
{
    //time(11bit) + num(1bit)
    $order_number = time() . $num;
    if(! dbGetRecordCount(TB_ORDER, "order_number='$order_number'")) {
        return $order_number;
    }
    getOrderNumber($num++);
    
}

function checkArticleQuantity($id, $num = 0)
{
    global $lang;
    $articl_quantity = dbGetFieldValue(TB_ARTICLE, 'quantity', 'id='.$id);
    if($num > $articl_quantity) {
        Log_e(__FILE__,__LINE__,'quantity is not enough ($num > $articl_quantity)');
        goErrorPage($row['title'].' '.$lang['over_maxnum'].':'.$articl_quantity);
    }
}

function addOrder($cartContents)
{
    global $lang, $cfgarr_order_payment, $cfgarr_order_deliver, $cfgarr_order_deliver_fare;
    Log_d(__FILE__,__LINE__,'addOrder start...');
    $order_number = getOrderNumber();
    $total_quantity = 0;
    $total_price = $cfgarr_order_deliver_fare[kPost('delivery_id')];

    foreach($cartContents as $row) {
        checkArticleQuantity($row['id'], $row['quantity']);
        
        updateArticleQuantity($row['id'], -$row['quantity']);
    
        $total_quantity += $row['quantity'];
        $total_price += $row['price'] * $row['quantity'];
        
        $article = array(
            'order_id' =>  $order_number,
            'article_id' => $row['id'],
            'quantity' => $row['quantity'],
            'price' => $row['price'],
            'flag' => 0,
        );

        dbInsert(TB_ORDER_ARTICLE, $article);
    }
 
    // add order
    $recordarr = array(
        'addtime' => time(),
        'order_number' => $order_number,
        'uid' => getCookie(COOKIE_UID),
        'username' => getCookie(COOKIE_USERNAME),
        'count' => $total_quantity,
        'total' => $total_price,
        'fare' => $cfgarr_order_deliver_fare[kPost('delivery_id')],
        'is_invoice' => kPost('is_invoice'),
        'leave_words' => stripTags(kPost('leave_words')),
        'payment_id' => $cfgarr_order_payment[kPost('payment_id')],
        'delivery_id' => $cfgarr_order_deliver[kPost('delivery_id')],
        'flag' => 1,
        'status' => 0,

        'realname' => kPost('realname'),
        'gender' => 0,
        'address' => kPost('address'),
        'zipcode' => kPost('zipcode'),
        'email' => kPost('email'),
        'tel' => kPost('tel'),
        'mobile' => kPost('mobile'),
    );
    
    if( dbInsert(TB_ORDER, $recordarr)){
        return  $order_number;
    }
    return false;
}


if(empty($uid)) {
    goPage('login.php', 'cart.php');
}

$url = $_SERVER["PHP_SELF"];
$errormsg = '';

$clCart = new CCart();
$cartContents = $clCart->getCart();

//---start---
$search_select = Common::creatSelect(TB_CHANNEL,'id','title','',"length(id)=2 and status=0 and flag<>2 order by ordernum ");
$navigation = '>>'. $lang['cart'];

$act = kRequest('act');
if($act=='add') {
    Log_v(__FILE__,__LINE__,'add cart');
    $sql="select id,title,price,fileurl from ".TB_ARTICLE." where id=$id";
    $rs = dbGetRecord1($sql);
    if(!$rs) {
        header("Location:error.php");
    }
    $rs['quantity'] = 1;
    $rc = $clCart->addCart($rs);
    if($rc) {
        header("Location:cart.php");
    }
} else if($act=='del') {
    Log_v(__FILE__,__LINE__,"delete article id:$id from cart");
    $clCart->delCart($id);
    header("Location:cart.php");
} else if($act=='empty') {
    Log_v(__FILE__,__LINE__,'empty cart');
    $clCart->emptyCart();
    header("Location:cart.php");
} else if($act=='modify') {
    Log_v(__FILE__,__LINE__,'modify cart');
    $clCart->updateCartByField('quantity', $quantity);
    header("Location:cart.php?act=order");
} else if($act=='save') {
    $order_number = addOrder($cartContents);
    if($order_number) {
        $clCart->emptyCart();
        Log_v(__FILE__,__LINE__,'save cart to order ok');
        header("Location:cart.php?act=orderok&orderno=$order_number");
    }else{
        Log_e(__FILE__,__LINE__,'save cart to order fail');
        goErrorPage('save cart to order fail');
    }
} else if($act=='order') {
    $sql="select * from ".TB_USER." where uid=$uid";
    $rsUser = dbGetRecord1($sql);

}

$tpl_file = 'cart';
require_once(getTemplatePath($tpl_file));
?>

