<?php
set_time_limit(3600);
error_reporting(E_ALL);
require_once 'config.php';

$flag = APPLICATION_PATH . '/../data/log/notifylgsttuotou.lock';

if (@file_exists($flag)) {
    echo "Another process is running.\r\n";
    echo "{$flag}\r\n";
    exit();
}

$handler = fopen($flag, 'wb');
fclose($handler);


echo '[', date('Y-m-d H:i:s'), '] Starting.', "\r\n";

try {

    $db = Common_Common::getAdapter();

    $sqlCount = searchSql("count(*)");
    $countArr = $db->query($sqlCount)->fetch();
    $count = $countArr['count(*)'];
    $sql = searchSql("",1,10);
    $resultSet = $db->query($sql);
    $rows = $resultSet->fetchAll();

    if($count > 0)
    {
        $pageSize = 10;
        $pages = ceil($count/$pageSize); 

        for ($page=1; $page <= $pages; $page++) 
        { 
            $sql = searchSql($fields,$page,$pageSize);
            $ordersList = $db->query($sql)->fetchAll();

            if(!empty($ordersList))
            {
                $lgstNotify = new Service_LgstOrdersTuoTouNotify();
                $lgstNotify->notifyLgstTuotou($ordersList);
            }
        }
    }

} catch (Exception $e) {
    // @unlink($flagFile);
    echo '[' . date('Y-m-d H:i:s') . '] Fail Exception:' . $e->getMessage() ."\r\n";
}

echo "[" . date('Y-m-d H:i:s') . "] End run\r\n";
@unlink($flag);

function searchSql($fields="",$page=1,$pageSize=10){

    if($fields == "count(*)"){

        $sql = "SELECT count(*) from orders JOIN customer on orders.customer_id = customer.customer_id left JOIN notify_lgst_order_tuotou_log on orders.reference_no=notify_lgst_order_tuotou_log.order_code where 1 AND customer.customer_platform='LT' and orders.order_status = 13 and orders.reference_no != '' and (orders.reference_no not in (SELECT order_code from notify_lgst_order_tuotou_log) or orders.reference_no=notify_lgst_order_tuotou_log.order_code AND notify_lgst_order_tuotou_log.status=0)";
    }else{

        $start = ($page-1) * $pageSize;
        $sql = "SELECT orders.order_code,orders.customer_code,orders.reference_no from orders JOIN customer on orders.customer_id = customer.customer_id left JOIN notify_lgst_order_tuotou_log on orders.reference_no=notify_lgst_order_tuotou_log.order_code where 1 AND customer.customer_platform='LT' and orders.order_status = 13 and orders.reference_no != '' AND (orders.reference_no not in (SELECT order_code from notify_lgst_order_tuotou_log) or orders.reference_no=notify_lgst_order_tuotou_log.order_code AND notify_lgst_order_tuotou_log.status=0) limit $pageSize offset $start";

    }
    return $sql;
}

