<?php
/* $connection = ssh2_connect("dhl-sftp01.rze.deutschepost.de",22);
if (ssh2_auth_password($connection,"CRG","Liit0kei")) {
      echo "Authentication Successful!\n";
} else {
      die('Authentication Failed...');
} */
require_once ('config.php');

$filePath = APPLICATION_PATH.'/../data/log/'.'trackingLog2.txt';
if(!file_exists($filePath)){
    $fp= fopen($filePath,"w");
    fclose($fp);
}
//file_put_contents($filePath,var_export($timeStart,true),FILE_APPEND);
$smCodeArr = array(
    //'HKDHL'=>'DHL',
    'BH-HKDHL'=>'DHL',
    'BH-SGG'=>'QQYZ',
    'BH-USPS'=>'OZZX',
    'BH-DPD'=>'USPS',
    //'HKUPS-KW'=>'UPS',
    //'SZY-EMS'=>'EMS',
    //'WG-EMS'=>'EMS',
    //'SZY-ETK'=>'EMS',
    //'BH-DGMG'=>'DHL_GLB',
    //'CJ-DGMG'=>'DHL_GLB',
    //'SZY-EUB'=>'EMS',
    //'WG-EUB'=>'EMS',
    //'WG-EUB-EBAY'=>'EMS',
    //'PNLG'=>'NL',
    //'HKPG'=>'NL',
    //'BH-DPD'=>'',
    //'AUP'=>'IADLYYZ',
    //'BH-SGG'=>'',
    //'BH-USPS'
);
$EBusinessID = '1255385';
$AppKey = "3921afe4-1123-4bc3-bd7c-5b553bb68eb8";
$validateUrl = "http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";
foreach($smCodeArr as $key=>$company){
    $condition = array(
        'order_status'=>'11',
        'sm_code'=>$key,
    );
    $total = Service_Orders::getByCondition($condition,'count(*)');
    $pageSize = 20;
    $totalPage = ceil($total/$pageSize);
    for($page=1;$page<=$totalPage;$page++){
        $ordersList = Service_Orders::getByCondition($condition,"*",$pageSize,$page,'order_id asc');
        foreach($ordersList as $orderRow){
            if($orderRow['customer_code']=="E0207"||$orderRow['customer_code']=="E0110") continue;
            $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
            if(empty($shipOrder)) continue;
            $items.="<Item><No>".$shipOrder['tracking_number']."</No><Bk></Bk></Item>";
            $orderCodeArr[] =  $orderRow['order_code'];
            $orderCodeStr.= $orderRow['order_code'].",";
            $requestData = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Content><ExpressCodes><Code>".$company."</Code><Items><Item><No>".$shipOrder['tracking_number']."</No><Bk></Bk></Item></Items></ExpressCodes></Content>";
            $datasign = urlencode(base64_encode(md5($requestData.$AppKey)));
            $params = array(
                'EBusinessID' => $EBusinessID,
                'RequestType' => '1005',
                'RequestData' => urlencode($requestData) ,
                'DataType' => '1',
                'DataSign'=>$datasign,
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $validateUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $response = curl_exec($ch);
            //echo $response;
            $xlm = simplexml_load_string($response);
            $result = Common_Common::objectToArray($xlm);
            if($result['Success']==true){
                $ret = $orderRow['order_code']." Traces order Success!\n";
                file_put_contents($filePath,var_export($ret,true),FILE_APPEND);
            }else{
                $ret = $orderCodeStr."Traces order failure:".$result['Reason']."\n";
                file_put_contents($filePath,var_export($ret,true),FILE_APPEND);
            }
        }
    }
}
exit;
$receiving_code = "BHC150003478";
$row = Service_FtpMessageSendlist::getByField($receiving_code,"refercence_no","*");
$fileName = $row['refercence_no'].'.xml';
$relativePath = '/outbound_send/'.date('Y/m/d');
//APPLICATION_PATH.'/../data/ftp';
$absolutePath =APPLICATION_PATH.'/../data/ftp'.$relativePath;
if(!file_exists($absolutePath)) {
    mkdir($absolutePath, 0777, true);
}
$obxProcess = new Service_OutBillXmlProcess($row['refercence_no']);
$result = $obxProcess->generate($absolutePath.'/'.$fileName);
exit;

$asnObj = new Service_AsnProccess();
$asnObj->split9610("BHR150002760");
exit;

$fileName = 'BHC150003172.xml';
$relativePath = APPLICATION_PATH.'/../data/ftp/outbound_send/'.date('Y/m/d');
$absolutePath = $relativePath;
if(!file_exists($absolutePath)) {
    mkdir($absolutePath, 0777, true);
}
$obxProcess = new Service_OutBillXmlProcess("BHC150003172");
$result = $obxProcess->generate($absolutePath.'/'.$fileName);
exit;

$receiving['receiving_code'] = 'BHR150002783';
if($receiving['receive_model_type']=="1"){
    $goodsIdArr = Service_OrderProduct::getGoodsId($receiving['receiving_code']);
    $sumNetWeight = Service_OrderProduct::calNetWeightByCondition(array('receiving_code'=>$receiving['receiving_code']));
}else{
    $goodsIdArr = Service_ReceivingDetail::getGoodsId($receiving['receiving_code']);
    $sumNetWeight = Service_ReceivingDetail::sumNetWeight($receiving['receiving_code']);
}
$goodsIdArr = array_chunk($goodsIdArr,200);
$subIndex = 1;
$gross_wt = ($receiving['roughweight']-$sumNetWeight)/count($goodsIdArr);
foreach($goodsIdArr as $gk=>$gv){
    if($subIndex<10){
        $sub_receiving_code = $receiving['receiving_code']."-0".$subIndex;
    }else{
        $sub_receiving_code = $receiving['receiving_code']."-".$subIndex;
    }
    $subIndex++;
    $receivingXml = array(
        'receiving_code'=>$receiving['receiving_code'],
        'sub_receiving_code'=>$sub_receiving_code,
        'gross_wt'=>'0',
        'net_wt'=>'0',
        'pack_no'=>'0',
        'refercence_form_id'=>'',
        'rx_add_time'=>date("Y-m-d H:i:s"),
        'receiving_xml_status'=>'3',
    );
    //Service_ReceivingXml::add($receivingXml);
    //$RXdbObj = new Table_ReceivingXml();
    //$rxId = $RXdbObj->getAdapter()->lastInsertId();
    $net_wt = 0;
    $pack_no = 0;
    $G_NO_index = 1;
    foreach($gv as $goods_id){
        if($receiving['receive_model_type']=="1"){
            $productList = Service_OrderProduct::getJoinProductByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
        }else{
            $productList = Service_ReceivingDetail::getJoinProductByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
        }
        $productRow = Service_Product::getByField($productList[0]['product_id'],'product_id',"*");
        $currencyRow = Service_Currency::getByField($productRow['currency_code'],'currency_code',"*");
        $receivingXmlDetail = array(
           // 'rx_id'=>$rxId,
            'from_id'=>$receiving['receiving_code'],
            'sub_receiving_code'=>$sub_receiving_code,
            'g_no'=>$G_NO_index,
            'goods_id'=>$productList[0]['goods_id'],
            'merger_g_no'=>$G_NO_index,
            'code_ts'=>$productList[0]['hs_code'],
            'g_name_cn'=>$productList[0]['hs_goods_name'],
            //'decl_price'=>"",
            'curr'=>$currencyRow['currency_hs_code'],
            'qty_1'=>0,
            'unit_1'=>'',
            'qty_2'=>'',
            'unit_2'=>'',
        );

        $g_qty = 0;
        $decl_total = 0;
        $decl_price = 0;
        foreach($productList as $p){
            if($receiving['receive_model_type']=="1"){
                $quantity = $p['op_quantity'];
                $g_qty+=$p['op_quantity'];
            }else{
                $quantity = $p['rd_receiving_qty'];
                $g_qty+=$p['rd_receiving_qty'];
            }

            $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$p['product_id']), 'hem_detail');
            $elements = array();

            foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
            $receivingXmlDetail['g_model'] = implode('|',$elements);
            $hs_uom_map = Service_HsUomMap::getByField($p['product_id'],'product_id',"*");
            $quantitylaw1 = isset($hs_uom_map['hum_quantity_law'])?$hs_uom_map['hum_quantity_law']:'0';
            $receivingXmlDetail['qty_1'] += $quantitylaw1*$quantity;
            $quantitylaw2 = isset($hs_uom_map['hum_quantity_second'])?$hs_uom_map['hum_quantity_second']:"0";
            $receivingXmlDetail['qty_2'] += $quantitylaw2*$quantity;
            if(!empty($hs_uom_map)) $hs_uom = Service_HsUom::getByField($hs_uom_map['hu_id'],'hu_id',"*");
            $receivingXmlDetail['unit_1'] = isset($hs_uom['pu_code_law'])?$hs_uom['pu_code_law']:"";
            $receivingXmlDetail['unit_2'] = isset($hs_uom['pu_code_second'])?$hs_uom['pu_code_second']:"";
            $product = Service_Product::getByField($p['product_id'],"product_id","*");
            $decl_total += $product['product_declared_value']*$quantity;

        }
        $pack_no+=$g_qty;
        if($receiving['receive_model_type']=="1"){
            $ntWeight = Service_OrderProduct::calNetWeightByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
        }else{
            $ntWeight = Service_ReceivingDetail::calNetWeightByCondition(array('goods_id'=>$goods_id,'receiving_code'=>$receiving['receiving_code']));
        }
        echo "receiving_code=".$receiving['receiving_code']."&goods_id=".$goods_id."&ntWeight=".$ntWeight."\n";
        $net_wt+= $ntWeight;
        $decl_price = sprintf("%.4f",$decl_total/$g_qty);
        $receivingXmlDetail['decl_price'] = $decl_price;
        $receivingXmlDetail['g_qty'] = $g_qty;
        $receivingXmlDetail['decl_total'] = $decl_total;
        //Service_ReceivingXmlDetail::add($receivingXmlDetail);
        $G_NO_index++;
    }
    $updateReceivingXml = array(
        'gross_wt'=>$net_wt+$gross_wt,
        'net_wt'=>$net_wt,
        'pack_no'=>$pack_no,
    );
    //Service_ReceivingXml::update($updateReceivingXml,$sub_receiving_code,'sub_receiving_code');

    $aMessage['fmt_code'] = 'MRK';
    $aMessage['fmt_type'] = 'BSG011';
    $aMessage['refercence_no'] = $sub_receiving_code;
    $aMessage['fml_status'] = 1;
    $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
    $aMessage['fml_comment'] = "WMS拆";
    //Service_FtpMessageSendlist::add($aMessage);

}
exit;

//$ftProcess = new Service_FtpReceiveProcess();
//$sendRow = Service_FtpMessageSendlist::getByField("BHR150002474A","refercence_no","*");
//$affect = $ftProcess->updateSendMessage($sendRow);
$asn = new Service_AsnProccess();
$asn->split9610('BHR150002693');
exit;
$fileName = 'BHC150002797.xml';
$relativePath = APPLICATION_PATH.'/../data/ftp/outbound_send/'.date('2015/10/01');
$absolutePath = $relativePath;
if(!file_exists($absolutePath)) {
    mkdir($absolutePath, 0777, true);
}
$obxProcess = new Service_OutBillXmlProcess("BHC150002797");
$result = $obxProcess->generate($absolutePath.'/'.$fileName);
die("just for test!");
$fileName = "520678_20150602-05.txt";
//"/mnt/html/www/export/wms/data/Efile/520678_20150521to25.txt";
$filePath = APPLICATION_PATH . '/../data/Efile2015/'.$fileName;
if(!file_exists($filePath)){
    $fp= fopen($filePath,"w");
    fclose($fp);
}
/*
$strServer = "dhl-sftp01.rze.deutschepost.de";
$strServerPort = "22";
$strServerUsername = "CRG";
$strServerPassword = "Liit0kei";

$resConnection = ssh2_connect($strServer, $strServerPort);
if(!$resConnection) die("Unable connect sftp on ".date("Y-m-d H:i:s")."\n");
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){
    $resSFTP = ssh2_sftp($resConnection);

    $opts = array(
        'http'=>array(
            'method'=>"GET",
            'timeout'=>120,
        )
    );
    $source_file =  APPLICATION_PATH . '/../data/Efile2015/520678_20150620.txt';
    if(file_exists($source_file)){
        if(!copy($source_file,"ssh2.sftp://{$resSFTP}/CRG/520678_20150520.txt")) {
            echo 'upload failed</br>';
        }else{
            echo "upload file Success on ".date("Y-m-d H:i:s")."\n";
        }
    }
}else{
    echo "Unable to authenticate on server on ".date("Y-m-d H:i:s")."\n";
}
exit;*/
$db = Common_Common::getAdapter();
$db->beginTransaction();
$sql = "select * from ship_batch where sb_ship_time>='2015-06-02 00:00:00' and sb_ship_time<='2015-06-02 23:59:59'";
$shipBatch = $db->fetchAll($sql);
foreach($shipBatch as $sb){
    $ShipBatchDetail = Service_ShipBatchDetail::getByCondition(array('sb_code'=>$sb['sb_code']),"*");
    foreach($ShipBatchDetail as $key=>$value){
        $obd = Service_OutboundBagDetail::getByCondition(array('ob_no'=>$value['ob_no']),"*");

        foreach($obd as $k=>$v){
            $orderRow = Service_Orders::getByField($v['order_code'],"order_code","*");

            if($orderRow['sm_code']=="CJ-DGMG"){
                $orderReceiptAddress = Service_OrderAddressBook::getByCondition(array("order_code"=>$orderRow['order_code'],'oab_type'=>'0'),"*");
                $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
                $country = Service_Country::getByField($orderReceiptAddress[0]['oab_country_id'],'country_id',"*");
                $ParcelContent = "";
                $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code']),"*");
                $op_declared_value = 0;
                $address1 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address1']);
                $address2 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address2']);
                foreach($orderProduct as $opk=>$opv){
                    //$ParcelContent=" ".trim($opv['product_title_en']);
                    //$op_declared_value=$opv['op_purpose_declared_value']*$opv['op_quantity'];

                    $ParcelContent=trim($opv['product_title_en']);
                    $op_declared_value=$opv['op_purpose_declared_value']*$opv['op_quantity'];
                    $product = Service_Product::getByField($opv['product_id'],"product_id","*");

                    $content = "520678|".$shipOrder['tracking_number']."|".$orderReceiptAddress[0]['oab_firstname']."|".$address1."|".$address2."||".$orderReceiptAddress[0]['oab_city']."|".$orderReceiptAddress[0]['oab_state']."|".$orderReceiptAddress[0]['oab_postcode']."|".$orderReceiptAddress[0]['oab_cell_phone']."|".$orderReceiptAddress[0]['oab_email']."|".$country['country_code']."|".$country['country_name_en']."|CN|".$product['product_title_en']."|".$op_declared_value."|".($shipOrder['so_weight']*1000)."||".$opv['op_quantity']."|".$product['product_sku']."|".$ParcelContent."|".$opv['op_declared_value']."|||||".$orderRow['currency_code']."||||PPS|||||||".$shipOrder['tracking_number']."||\n";
                    file_put_contents($filePath,$content,FILE_APPEND);
                }
                //$dmgProductCode = $orderRow['sm_code']=="CJ-DGMG"?'PPS':'PKD';
                $tag++;
            }
            /*if($orderRow['sm_code']=="CJ-DGMP"){
                $orderReceiptAddress = Service_OrderAddressBook::getByCondition(array("order_code"=>$orderRow['order_code'],'oab_type'=>'0'),"*");
                $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'],"order_code","*");
                $country = Service_Country::getByField($orderReceiptAddress[0]['oab_country_id'],'country_id',"*");
                $ParcelContent = "";
                $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderRow['order_code']),"*");
                $op_declared_value = 0;
                foreach($orderProduct as $opk=>$opv){
                    $ParcelContent.=" ".trim($opv['product_title_en']);
                    $op_declared_value+=$opv['op_purpose_declared_value']*$opv['op_quantity'];
                }
                //$dmgProductCode = $orderRow['sm_code']=="CJ-DGMG"?'PPS':'PKD';
                $address1 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address1']);
                $address2 = str_replace(PHP_EOL, '',$orderReceiptAddress[0]['oab_street_address2']);
                $content = "520678|".$shipOrder['tracking_number']."|".$orderReceiptAddress[0]['oab_firstname']."|".$address1."|".$address2."||".$orderReceiptAddress[0]['oab_city']."|".$orderReceiptAddress[0]['oab_state']."|".$orderReceiptAddress[0]['oab_postcode']."|".$orderReceiptAddress[0]['oab_cell_phone']."|".$orderReceiptAddress[0]['oab_email']."|".$country['country_code']."|".$country['country_name_en']."|CN|".$ParcelContent."|".$op_declared_value."|".$orderRow['grossWt']."|".$shipOrder['so_weight']."|PKW|PKW|PKW|PKW|||||".$orderRow['currency_code']."||||PKW|||||||".$shipOrder['tracking_number']."||\n";
                file_put_contents($filePath,$content,FILE_APPEND);
                $tag++;
            }*/
        }
    }

}
