<?php
/*
   This file is the property of Teapplix. Use of this file is 
   restricted to Teapplix customers and governed by
   Teapplix's Terms and Conditions from the following url:

   http://www.teapplix.com/terms.html

   You can only use this file in conjunction with your Teapplix
   account. You agree not to redistribute this file or reverse 
   engineer its contents. You agree to destroy all copies of this 
   file when you terminate your Teapplix subscription.

   Copyright 2008-2011 Teapplix. All rights reserved.

   http://www.teapplix.com
*/
/* 
   the following funciton can be customized if you do not want to 
   grant admin account access to Teapplix.

   You can customize this function to return 1 for the correct 
   "username password" combination, 0 otherwise, and setup 
   Teapplix to use the special username and password to 
   download your orders.
*/

function DoAuthCustom($username$password) {                 //__EXCLUDE__
    
if ($username == "teapplix" && $password=="changeme123") { //__EXCLUDE__
        
return 1;                                             //__EXCLUDE__
    
}                                                         //__EXCLUDE__
    
return 0;                                                 //__EXCLUDE__
}                                                             //__EXCLUDE__

define('TE_VAR_ACTION''action');
define('TE_VAR_ID''id');
define('TE_VAR_START''start');
define('TE_VAR_END''end');
define('TE_VAR_MAXCOUNT''maxcount');
define('TE_VAR_STATUS_CODE''status_code');
define('TE_VAR_COMMENTS''comments');
define('TE_VAR_VERBOSE''verbose');
define('TE_VAR_DEBUG''debug');
define('TE_VAR_USERNAME''username');
define('TE_VAR_PASSWORD''password');

if (!empty(
$_REQUEST['debug'])) {
    
error_reporting(E_ALL);
    
ini_set('display_errors''on');
}

# Required XCart setup
include_once '../top.inc.php';
include_once 
'../init.php';
include_once 
'../include/func/func.crypt.php';
include_once 
'../include/func/func.order.php';
require_once 
"auth.php";
//require_once "../auth.php";

define("AREA_TYPE""A");

/*require_once "../include/security.php";
require_once "../include/orders.php";
x_load('crypt', 'order', 'product');*/

# Teapplix Configuration
$moduleVersion "1.0.1";

// Authenticates the &username and &password
function DoAuth($username$password) {

    global 
$sql_tbl;
    global 
$active_modules;

    
$loginOk false;
    
$isAdmin false;

    
// perform login here
    
$user_data func_query_first(
        
"select * from $sql_tbl[customers] " .
        
"where login='$username' and status='Y'");

    if (!empty (
$user_data)) {
        
$storedPassword text_decrypt($user_data["password"]);
        if (
text_verify($password$storedPassword)) {
            
$loginOk true;
            
$usertype $user_data["usertype"];
            
$isAdmin = ($usertype == 'A'
                || (
$usertype == "P" && $active_modules["Simple_Mode"]);
        }
    }
    return 
$loginOk && $isAdmin;
}

header("Last-Modified: " gmdate("D, d M Y H:i:s") . " GMT");
    
/* HTTP/1.1 */
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0"false);

/* HTTP/1.0 */
header("Pragma: no-cache");    
    
DoAction();

function 
fromGMT($gmt) {                
    return 
date("Y-m-d H:i:s"$gmt);
}

function 
toGMT($dateSql)
{
    
$pattern "/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/i";

    if (
preg_match($pattern$dateSql$dt)) 
    {
        
$dateUnix mktime($dt[4], $dt[5], $dt[6], $dt[2], $dt[3], $dt[1]);
        return 
gmdate(DATE_ATOM$dateUnix);
    }
        
    return 
$dateSql;
}
    
function 
GetParams() {
    global 
$action$start$end$debug$verbose$maxcount$status_code;
    global 
$username$password;

    
$username $_GET[TE_VAR_USERNAME];
    
$password $_GET[TE_VAR_PASSWORD];

    
$action = (isset($_GET[TE_VAR_ACTION]) ? $_GET[TE_VAR_ACTION] : '');
    
$start = (isset($_GET[TE_VAR_START]) ? $_GET[TE_VAR_START] : 0);

    
$end = (isset($_GET[TE_VAR_END]) ? $_GET[TE_VAR_END] : 0);

    
$maxcount = (isset($_GET[TE_VAR_MAXCOUNT]) ? $_GET[TE_VAR_MAXCOUNT] : 0);

    
$status_code $_GET[TE_VAR_STATUS_CODE];
    
$status_code = ($status_code 0) ? $status_code ord('C');
    
$status_code chr($status_code);

    
$debug = (isset($_GET[TE_VAR_DEBUG]) ? $_GET[TE_VAR_DEBUG] : '');
    
$verbose = (isset($_GET[TE_VAR_VERBOSE]) ? $_GET[TE_VAR_VERBOSE] : '');
}

function 
S($tag) {
    echo 
'<' $tag '>';
}

function 
E($tag) {
    echo 
'</' $tag '>'.PHP_EOL;
}

// Output the given tag\value pair
function T($tag$value) {
    
S($tag);
    echo 
htmlspecialchars($value);
    
E($tag);
}

function 
XML() {
    echo 
"<?xml version=\"1.0\"?>";
}

function 
ListOrderStatus() {
    
S("OrderStatus");
    
T("Code""B");
    
T("Name""Backordered");
    
T("Code""C");
    
T("Name""Complete");
    
T("Code""D");
    
T("Name""Declined");
    
T("Code""F");
    
T("Name""Failed");
    
T("Code""I");
    
T("Name""Incomplete");
    
T("Code""P");
    
T("Name""Processed");
    
T("Code""Q");
    
T("Name""Queued");
    
E("OrderStatus");
}

function 
XMLHeader($error=""$description="")
{
    
S("Header");
    
T("DocumentVersion""1.01");

    global 
$action$start$end$debug$verbose$maxcount$status_code;

    if (
$error) {
        
$verbose 0;
        
$debug 1;
    }

    if (
$verbose) {
        
S("ZenCart");
        
ListOrderStatus();
        
$action '';
        
E("ZenCart");
    }

    if (
$debug) {
        
S("Debug");
        
T("Action"$action);
        
T("Start"$start);
        
T("End"$end);
        
T("MaxCount"$maxcount);
        
T("StatusCode"$status_code);
        
E("Debug");
    }

    if (
$error) {
        
S("Fault");
        
T("Code"$error);
        
T("Description"$description);
        
E("Fault");
    }

    
E("Header");
}

function 
DoAction() {
    global 
$action$username$password;
    
    
header('Content-Type: text/xml');

    
GetParams();
    
XML();
    
S("TeapplixEnvelop");

    
// only proceed if the user authenticates ok
    
if (!DoAuth($username$password)) {
        if (!
DoAuthCustom($username$password)) {
            
XMLHeader(401'Username and/or Password not correct!');
            
E("TeapplixEnvelop");
            return;
        }
    }

    
XMLHeader();
    switch (
strtolower($action))
    {
        case 
'download'
            
DownloadOrders();
            break;
        case 
'update':
            
UpdateStatus();
            break;
        case 
'listing':
            
GetListing();
            break;
        case 
'sync_listing':
            
SyncListing();
            break;
    }

    
// close out the xml stream
    
E("TeapplixEnvelop");
}

function 
GetListing() {
    global 
$sql_tbl;
    
$productsTable $sql_tbl['products'];
    
$productsLngEnTable $sql_tbl['products_lng_en'];
    
    
$variantsTable $sql_tbl['variants'];
    
$variantItemsTable $sql_tbl['variant_items'];
    
$classesTable $sql_tbl['classes'];
    
$classOptionsTable $sql_tbl['class_options'];
    
$productsQuery "SELECT * FROM `$productsTable` AS `p` INNER JOIN `$productsLngEnTable` AS `pe` ON `pe`.`productid` = `p`.`productid`";
    
$productsResult db_query($productsQuery);
    if(
$productsResult) {
        
$count 1;
        
T("MessageType""ProductReport");
        while (
$row db_fetch_array($productsResult)) {
            
S("Message");
            
T("MessageID"$count);
            
S("ProductReport");
            
T("ProductId",$row['productid']);
            
T("ProductCode",$row['productcode']);
            
T("Product",$row['product']);
            
T("Descr",$row['descr']);
            
T("ListPrice",$row['list_price']);
            
T("Avail",$row['avail']);
            
T("AddDate",$row['add_date']);
            
T("MinAmount",$row['min_amount']);
            
S("Variants");
            
$productid $row['productid'];
            
$productVariantsQuery "SELECT `v`.`variantid`,`v`.productcode,`c`.`class` ,`co`.`option_name`,`v`.`avail` FROM `$variantsTable` AS `v` INNER JOIN `$variantItemsTable` AS `i` ON `i`.`variantid` = `v`.`variantid` INNER JOIN `$classOptionsTable` AS `co` ON `co`.`optionid` = `i`.`optionid` INNER JOIN `$classesTable` AS `c` ON `c`.`classid` = `co`.`classid` WHERE `v`.`productid` = $productid ORDER BY `v`.`productcode`, `c`.`class`";
            
$productVariantsResult db_query($productVariantsQuery);
            echo 
mysql_error();
            
$variants = array();
            while(
$pvRow db_fetch_array($productVariantsResult)) {
                
$variantProductCode $pvRow['productcode'];
                if(!isset(
$variants[$variantProductCode])) {
                    
$variants[$variantProductCode] = array(
                        
"avail"=>$pvRow['avail'],
                        
"variantid"=>$pvRow['variantid'],
                        
"options"=>array());
                }
                
$variants[$variantProductCode]["options"][] = "{$pvRow['class']}{$pvRow['option_name']}";
            }
            foreach(
$variants as $productCode => $data) {
                
$options $data['options'];
                
$avail $data['avail'];
                
$variantid $data['variantid'];
                
S("Variant");
                
T("ProductCode",$productCode);
                
T("Avail",$avail);
                
T("VariantId",$variantid);
                
$optionsStr implode(",",$options);
                
T("Options",$optionsStr);
                
E("Variant");
            }
            
E("Variants");
            
E("ProductReport");
            
E("Message");
            
$count++;
        }
    }
}

function 
SyncListing() {
    global 
$sql_tbl,$listing;
    
$productsTable $sql_tbl['products'];
    
$variantsTable $sql_tbl['variants'];
    if(
is_array($listing)) {
        foreach(
$listing as $productcode => $avail) {
            
$avail intval($avail);
            
$query "UPDATE `$productsTable` SET `avail` = $avail WHERE `productcode` = '$productcode'";
            
db_query($query);
            
$query "UPDATE `$variantsTable` SET `avail` = $avail WHERE `productcode` = '$productcode'";
            
db_query($query);
        }
    }
}

function 
Coalesce() {
    
$args func_get_args();
    foreach (
$args as $arg) {
        
$arg trim($arg);
        if (!empty(
$arg)) {
            return 
$arg;
        }
    }
    return 
"";
}
// Returns the orders to be processed.
// This is called when the request querystring
// contains action=getorders
function DownloadOrders() {
    global 
$sql_tbl;
    global 
$action$start$end$debug$verbose$maxcount$status_code;

    
$ordersQuery "select * " .
    
" from $sql_tbl[orders] " .
    
" where status = '$status_code'";

    if (
$start) {
        
$start intval($start);
        
$ordersQuery .= " and date >= '$start'";
    }
    if (
$end) {
        
$end intval($end);
        
$ordersQuery .= " and date <= '$end'";
    }
    if (
$maxcount) {
        
$ordersQuery .= "  limit 0, " $maxcount;
    }

    
$ordersResults db_query($ordersQuery);
    if (
$ordersResults) {
        
$count 1;
        
T("MessageType""OrderReport");
        while (
$row db_fetch_array($ordersResults))
        {
            
$firstname Coalesce($row['s_firstname'], $row['firstname'], $row['b_firstname']);
            
$lastname Coalesce($row['s_lastname'], $row['lastname'], $row['b_lastname']);
            
$city Coalesce($row['s_city'], $row['b_city']);
            
$address Coalesce($row['s_address'], $row['b_address']);
            
$state Coalesce($row['s_state'], $row['b_state']);
            
$country Coalesce($row['s_country'], $row['b_country']);
            
$zipcode Coalesce($row['s_zipcode'], $row['b_zipcode']);
            
$phone Coalesce($row['s_phone'], $row['b_phone']);
                
            
S("Message");
            
T("MessageID"$count);
            
S("OrderReport");

            
T("OrderID"$row['orderid']);
            
T("OrderDate"toGMT($row['date']));
            
T("PaymentType"$row['payment_method']);
            
S("CustomerOrderInfo");
            
T("Type""CustomerComment");
            
T("Value"$row['customer_notes']);
            
E("CustomerOrderInfo");
            
            
S("CustomerOrderInfo");
            
T("Type""StatusCode");
            
T("Value"$row['status']);
            
E("CustomerOrderInfo");
            
            
S("BillingData");
            
T("BuyerEmailAddress"$row['email']);
            
T("BuyerName""$firstname $lastname");
            
T("BuyerPhoneNumber"$phone);
            
E("BillingData");

            
S("FulfillmentData");
            
T("FulfillmentMethod""Ship");
            
T("FulfillmentServiceLevel"$row['shipping']);
            
S("Address");
            
T("Name""$firstname $lastname");
            list(
$addr1$addr2) = 
                
preg_split("/[\r\n]+/"$address);
            
T("AddressFieldOne"$addr1);
            
T("AddressFieldTwo"$addr2);
            
T("City"$city);
            
T("StateOrRegion"$state);
            
T("PostalCode"$zipcode);
            
T("CountryCode"$country);
            
T("PhoneNumber"$phone);
            
E("Address");
            
E("FulfillmentData");
            
GetOrderItems($row['orderid']);
            
GetOrderTotals($row);
            
E("OrderReport");
            
E("Message");
            
$count++;
        }
    }

}

// writes out the item details for an order
function GetOrderItems($orderid) {
    global 
$sql_tbl;
    
$sql 'select * from ' "$sql_tbl[order_details].
        
" where orderid = '$orderid'";

    
$detail db_query($sql);
    if (! 
$detail) {
        return;
    }
    while (
$item db_fetch_array($detail)) {
        
$imageUrl $item['products_image'];
        if (isset(
$imageUrl) and strlen($imageUrl) > 0)
        {
            
$imageUrl $imageRoot $imageUrl;
        }
            
        
S("Item");
        
T("OrderItemCode"$item['itemid']);
        
T("ProductID"$item['productid']);
        
T("SKU"$item['productcode']);
        
T("Title"$item['product']);
        
T("Options",$item['product_options']);
        
T("Quantity"$item['amount']);
        
S("ItemPrice");
        
S("Component");
        
T("Type""Principal");
        
T("Amount"$item['price']);
        
E("Component");
        
E("ItemPrice");
        
E("Item");
    }
}

// writes out the totals subitems
function GetOrderTotals($row) {
    
S("Totals");
    
T("Shipping"$row['shipping_cost']);
    
T("Tax"$row['tax']);
    
T("Total"$row['total']);
    
E("Totals");
}

// Updates the status of an order in XCart
function UpdateStatus() {

    global 
$status_code$sql_tbl;

    if (!isset(
$_GET[TE_VAR_ID])
        || !
$status_code )
    {
        
XMLHeader(10"Not all parameters supplied.");
        return;
    }
    
$count 0;
    foreach (
$_GET[TE_VAR_ID] as $id) {
        
func_change_order_status($id$status_code);
        
$count++;
    }
    
T("MessageType""UpdateStatusCount");
    
S("Message");
    
T("UpdateCount"$count);
    
E("Message");
}

?>