<?php
set_time_limit(3600);
error_reporting(E_ALL);
require_once 'config.php';

$flag = APPLICATION_PATH . '/../data/log/notifylgstbeian.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("",2,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);
            $productList = $db->query($sql)->fetchAll();

            if(!empty($productList))
            {
                $lgstNotify = new Service_LgstBeiAnProductNotify();
                $lgstNotify->notifyLgstProductBeiAn($productList);
            }
        }
    }

} 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 product JOIN customer on product.customer_id = customer.customer_id left JOIN notify_product_beian_lightstrade_log on product.product_id=notify_product_beian_lightstrade_log.product_id where 1 AND customer.customer_platform='LT' and (product.product_id not in (SELECT product_id from notify_product_beian_lightstrade_log) or product.product_id=notify_product_beian_lightstrade_log.product_id AND notify_product_beian_lightstrade_log.status=0)";
    }else{

        $start = ($page-1) * $pageSize;
        $sql = "SELECT product.product_id,product.product_sku,product.customer_code,product.product_status from product JOIN customer on product.customer_id = customer.customer_id left JOIN notify_product_beian_lightstrade_log on product.product_id=notify_product_beian_lightstrade_log.product_id where 1 AND customer.customer_platform='LT' AND (product.product_id not in (SELECT product_id from notify_product_beian_lightstrade_log) or product.product_id=notify_product_beian_lightstrade_log.product_id AND notify_product_beian_lightstrade_log.status=0) limit $pageSize offset $start";

    }
    return $sql;
}

