<?php
//session_start();  

include_once '_function/_funs.php';
$GUID              = "";
$showMenu          = "";
$CFG_statedisabled = 0;
$LastOrderID=null;
$CompanyName=null;
$MyComputerName = 'PDA';
include_once '_dbdir.php';

//$_SESSION['forcein']=0;

if ($CFG_ShowDesk==1 && $CFG_QRCodeInsideEnable==1 && strlen($CFG_QRCodeInsideTOKEN)>0){
	//店内二维码TOKEN 
	 if (!isset($_REQUEST['uid'])) { 
		 //未设置token，禁用餐台功能
		 $CFG_ShowDesk=0;
	 }else if ($_REQUEST['uid'] == $CFG_QRCodeInsideTOKEN) {	
		 $CFG_ShowDesk=1;
	 }else{
		 //token不正确，禁用餐台功
		 $CFG_ShowDesk=0;
	 }
	//die($CFG_QRCodeInsideTOKEN.' / '.$_REQUEST['uid'].' / '.$CFG_ShowDesk);
}

if (isset($_POST['showMenu']))
    $showMenu = $_POST['showMenu'];

if ($showMenu == 'logoff') {
    // 把失效日期设置为一小时前
    @setcookie('wechat', 0, time() - 3600);
    //@setcookie ("wechat", "", time() - 3600);
    if ($debug)
        console_log('logoff');
    die('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <!-- meta使用viewport以确保页面可自由缩放 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="refresh" content="1"><br><br><hr>Gracias,hasta pronto!<br><br><hr>谢谢光临，再见！<br><br><hr>Thank you for coming, goodbye！<br><br><hr>');
	
} elseif ($CFG_QRCodeDeskEnable==1 && strlen($CFG_QRCodeDeskTOKEN)>0 && isset($_REQUEST['forcein']) && isset($_REQUEST['uid'])&& $_REQUEST['uid'] == $CFG_QRCodeDeskTOKEN) {	
//餐桌二维码TOKEN 
	$forcein=1;
	//$_SESSION['forcein']=1;
	$CFG_ShowDesk=0;
    $GUID = $_REQUEST['forcein'];
} elseif (isset($_COOKIE["wechat"])) {
    $GUID = $_COOKIE['wechat'];
    if ($debug)
        console_log('isset _COOKIE wechat : ' . $GUID);
} elseif (isset($_REQUEST['login'])) {
    //登录调用这里
    $usernameInit = $_REQUEST['username3330'];
    $passwordInit = $_REQUEST['password3330'];
    if ($debug)
        console_log('isset _login');
} elseif (isset($_REQUEST['reg_username3330'])) {
    //注册
    $GUID = $_REQUEST['reg_username3330'];
    console_log('注册 isset _username3330');
} elseif (isset($_REQUEST['wechat'])) {
    $GUID = $_REQUEST['wechat'];
    if ($debug)
        console_log('isset _REQUEST useraut ' . $GUID);
    //setcookie("wechat", $GUID);
}


if (isset($_REQUEST['location'])) {
    $location = $_REQUEST['location'];
    if ($debug)
        console_log('isset _REQUEST useraut ' . $GUID);
    setcookie("location", $location);
}





if (isset($_REQUEST['newOrder']) && $_REQUEST['newOrder'] == 1) {
    include_once 'neworder.php';
}

$is_exist = 0;

if ($debug)
    console_log('Login :' . $usernameInit);

//用户验证
if (!empty($usernameInit)) {
    $query_RecordsetCFG = "SELECT top 1 CompanyName,CustomerID FROM Customers where cast(username as varchar(max))='" . save2mssql($usernameInit) . "' and cast(password as varchar(max))='" . save2mssql($passwordInit) . "'";
    if ($debug)
        console_log("验证和客户A    :    " . save2mssql($usernameInit));
    
    //die( $query_RecordsetCFG);
    $values = $orders->query($query_RecordsetCFG);
    if (is_iterable($values)) {
        foreach ($values as $row_RecordsetCFG) {
            $is_exist                        = 1;
            $row_RecordsetCFG['CompanyName'] = loadFromMssql($row_RecordsetCFG['CompanyName']);
            $row_RecordsetCFG['CustomerID']  = loadFromMssql($row_RecordsetCFG['CustomerID']);
            $CompanyName                     = $row_RecordsetCFG['CompanyName'];
            $GUID                            = $row_RecordsetCFG['CustomerID'];
            $updateSQL                       = sprintf("UPDATE Customers SET lastOnline=%s,last_operation=%s WHERE CustomerID=%s", GetSQLValueStringGBK(date("Y-m-d H:i:s"), "date"), GetSQLValueStringGBK("login", "text"), GetSQLValueStringGBK($GUID, "text"));
            
            $orders->exec($updateSQL);
            setcookie("wechat", $GUID,time()+7*3600); //创建cookie,cookie存在时间为7天
            if ($debug)
                console_log("A setcookie wechat    :    " . $GUID);
        }
    }
    if (!$is_exist)
        $showMenu = 'login';
}


if ($debug)
    console_log('GUID:' . $GUID);


//验证和客户
if (!empty($GUID)) {
    if ($debug)
        console_log("验证和客户B    :    " . $GUID);
    console_log("is_exist    :    " . $is_exist);
    
    if (!$is_exist) {
        $query_RecordsetCFG = "SELECT top 1 CompanyName,CustomerID FROM Customers  where CustomerID='" . save2mssql($GUID) . "' or cast(wechat as varchar(max))='" . save2mssql($GUID) . "'";
        
        
        $values = $orders->query($query_RecordsetCFG);
        if (is_iterable($values)) {
            foreach ($values as $row_RecordsetCFG) {
                $is_exist                        = 1;
                $row_RecordsetCFG['CompanyName'] = loadFromMssql($row_RecordsetCFG['CompanyName']);
                $row_RecordsetCFG['CustomerID']  = loadFromMssql($row_RecordsetCFG['CustomerID']);
                $CompanyName                     = $row_RecordsetCFG['CompanyName'];
                $GUID                            = $row_RecordsetCFG['CustomerID'];
                $updateSQL                       = sprintf("UPDATE Customers SET lastOnline=%s,last_operation=%s WHERE CustomerID=%s", GetSQLValueStringGBK(date("Y-m-d H:i:s"), "date"), GetSQLValueStringGBK("login", "text"), GetSQLValueStringGBK($GUID, "text"));
                
                $orders->exec($updateSQL);
                setcookie("wechat", $GUID,time()+7*3600);
                //die($updateSQL);
                if ($debug)
                    console_log("B setcookie wechat    :    " . $GUID);
                
            }
        }
    }
    if ($debug)
        console_log("is_exist: " . $is_exist);
    if (!$is_exist) {
        $OrdersStatus = '新';
        $Address      = '';
        $City         = '';
        $PostalCode   = '';
        $wechat       = '';
        $Phone        = '';
        if (isset($_REQUEST['CompanyName']) && !empty($_REQUEST['CompanyName']))
            $CompanyName = $_REQUEST['CompanyName'];
        else
            $CompanyName = generate_password(4);
        
        if (isset($_REQUEST['Address']) && !empty($_REQUEST['Address']))
            $Address = $_REQUEST['Address'];
        if (isset($_REQUEST['City']) && !empty($_REQUEST['City']))
            $City = $_REQUEST['City'];
        if (isset($_REQUEST['PostalCode']) && !empty($_REQUEST['PostalCode']))
            $PostalCode = $_REQUEST['PostalCode'];
        if (isset($_REQUEST['wechat']) && !empty($_REQUEST['wechat']))
            $wechat = $_REQUEST['wechat'];
        if (isset($_REQUEST['Phone']) && !empty($_REQUEST['Phone']))
            $Phone = $_REQUEST['Phone'];
        if (isset($_REQUEST['reg_username3330']) && !empty($_REQUEST['reg_username3330']))
            $usernameInit = $_REQUEST['reg_username3330'];
        if (isset($_REQUEST['reg_password3330']) && !empty($_REQUEST['reg_password3330']))
            $passwordInit = $_REQUEST['reg_password3330'];
        
        
        $ShipTypeInit    = $_POST['ShipType'];
        $PaymentTypeInit = $_POST['PaymentType'];
        //订单类型： 外卖 店内 自提 
        //支付方式： 现金 饭票 其他
        
        
        //$sn=md5(microtime());
        $insertSQL = sprintf("INSERT INTO Customers (username,password,CustomerID,CompanyName,lastOnline,last_operation,Address,City,PostalCode,Phone,wechat,ShipType,PaymentType) VALUES (%s, %s,%s, %s, %s, %s,%s, %s, %s, %s, %s, %s, %s)", GetSQLValueStringGBK($usernameInit, "text"), GetSQLValueStringGBK($passwordInit, "text"), GetSQLValueStringGBK($GUID, "text"), GetSQLValueStringGBK($CompanyName, "text"), GetSQLValueStringGBK(date("Y-m-d H:i:s"), "date"), GetSQLValueStringGBK("login", "text"), GetSQLValueStringGBK($Address, "text"), GetSQLValueStringGBK($City, "text"), GetSQLValueStringGBK($PostalCode, "text"), GetSQLValueStringGBK($Phone, "text"), GetSQLValueStringGBK($wechat, "text"), GetSQLValueStringGBK($ShipTypeInit, "text"), GetSQLValueStringGBK($PaymentTypeInit, "text"));
        $orders->query($insertSQL);
        setcookie("wechat", $GUID,time()+7*3600);
        if ($debug)
            console_log("C setcookie wechat" . $GUID);
        if ($debug)
            console_log("[添加" . $GUID . "成功]  ");
        if ($debug)
            console . log('insertSQL : ' . $insertSQL);
        
        
    } else {
		//启用餐台可以继续编辑结帐中的单据。反之进入结帐中的单据就不可再编辑，点击台号后开新单
		if ($CFG_ShowDesk==1) 
			$deskstr="(Status='". save2mssql('结账中')."' or Status='". save2mssql('服务中')."')";
		else 
			$deskstr="Status='". save2mssql('服务中')."'";
		
        $LastOrderID="";
        $query_RecordsetCFG = "SELECT top 1 Customers.CompanyName,  Orders.Status, Orders.OrderID, Orders.RequiredDate FROM Customers   LEFT OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID    where Customers.CustomerID='".save2mssql($GUID)."' and ". $deskstr." order by Customers.CustomerID ";
       // die($query_RecordsetCFG);
        if ($debug)
            console_log("验证和客户C    :    " .   $query_RecordsetCFG );
        $values = $orders->query($query_RecordsetCFG);
        if (is_iterable($values)) {
            foreach ($values as $row_RecordsetCFG) {
                $row_RecordsetCFG['Status'] = loadFromMssql($row_RecordsetCFG['Status']);
                $OrdersStatus               = $row_RecordsetCFG['Status'];
                $LastOrderID                = $row_RecordsetCFG['OrderID'];
                if ($debug)
                    console_log("验证客户最后一张订单 $LastOrderID");
            }
        }
        
    }
    if ($debug)
        console_log("你好 $CompanyName | Status $OrdersStatus | OrderID $LastOrderID ");
    if (!is_numeric($LastOrderID)) {
        $NewOrdersql_OID = "SELECT max(OrderID)+1 FROM Orders";// where  CONVERT (date, RequiredDate) =CONVERT (date, GETDATE ()) ";
        if ($debug)
            console_log("max(OrderID)    :    " .   $NewOrdersql_OID );
        
        $values = $orders->query($NewOrdersql_OID);
        if (is_iterable($values)) {
            foreach ($values as $pNewOrder) {
                $NewOrderID = $pNewOrder[0];
                if (!is_numeric($pNewOrder[0]))
                    $NewOrderID = date('ymd') * 100 + 1;
            }
            if (empty($NewOrderID))
                $NewOrderID = date('ymd') * 100 + 1;
				$sql_new="INSERT INTO [Orders] ([OrderID],[ShipCity],[TaxInclude],[CustomerID], [Status],RequiredDate,OrderDate) VALUES (". $NewOrderID . ",'" . save2mssql($CompanyName). "','True','" . save2mssql($GUID). "','".save2mssql('服务中')."','".date('Y-m-j')."','".date('Y-m-j')."')";
            if ($debug)
                console_log(" Orders INSERT    :    " .   $sql_new );
            
            $orders->query($sql_new);
            console_log("台号:  " . $_POST['CustomerID'] . "      流水号:  " . $NewOrderID . "");
            $OrdersStatus = '服务中';
            $LastOrderID  = $NewOrderID;
        }
        
    }
}


if ($debug) {
    console_log('usernameInit:' . $usernameInit);
    console_log('reg_username3330:' . $_REQUEST['reg_username3330']);
    console_log('reg_password3330:' . $_REQUEST['reg_password3330']);
    console_log('showMenu:' . $_POST['showMenu']);
    console_log('CompanyName:' . (isset($CompanyName)?'111':'000'));
}
?>