File: /var/www/html/amberconcept/upload_data.php
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
//include wp libriries and set timezone to HK
require_once('wp-load.php');
require_once('PHPExcel.php');
require_once('TCPDF/data/tcpdf_include.php');
date_default_timezone_set("Asia/Hong_Kong");
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
if(isset($_GET['id']) && $_GET['id']!="") {
$sql = "SELECT * FROM custom_po_master WHERE id = '".$_GET['id']."%' LIMIT 1";
$result = $wpdb->get_results($sql);
if(count($result)>0){
$poObj = $result[0];
} else {
//echo "Invalid PO";
echo json_encode(['success'=>false, 'message'=>'Invalid PO']);
exit();
}
} else {
echo json_encode(['success'=>false, 'message'=>'Invalid Parameter']);
//echo "Invalid Parameter";
exit();
}
$order_id = $poObj->order_id;
$order = wc_get_order($order_id);
$isFotomax = $order->get_user_id()==7?true:false;
$htmlHeader = '';
function getHeaderString($po_number, $po_line, $po_date, $order_id){
// draw header table
return $htmlHeader = '<div id="headerSection">
<table cellspacing="2" cellpadding="2">
<tr>
<td>
<table id="po_table" cellspacing="1" cellpadding="1">
<tr>
<td colspan="2"><h1>PURCHASE ORDER</h1></td>
</tr>
<tr>
<td>PO Number:</td><td>'.$po_number.'-'.$po_line.'</td>
</tr>
<tr>
<td>DATE:</td><td>'.date('F d, Y', strtotime($po_date)).'</td>
</tr>
<tr>
<td>VENDOR NO.:</td><td>Wink Impression</td>
</tr>
<tr>
<td>ORDER ID:</td><td>'.$order_id.'</td>
</tr>
</table>
</td>
<td></td>
<td>
<table id="amber_table" cellspacing="1" cellpadding="1" style="text-align: right;">
<tr>
<td><img src="custom/image/Amber.png" width="150"></td>
</tr>
<tr>
<td><small>Flat 6A, Kin Ho Industrial Building, Block 1<br>14-24 Au Pui Wan Street, Fotan, NT, HK</small></td>
</tr>
<tr>
<td><small>Tel: 852-2278 5768<br>Fax: 852-2691 0724<br>Email: cs.hk@amberconcept.com</small></td>
</tr>
</table>
</td>
</tr>
</table>
</div>';
}
$vendor_detail = "";
$arr_vendor_detail = explode("\r\n", $poObj->vendor_detail);
foreach($arr_vendor_detail as $vendor_detail_line){
$vendor_detail .= "<tr><td>".$vendor_detail_line."</td></tr>";
}
$ship_detail = "";
$arr_ship_detail = explode("\r\n", $poObj->ship_detail);
foreach($arr_ship_detail as $ship_detail_line){
$ship_detail .= "<tr><td>".$ship_detail_line."</td></tr>";
}
// draw address table
$htmlAddress = '<div id="addressSection">
<table cellspacing="0" cellpadding="0" border="0.01">
<tr>
<td width="30%">
<table id="vendor_table" cellspacing="0" cellpadding="2">
<tr style="background-color:#000;color:#FFF">
<td>Vendor</td>
</tr>'.$vendor_detail.'
</table>
</td>
<td width="30%">
<table id="ship_table" cellspacing="1" cellpadding="1">
<tr style="background-color:#000;color:#FFF">
<td>Ship To</td>
</tr>'.$ship_detail.'
</table>
</td>
<td width="40%">
<table id="other_table" cellspacing="1" cellpadding="1">
<tr style="background-color:#000;color:#FFF">
<td colspan="2">Other Information</td>
</tr>
<tr>
<td>Ship Via: </td><td>'.$order->get_shipping_method().'</td>
</tr>
<tr>
<td>Shipment Term: </td><td>FOB</td>
</tr>
<tr>
<td>Payment Term: </td><td>Net 30 Days</td>
</tr>
<tr>
<td>Request Delivery Date: </td><td>'.($isFotomax?'Fotomax單, 7日內交':'10日內交').'</td>
</tr>
<tr>
<td>Courier: </td><td>Fedex/SF Express/GE-DHL</td>
</tr>
<tr>
<td>Shippng Document Value: </td><td>US$50 /pc</td>
</tr>
<tr>
<td>Weight & Ctn Size: </td><td>Pls see packing list</td>
</tr>
</table>
</td>
</tr>
</table>
</div>';
// draw footer cell (right)
$htmlPrice = '
<table cellspacing="0" cellpadding="1" border="0.01">
<tr>
<td width="70%" align="right" style="background-color:#000;color:#FFF">Sub Total ('.$poObj->currency.'):</td>
<td width="30%" align="center" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.number_format($poObj->po_amount, 2, '.', ',').'</td>
</tr>
<tr>
<td width="70%" align="right" style="background-color:#000;color:#FFF">Discount ('.$poObj->currency.'):</td>
<td width="30%" align="center" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray"></td>
</tr>
<tr>
<td width="70%" align="right" style="background-color:#000;color:#FFF">Sales Tax Rate ('.$poObj->currency.'):</td>
<td width="30%" align="center" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray"></td>
</tr>
<tr>
<td width="70%" align="right" style="background-color:#000;color:#FFF">Sales Tax ('.$poObj->currency.'):</td>
<td width="30%" align="center" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray"></td>
</tr>
<tr>
<td width="70%" align="right" style="background-color:#000;color:#FFF">Other Cost ('.$poObj->currency.'):</td>
<td width="30%" align="center" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray"></td>
</tr>
<tr>
<td width="70%" align="right" style="background-color:#000;color:#FFF">Grand Total ('.$poObj->currency.'):</td>
<td width="30%" align="center" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.number_format($poObj->po_amount, 2, '.', ',').'</td>
</tr>
</table>';
// draw date cell (left)
$htmlDate = '<table id="dateSection" width="100%">
<tr>
<td><h1>'.date('F d, Y', strtotime($poObj->po_date)).'</h1></td>
</tr>
<tr>
<td><hr></td>
</tr>
<tr>
<td>Date</td>
</tr>
</table>';
// draw sign cell (right)
$htmlSign = '<table id="signSection" width="100%">
<tr>
<td><h1>Sam Lee</h1></td>
</tr>
<tr>
<td><hr></td>
</tr>
<tr>
<td>Authorized Signature</td>
</tr>
</table>';
// Extend the TCPDF class to create custom Header and Footer
class MYPDF extends TCPDF {
public $htmlHeader;
public $htmlAddress;
public $htmlShipping;
public $htmlPrice;
public $htmlDate;
public $htmlSign;
public $poNumber;
public $itemName;
public $materialName;
public $customMaterialName;
public $size;
public $binding;
public $spreads;
public $qty;
//Page header
public function Header() {
$this->writeHTML($this->htmlHeader, true, false, false, false, '');
$this->Line(10, 38, 200, 38, array('width' => 0.7));
$this->writeHTML($this->htmlAddress, true, false, false, false, '');
}
// Page footer
public function Footer() {
// Position at 60 mm from bottom
$this->SetY(-60);
$this->SetFillColor(204,204,204);
$this->SetTextColor(0, 0, 0);
$this->writeHTMLCell(60, '', 10, 235, $this->htmlShipping, 0, 1, 1, true, 'L', true);
$this->SetFillColor(255, 255, 255);
$this->writeHTMLCell(60, '', 140, 235, $this->htmlPrice, 0, 1, 1, true, 'J', true);
$this->writeHTMLCell(60, '', 10, 265, $this->htmlDate, 0, 1, 1, true, 'J', true);
$this->writeHTMLCell(60, '', 140, 265, $this->htmlSign, 0, 1, 1, true, 'J', true);
$this->Line(10, 286, 200, 286, array('width' => 0.3));
// Page number
if(trim($this->itemName)=="Print on Canvas with Wooden Frame"){
$customDescription = $this->poNumber."_T-PD24120009_PS深木色框 24x36 油画布输出_[x".$this->qty."]";
} elseif(trim($this->itemName)=="Fotomax HKBU Certificate"){
$customDescription = $this->poNumber."_T-PD25070104 _画框_红色实木证书装表框 8.27x11.73_[x".$this->qty."]";
} elseif(trim($this->itemName)=="Canvas"){
$customDescription = $this->poNumber."_".$this->size."_快速框 [x".$this->qty."]";
} elseif (trim($this->itemName)=="Fine art prints with Wooden Frame") {
// PO#10959-1_ PS框連ESPON 打印_60 X 80cm[x1]
$customDescription = $this->poNumber.'_PS框連ESPON 打印_36 X 24" [x'.$this->qty.']';
} elseif (trim($this->itemName)=="Fotomax 3D Aluminum Prints") {
//$customDescription = $this->poNumber."_T-PD24100049 单品_单张材质印制_8X10_单片输出_MT1095_1P:1.2mm铝板 四周圆角 立体打印 8层白墨+1层色位 横竖 Amber[x".$this->qty."]";
$customDescription = $this->poNumber."_T-PD24100049 单品_单张材质印制_".$this->size."_单片输出[x".$this->qty."]";
} elseif (trim($this->itemName)=="T-PD25080092 画框_银色铝框_") {
$customDescription = $this->poNumber."_T-PD25080092 画框_银色铝框_62.6x86.6cm_成品包装_MT00000202_1P:画芯 48x71cm 外框 63x87cm 白卡装裱 横竖 [x".$this->qty."]";
} elseif (trim($this->itemName)=='AY - 20X24" Print on Zinc with Aluminum Frame') {
$customDescription = $this->poNumber."_T-PD015822 画框_黑色铝框_24X16_成品包装_MT4612_1P:外观:24.12x16.12(横+竖)锌板打印+裱5mm发泡板+黑卡_Amber [x".$this->qty."]";
} elseif (trim($this->size)=="") {
$customDescription = $this->poNumber."_".$this->itemName."_".$this->customMaterialName." [x".$this->qty."]";
} else {
$customDescription = $this->poNumber."_".$this->materialName."_".$this->size."_".$this->binding."_".$this->spreads." [x".$this->qty."]";
}
$this->Cell(10, 20, $customDescription, 0, false, 'L', 0, '', 0, false, 'T', 'M');
$this->Cell(195, 20, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
}
}
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->htmlHeader = getHeaderString($poObj->po_number, 1, $poObj->po_date, $poObj->order_id);
$pdf->htmlAddress = $htmlAddress;
$pdf->htmlPrice = $htmlPrice;
$pdf->htmlDate = $htmlDate;
$pdf->htmlSign = $htmlSign;
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('WH-HKMIS');
$pdf->SetTitle('AMBER PO');
$pdf->SetSubject('AMBER PO');
$pdf->SetKeywords('AMBER PO');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array('DroidSansFallback', '', PDF_FONT_SIZE_DATA));
$pdf->setFooterFont(Array('DroidSansFallback', '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, 80, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, 65);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// ---------------------------------------------------------
// set font
$pdf->SetFont('DroidSansFallback', '', 7, '', true);
// add a page
//$pdf->AddPage();
// draw product table
$sql = "SELECT * FROM custom_po_detail WHERE po_id = '".$_GET['id']."%' ";
$result = $wpdb->get_results($sql);
$i = 1;
$canvasCount=0;
foreach($result as $poLineObj){
$pdf->resetHeaderTemplate();
$pdf->htmlHeader = getHeaderString($poObj->po_number, $i, $poObj->po_date, $poObj->order_id);
$pdf->AddPage();
$pdf->poNumber = $poObj->po_number."-".$i;
$htmlProduct = '<div id="productSection">';
$htmlProduct .= '<table cellspacing="0" cellpadding="0" border="0.001" nobr="true" class="productTable"><tr><td>
<table cellspacing="0" cellpadding="3">
<tr style="background-color:#000;color:#FFF">
<td width="20%" align="left">Description '.$i.'</td>
<td width="48%" align="left"></td>
<td width="10%" align="center">Qty.</td>
<td width="12%" align="center">Unit Price ('.$poObj->currency.')</td>
<td width="10%" align="center">Total ('.$poObj->currency.')</td>
</tr> ';
$i++;
$bill_to_name = $order->get_formatted_billing_full_name();
$array_logo_file = array(
'Upload' => get_customer_logo_po($bill_to_name)!=""?get_customer_logo_po(trim($bill_to_name)):'Logo圖樣',
'Letterpress' => "壓字粒"
);
if($poLineObj->item_type=="Product Cost"){
$pdf->spreads = "";
$pdf->size = "";
$pdf->binding = "";
$pdf->materialName = "";
$pdf->customMaterialName = "";
$pdf->qty = "";
$pdf->itemName = "";
$arr_content = explode("\r\n", $poLineObj->item_name);
$pdf->qty = $poLineObj->item_qty;
foreach($arr_content as $content_line){
$arr_content_line = explode("::",$content_line);
if($arr_content_line[0]=="Name 產品名稱") {
$itemName = $arr_content_line[1];
$pdf->itemName = $arr_content_line[1];
$htmlProduct .= '<tr><td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$arr_content_line[0].'</td><td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$arr_content_line[1].'</td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray"><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$poLineObj->item_qty.'</td><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.number_format($poLineObj->item_unit_price,2,".",",").'</td><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.number_format($poLineObj->item_total,2,".",",").'</td></tr>';
} else {
if($arr_content_line[0]=="Material 物料") {
$pdf->customMaterialName = trim($arr_content_line[1]);
}
if($arr_content_line[0]=="Spreads 頁數") {
$pdf->spreads = trim($arr_content_line[1]);
}
if($arr_content_line[0]=="Size 尺寸") {
$pdf->size = trim($arr_content_line[1]);
}
if($arr_content_line[0]=="Canvas尺寸") {
$pdf->size = str_replace(" ","",str_replace('"',"",trim($arr_content_line[1])));
}
if($arr_content_line[0]=="Prints Size") {
$pdf->size = trim(str_replace(array( "'",'"',' ','\r','\n','\r\n'),'',$arr_content_line[1]));
}
if($arr_content_line[0]=="Binding 釘裝方式") {
$lineContents = explode("(",trim($arr_content_line[1]));
$pdf->binding = rtrim($lineContents[1],")");
}
if($arr_content_line[0]=="Color 封殼物料") {
$lineContents = explode("(",trim($arr_content_line[1]));
$lineContents2 = explode("+",trim($lineContents[1]));
$arr_adjusted = explode(" ",trim($lineContents2[0]));
array_shift($arr_adjusted);
$finaliszed_string = implode($arr_adjusted, " ");
$finaliszed_string = str_replace(":","",$finaliszed_string);
$pdf->materialName = trim($finaliszed_string);
}
$htmlProduct .= '<tr><td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$arr_content_line[0].'</td><td colspan="4" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$arr_content_line[1].'</td></tr>';
}
if($arr_content_line[0]=="Fotomax PO") {
$fotomaxPo = $arr_content_line[1];
}
}
} else {
$itemName = $poLineObj->item_name;
$htmlProduct .= '<tr><td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$poLineObj->item_type.'</td><td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$poLineObj->item_name.'</td><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$poLineObj->item_qty.'</td><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.number_format($poLineObj->item_unit_price,2,".",",").'</td><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.number_format($poLineObj->item_total,2,".",",").'</td></tr>';
}
$htmlProduct .= '</table></td></tr></table>';
$htmlProduct .= '</div>';
$pdf->writeHTML($htmlProduct, true, false, false, false, '');
$init_X = $pdf->getX();
$init_Y = $pdf->getY();
$w = 47.5;
$fileCount=0;
$col_per_row = 4;
if(trim($itemName)=="Canvas" || trim($itemName)=="Fine art prints with Wooden Frame" || trim($itemName)=="Fotomax 3D Aluminum Prints" || trim($itemName)=="Fotomax HD Aluminum Prints 高清鋁板相片" || trim($itemName)=="Print on Canvas with Wooden Frame"){
$file = get_post_meta($order_id, '_wcuf_uploaded_files', true);
if($file!=""){
foreach($file as $fileArr){
$source_image = imagecreatefromjpeg($fileArr['absolute_path'][$canvasCount]);
$h = (imagesy($source_image)/imagesx($source_image))*$w;
$row = floor($fileCount/$col_per_row);
$col = $fileCount%$col_per_row;
$x = $init_X + $col*$w;
$y = $init_Y + $row*$h;
$pdf->Image($fileArr['absolute_path'][$canvasCount], $x, $y, $w, $h, 'JPG', '', '', true, 150, '', false, false, 1, false, false, false);
$fileCount++;
}
$canvasCount++;
}
}
// draw footer cell (left)
if($isFotomax){
$customer_address = "";
$htmlShipping = "Fotomax<br>";
if(isset($fotomaxPo)) $htmlShipping .= "(".$fotomaxPo.")<br>";
$customer_address = "收件人名稱: ".$poObj->customerName."<br>收件地址: ".$poObj->customerAddress."<br>收件人電話: ".$poObj->customerPhone."<br>順豐: ".$poObj->courierPayment;
$htmlShipping .= $customer_address;
} else {
$customer_address = "";
/*
$arr_customer_address = explode("\r\n", $poObj->customer_ship_address);
foreach($arr_customer_address as $customer_address_line){
$customer_address .= $customer_address_line."<br>";
}
*/
$customer_address = "收件人名稱: ".$poObj->customerName."<br>收件地址: ".$poObj->customerAddress."<br>收件人電話: ".$poObj->customerPhone."<br>順豐: ".$poObj->courierPayment;
$htmlShipping = $customer_address;
}
$pdf->htmlShipping = $htmlShipping;
}
//$pdf->lastPage();
// ---------------------------------------------------------
//Close and output PDF document
//$poKey = 'PO'.$order->get_order_number().'-'.$i;
//Close and output PDF document
try {
$sql = "SELECT * FROM custom_po_detail WHERE po_id = '".$_GET['id']."%' ";
$result = $wpdb->get_results($sql);
$i = 1;
foreach($result as $poLineObj){
//echo "1";
$poKey = 'PO'.$order->get_order_number()."-".$i;
$output_path = "/var/www/html/ossfs/amber/po/".$poKey."/";
$permissions = 0777;
if (!is_dir($output_path)) {
//echo "2";
// Create the directory
if (mkdir($output_path, $permissions, true)) { // 'true' enables recursive creation of parent dirs if needed
//echo "3";
chmod($output_path, $permissions);
}
} else {
//echo "4";
chmod($output_path, $permissions);
}
//echo "5";
$pdf->Output($output_path.$poKey.'.pdf', 'F');
$i++;
}
generateJson($_GET['id'], $wpdb);
} catch (Exception $e) {
echo json_encode(['success'=>false, 'message'=>'Failed to generate PDF content: ' . $e->getMessage()]);
//throw new RuntimeException("Failed to generate PDF content: " . $e->getMessage(), 0, $e);
}
//$pdf->Output($poObj->po_number.'.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+
function generateJson($id, $wpdb){
if(isset($id) && $id!="") {
$sql = "SELECT * FROM custom_po_master WHERE id = '".$id."%' LIMIT 1";
$result = $wpdb->get_results($sql);
if(count($result)>0){
$poObj = $result[0];
} else {
echo json_encode(['success'=>false, 'message'=>'Invalid PO']);
exit();
}
} else {
echo json_encode(['success'=>false, 'message'=>'Invalid Parameter']);
exit();
}
$order_id = $poObj->order_id;
$order = wc_get_order($order_id);
$isFotomax = $order->get_user_id()==7?true:false;
$sql = "SELECT * FROM custom_po_detail WHERE po_id = '".$_GET['id']."%' ";
$result = $wpdb->get_results($sql);
$productArr = array();
$itemNumber = 1;
foreach($result as $lineNo=>$poLineObj){
$photoID = 1;
$lineRemark = "順豐: ".$poObj->courierPayment;
/*
$arrLineDetail = explode("\r\n", $poLineObj->item_name);
foreach($arrLineDetail as $lineDetail){
if(strpos($lineDetail, "備註") !== false)
$lineRemark .= $lineDetail;
}
*/
$key = str_replace("PO#","PO",$poObj->po_number)."-".($lineNo+1);
$orderData = array();
//$orderData['OrderId'] = $poObj->po_number."-".$i;
$orderData['OrderId'] = $poObj->po_number;
$orderData['Status'] = "有效";
$orderData['OrderTime'] = date("Y-m-d H:i:s");
$orderData['Remark'] = $lineRemark;
//$orderData['Remark'] = "TEST";
$orderData['StoreId'] = "C000889";
$orderData['StoreName'] = "AMBER CONCEPT";
$orderData['ShippingReceiver'] = array();
/*
$orderData['ShippingReceiver']['Name'] = $order->shipping_first_name." ".$order->shipping_last_name;
$orderData['ShippingReceiver']['Province'] = "香港";
$orderData['ShippingReceiver']['City'] = $order->shipping_city;
$orderData['ShippingReceiver']['CityPart'] = "";
$orderData['ShippingReceiver']['Street'] = $order->shipping_city.$order->shipping_address_1.$order->shipping_address_2;
$orderData['ShippingReceiver']['Phone'] = get_post_meta( $order_id, '_shipping_phone', true );
*/
$orderData['ShippingReceiver']['Name'] = $poObj->customerName;
$orderData['ShippingReceiver']['Province'] = "香港";
$orderData['ShippingReceiver']['City'] = "香港";
$orderData['ShippingReceiver']['CityPart'] = "";
$orderData['ShippingReceiver']['Street'] = $poObj->customerAddress;
$orderData['ShippingReceiver']['Phone'] = $poObj->customerPhone;
$orderData['OrderItems'] = array();
$photos = null;
$photos = array();
$directory = "/var/www/html/ossfs/amber/po/".$key;
if (is_dir($directory)) {
$files = scandir($directory);
foreach ($files as $filename) {
// Skip the current and parent directory entries
if ($filename === '.' || $filename === '..') {
continue;
}
// Add the full path to the file list
$photos[] = array(
"PhotoId" => strval($photoID),
"PhotoName" => $filename,
"PicPath" => "https://www.amberconcept.com/uploads/".$key."/".$filename
);
$photoID++;
}
}
/*
$arr_content = explode("\r\n", $poLineObj->item_name);
foreach($arr_content as $content_line){
$arr_content_line = explode("::",$content_line);
if($arr_content_line[0]=="Name 產品名稱") {
$itemName = $arr_content_line[1];
}
if($arr_content_line[0]=="Name 產品名稱") {
$itemName = $arr_content_line[1];
}
}
*/
/*
if(trim($itemName)=="Canvas" || trim($itemName)=="Fine art prints with Wooden Frame" || trim($itemName)=="Fotomax 3D Aluminum Prints" || trim($itemName)=="Fotomax HD Aluminum Prints 高清鋁板相片" || trim($itemName)=="Print on Canvas with Wooden Frame"){
$wordpressFile = get_post_meta($order_id, '_wcuf_uploaded_files', true);
if($wordpressFile!=""){
foreach($wordpressFile as $fileArr){
$photos[] = array(
"PhotoId" => strval($photoID),
"PhotoName" => $fileArr['original_filename'][0],
"PicPath" => $fileArr['url'][0]
);
$photoID++;
}
}
}
*/
$arr_content = explode("\r\n", $poLineObj->item_name);
$qty = $poLineObj->item_qty;
$size = "";
$spreads = "";
$binding = "";
$materialName = "";
$customMaterialName = "";
$box = "";
$logoLetterPress = "";
$logoLetterpressFinishing = "";
$logoLetterpressPosition = "";
$logoLetterpressRemark = "";
$logoLetterpressText = "";
$logoLetterpressFont = "";
foreach($arr_content as $content_line){
$arr_content_line = explode("::",$content_line);
if($arr_content_line[0]=="Name 產品名稱") {
$itemName = $arr_content_line[1];
//$htmlProduct .= '<tr><td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$arr_content_line[0].'</td><td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$arr_content_line[1].'</td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray"><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$poLineObj->item_qty.'</td><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.number_format($poLineObj->item_unit_price,2,".",",").'</td><td align="right" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.number_format($poLineObj->item_total,2,".",",").'</td></tr>';
} else {
if($arr_content_line[0]=="Material 物料") {
$customMaterialName = trim($arr_content_line[1]);
}
if($arr_content_line[0]=="Spreads 頁數") {
$spreads = trim($arr_content_line[1]);
}
if($arr_content_line[0]=="Size 尺寸") {
$size = trim($arr_content_line[1]);
}
if($arr_content_line[0]=="Canvas尺寸") {
$size = str_replace(" ","",str_replace('"',"",trim($arr_content_line[1])));
}
if($arr_content_line[0]=="Prints Size") {
$size = trim(str_replace(array( "'",'"',' ','\r','\n','\r\n'),'',$arr_content_line[1]));
}
if($arr_content_line[0]=="Binding 釘裝方式") {
$lineContents = explode("(",trim($arr_content_line[1]));
$binding = rtrim($lineContents[1],")");
}
if($arr_content_line[0]=="Color 封殼物料") {
$lineContents = explode("(",trim($arr_content_line[1]));
$lineContents2 = explode("+",trim($lineContents[1]));
$arr_adjusted = explode(" ",trim($lineContents2[0]));
array_shift($arr_adjusted);
$finaliszed_string = implode($arr_adjusted, " ");
$finaliszed_string = str_replace(":","",$finaliszed_string);
$materialName = trim($finaliszed_string);
}
//$htmlProduct .= '<tr><td style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$arr_content_line[0].'</td><td colspan="4" style="border-right:0.01px solid lightgray; border-bottom:0.01px solid lightgray">'.$arr_content_line[1].'</td></tr>';
}
if(trim($arr_content_line[0])=="Fotomax PO") {
$fotomaxPo = $arr_content_line[1];
}
if(trim($arr_content_line[0])=="Box 盒子") {
$box = $arr_content_line[1];
}
if(trim($arr_content_line[0])=="Logo/Letterpress on Cover?" || trim($arr_content_line[0])=="Letterpress") {
$logoLetterPress = $arr_content_line[1];
}
if(trim($arr_content_line[0])=="Logo/Letterpress Finishing 相冊後工序" || trim($arr_content_line[0])=="Letterpress Finishing 相冊後工序") {
$logoLetterpressFinishing = $arr_content_line[1];
}
if(trim($arr_content_line[0])=="Logo/Letterpress Position 位置" || trim($arr_content_line[0])=="Logo Position 位置") {
$logoLetterpressPosition = $arr_content_line[1];
}
if(trim($arr_content_line[0])=="Logo or Letterpress?") {
$logoLetterpressRemark = $arr_content_line[1];
}
if(trim($arr_content_line[0])=="Text") {
$logoLetterpressText = $arr_content_line[1];
}
if(trim($arr_content_line[0])=="Font 字款") {
$logoLetterpressFont = $arr_content_line[1];
}
}
if(trim($itemName)=="Print on Canvas with Wooden Frame"){
$customDescription = "T-PD24120009_PS深木色框 24x36 油画布输出_[x".$qty."]";
} elseif(trim($itemName)=="Fotomax HKBU Certificate"){
$customDescription = "T-PD25070104 _画框_红色实木证书装表框 8.27x11.73_[x".$qty."]";
} elseif(trim($itemName)=="Canvas"){
$customDescription = $size."_快速框 [x".$qty."]";
} elseif (trim($itemName)=="Fine art prints with Wooden Frame") {
$customDescription = 'PS框連ESPON 打印_36 X 24" [x'.$qty.']';
} elseif (trim($itemName)=="Fotomax 3D Aluminum Prints") {
$customDescription = "T-PD24100049 单品_单张材质印制_".$size."_单片输出[x".$qty."]";
} elseif (trim($itemName)=="9-Grid Matted Print") {
$customDescription = "T-PD25110087画框_AMBER_19.69X19.69_成品包装_MT0771_1P:无亚克力 9开窗内框3.94x3.94 外框:20x20 ;照片间0.47英寸;白卡; PS深木色3443-826T Amber专用 [x".$qty."]";
} elseif (trim($itemName)=="T-PD25080092 画框_银色铝框_") {
$customDescription = "T-PD25080092 画框_银色铝框_62.6x86.6cm_成品包装_MT00000202_1P:画芯 48x71cm 外框 63x87cm 白卡装裱 横竖 Amber专用 [x".$qty."]";
} elseif (trim($itemName)=='AY - 20X24" Print on Zinc with Aluminum Frame') {
$customDescription = "T-PD015822 画框_黑色铝框_24X16_成品包装_MT4612_1P:外观:24.12x16.12(横+竖)锌板打印+裱5mm发泡板+黑卡_Amber [x".$qty."]";
} elseif (trim($size)=="") {
$customDescription = $itemName."_".$customMaterialName."_[x".$qty."]";
} else {
//$customDescription = $materialName."_".$size."_".$binding."_".$spreads." [x".$qty."]";
$customDescription = $materialName."_".$size."_".$binding."_[x".$qty."]";
}
/*
$product = [
"OrderProductId" => ($lineNo+1),
"CtmName" => $poLineObj->item_name,
"ProductName" => $customDescription,
"ProductId" => $customDescription,
"Num" => strval($poLineObj->item_qty),
"Photos" => $photos
];
*/
$product = [
"OrderProductId" => $itemNumber,
"CtmName" => $poObj->po_number."-".($lineNo+1),
"ProductName" => $customDescription,
"ProductId" => $customDescription,
"Num" => strval($poLineObj->item_qty),
"Photos" => $photos
];
$itemNumber++;
//$orderData['OrderItems'][]['Products'][] = $product;
$productArr[]=$product;
// for logo (separate product) //
if(strtoupper(trim($logoLetterPress))=="YES") {
$logoLetterpressFinishingItemName = $logoLetterpressFinishing;
if(!empty($logoLetterpressPosition)) {
$logoLetterpressFinishingItemName .= "_".$logoLetterpressPosition;
}
if(!empty($logoLetterpressRemark)) {
$logoLetterpressFinishingItemName .= "_".$logoLetterpressRemark;
}
if(!empty($logoLetterpressText)) {
$logoLetterpressFinishingItemName .= "_".$logoLetterpressText;
}
if(!empty($logoLetterpressFont)) {
$logoLetterpressFinishingItemName .= "_".$logoLetterpressFont;
}
$logoLetterPressProduct = [
"OrderProductId" => $itemNumber,
"CtmName" => $poObj->po_number."-".($lineNo+1),
"ProductName" => $logoLetterpressFinishingItemName,
"ProductId" => $logoLetterpressFinishingItemName,
"Num" => strval($poLineObj->item_qty),
"Photos" => []
];
$itemNumber++;
$productArr[]=$logoLetterPressProduct;
}
// for box (separate product) //
if(!empty($box)) {
$boxProduct = [
"OrderProductId" => $itemNumber,
"CtmName" => $poObj->po_number."-".($lineNo+1),
"ProductName" => $box."_".$size,
"ProductId" => $box."_".$size,
"Num" => strval($poLineObj->item_qty),
"Photos" => []
];
$itemNumber++;
$productArr[]=$boxProduct;
}
/*
echo "<pre>";
print_r($productArr);
echo "</pre>";
*/
}
$orderData['OrderItems'][]['Products'] = $productArr;
/*
echo "<pre>";
print_r($orderData);
echo "</pre>";
*/
$postJson = json_encode($orderData, JSON_PRETTY_PRINT);
//$postJson = json_encode($orderData, JSON_UNESCAPED_UNICODE);
// Usage
try {
$result = postToApi($postJson);
if($result['body']['执行结果']=="成功"){
$wpdb->update(
'custom_po_master',
array(
'status' => 2,
'submittedJSON' => $postJson
),
array('id'=>$_GET['id'])
);
echo json_encode(['success'=>true, 'message'=>'submitted']);
} else {
//echo json_encode(['success'=>false, 'message'=>$result['body']['执行结果']]);
echo json_encode(['success'=>false, 'message'=>json_encode($result['body'])]);
}
//echo "Success! Code: ".$result['code']." Response: " . json_encode($result['body'], JSON_PRETTY_PRINT) . "\n";
} catch (Exception $e) {
echo json_encode(['success'=>false, 'message'=>$e->getMessage()]);
//echo "Failed: " . $e->getMessage() . "\n";
}
}
function postToApi($postJson, $headers = []) {
$url = "https://tos.wphoto123.com:88/B_ERP.aspx";
$data = [
'FCType' => 'BIN002',
'FCData' => $postJson
];
$ch = curl_init();
// Basic setup
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true, // Return response as string, don't output
CURLOPT_POST => true, // Enable POST
CURLOPT_POSTFIELDS => http_build_query($data), // Form data
CURLOPT_HTTPHEADER => array_merge([
'Content-Type: application/x-www-form-urlencoded',
'User-Agent: MyApp/1.0'
], $headers),
CURLOPT_TIMEOUT => 30, // 30-second timeout
CURLOPT_SSL_VERIFYPEER => false, // Verify SSL (security)
CURLOPT_FOLLOWLOCATION => true // Follow redirects
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception("cURL Error: " . $error);
}
if ($httpCode >= 200 && $httpCode < 300) {
return [
'success' => true,
'code' => $httpCode,
'body' => json_decode($response, true) ?? $response
];
} else {
throw new Exception("HTTP Error: $httpCode - $response");
}
}