function constructPIContent($pdf, $output, $order, $ignoreStockStatusDepot, $print_per_orders)
 {
     /*  NOTES!!!!!!!!!!!!!!!!
      *  if $print_per_orders == false, $order should contain "collections of orders"
      *  elseif $print_per_orders == true, $order should contain "one order only"
      */
     use_class('Product');
     use_class('ProductAttribute');
     global $class_pm, $class_pb, $product_categories_name, $DIAMOND_BRAND_IDS;
     if ($print_per_orders) {
         $orders[] = $order;
     } else {
         $orders = $order;
     }
     //echo "<pre>";var_dump($orders);die();
     $margin = 5;
     $fontsize_big = '9';
     $fontsize_med = '8';
     $fontsize_sml = '7';
     $fontsize_tny = '5';
     $barcode_width = 32;
     $barcode_pos = 210 - $margin - $barcode_width - 1;
     $element_name_max_chars = 30;
     if ($output == 'F') {
         //PRODUCE PDF FILE PER ITEM (MULTI PDF FILE PER ORDER)
         $pdf = new PDF('P', 'mm', 'A4');
         $pdf->setTitle('Production Instruction');
         $pdf->SetAuthor('JULIE GRACE / Bonofactum');
         $pdf->SetCreator('k-Auto Generated PDF');
         $pdf->SetDisplayMode('real');
         $pdf->SetAutoPageBreak(false);
         $pdf->AliasNbPages();
         $pdf->SetFillColor(191, 191, 191);
     }
     //start looping orders
     foreach ($orders as $order) {
         $o = $order['detail'];
         $is_ottob2b = $o['jng_sp_id'] == '11' || strpos(strtolower($o['customer']), 'otto b2b') !== false;
         foreach ($order['items'] as $oiid => $i) {
             if ($i['status'] < 8) {
                 $this->pi_printed[strtolower($o['type'])][] = $oiid;
             }
             $obj_product = new Product($i['products_id']);
             $is_gold_product = $obj_product->metal_stamp_code > 0 && $obj_product->metal_stamp_code != 925;
             $pdf->pi_number = $o['id'];
             if ($this->duplex_printing && isset($item_page_count) && $item_page_count % 2 != 0) {
                 $pdf->AddPage();
             }
             $pdf->AddPage();
             $item_page_count = 1;
             $product_key = $i['products_id'] . '-' . $i['articles_id'];
             $product_qty = intval($i['quantity']);
             $p = $this->products[$product_key];
             $is_elli_premium = $p['p']['products_brand_id'] == '29';
             $is_diamore = in_array($p['p']['products_brand_id'], $DIAMOND_BRAND_IDS);
             $is_pearl = $p['p']['products_brand_id'] == '7';
             $ean = $this->products_ean[$product_key];
             $product_complexity = strtoupper(productComplexityName($p['p']['complexity']));
             $order_type_code = '';
             if (strtoupper($o['type']) == 'DP') {
                 $order_type_code = strtoupper($o['type']);
                 $otc_width = 12;
             } else {
                 $order_type_code = $o['customer_type'];
                 $otc_width = 20;
             }
             $pdf->OrderBarcode($o['type'], $oiid, $barcode_pos, $margin, $barcode_width);
             $pdf->setFont('Arial', 'B', '12');
             $YPOS = $margin;
             $lineheight = 4;
             //ORDER TYPE CODE (JG,SP,DP)
             $pdf->SetXY($barcode_pos - $otc_width, 10);
             $pdf->Cell(100, $lineheight, $order_type_code);
             //PROCESS DATE
             $pdf->setFont('Arial', 'B', $fontsize_big);
             $process_date = date('d M Y', strtotime($i['prod_target_in']));
             $pdf->SetXY($barcode_pos, 22);
             $pdf->Cell($barcode_width, $lineheight, $process_date, 0, 2, 'R');
             //PRODUCT COMPLEXITY
             $pdf->setFont('Arial', 'B', '12');
             $pdf->SetXY($barcode_pos, 22 + $lineheight + 5);
             $pdf->Cell($barcode_width, $lineheight, $product_complexity, 0, 2, 'R');
             //PAGE HEADER
             $margin_orderinfo = $margin + 50;
             $pdf->SetXY($margin_orderinfo, $YPOS);
             $pdf->Cell(100, $lineheight, 'Production Instruction ' . $o['id'] . ' (' . $i['counter'] . ') - print ' . ($i['print_count'] + 1));
             $YPOS += $lineheight + 1;
             //ORDER INFORMATION
             $lineheight = 3.5;
             $orderilbl = array();
             $orderinfo = array();
             $orderilbl[] = 'Ship To (Country)';
             $orderinfo[] = ': ' . trim($o['shipto_name']) . ($o['shipto_address'] != '' ? ' (' . $o['shipto_address'] . ')' : '');
             //Show shipping window date only for order which using amazon logistic
             if (in_array($o['jng_sp_id'], array_keys(getSalesPartnerUseAmazonLogistic())) && isset($i['shipping_window_open'])) {
                 $orderilbl[] = 'Shipping Window Date';
                 $orderinfo[] = ': ' . date('d. M Y', strtotime($i['shipping_window_open']));
             }
             /* Moved to below barcode
                $orderilbl[] = 'Process Date';
                $orderinfo[] = ': '.date('d. M Y', strtotime($i['prod_target_in']));
                 */
             $orderilbl[] = 'Customer Name';
             $vip_status = $o['customer_is_vip'] ? ' ( VIP )' : '';
             if ($is_ottob2b) {
                 $orderinfo[] = ': OTTO B2B';
             } else {
                 $orderinfo[] = ': ' . $o['customer'] . $vip_status;
             }
             //$orderilbl[] = 'Order Source / Customer Name';
             //$orderinfo[] = ': '.$o['customer_type'].' / '.$o['customer'];
             //$orderilbl[] = 'Product Qty x EAN (ID / Code)';
             //$orderinfo[] = ': '.intval($i['quantity']).' x '.$ean.' ('.$p['p']['products_id'].' / '.$p['p']['products_model'].')';
             $orderilbl[] = 'Product Qty x EAN';
             $orderinfo[] = ': ' . $product_qty . ' x ' . $ean;
             $pdf->setFont('Arial', '', $fontsize_med);
             $pdf->setXY($margin_orderinfo, $YPOS);
             $pdf->MultiCell(50, $lineheight, implode("\n", $orderilbl));
             $pdf->setXY($margin_orderinfo + 30, $YPOS);
             $pdf->MultiCell(100, $lineheight, implode("\n", $orderinfo));
             $maxline = count($orderilbl);
             $YPOS += $maxline * $lineheight + 10;
             //STOCK PREPARATION
             $pdf->setFont('Arial', 'B', $fontsize_big);
             if ($i['stock_status'] == 'D' && !$ignoreStockStatusDepot) {
                 //USE DEPOT STOCK
                 $lineheight = 6;
                 $pdf->SetXY($margin + 1, $YPOS);
                 $pdf->Cell(100, $lineheight, 'Depot Stock', 1, 0, 'C', true);
                 $YPOS += $lineheight + 3;
             } elseif ($i['stock_status'] == 'P') {
                 //USE FINISH GOOD STOCK
                 $lineheight = 6;
                 $pdf->SetXY($margin + 1, $YPOS);
                 $pdf->Cell(100, $lineheight, 'Finish Good', 1, 0, 'C', true);
                 $YPOS += $lineheight + 3;
             } else {
                 //USE ELEMENTS STOCK
                 $lineheight = 4;
                 $pdf->SetXY($margin, $YPOS);
                 $pdf->Cell(100, $lineheight, 'Elements Preparation');
                 $YPOS += $lineheight + 1;
                 $pue_total = count($p['elements']);
                 $pue_rows = ceil($pue_total / 2);
                 $max_rows_el_per_page_1 = 12;
                 //MAX ROWS ELEMENT ON PAGE 1
                 $max_rows_el_per_page_n = 14;
                 //MAX ROWS ELEMENT ON NEXT PAGE
                 $max_rows_el_per_page = $max_rows_el_per_page_1;
                 $pue_counter = 0;
                 $pue_number = 0;
                 $rowpos = $YPOS;
                 $colpos = $margin + 1;
                 $colheight = 20;
                 $col_subcol_width = array();
                 $col_subcol_width[1] = 6;
                 //          $col_subcol_width[2] = $colheight;
                 $col_subcol_width[2] = 20;
                 $col_subcol_width[3] = 10;
                 $col_subcol_width[4] = 51;
                 $col_subcol_width[5] = 10;
                 $col_subcol_imgepos = $col_subcol_width[1];
                 $col_subcol_infopos = $col_subcol_width[1] + $col_subcol_width[2] + $col_subcol_width[3];
                 $colwidth = array_sum($col_subcol_width);
                 $print_header_el = false;
                 foreach ($p['elements'] as $element) {
                     if ($pue_counter == 0 || $print_header_el) {
                         $lineheight = 5;
                         $pdf->setXY($colpos, $rowpos);
                         $pdf->setFont('Arial', 'B', $fontsize_med);
                         $pdf->Cell($col_subcol_width[1], $lineheight, 'No', 1, 0, 'C', true);
                         $pdf->Cell($col_subcol_width[2], $lineheight, 'Image', 1, 0, 'C', true);
                         $pdf->Cell($col_subcol_width[3], $lineheight, 'ID', 1, 0, 'C', true);
                         $pdf->Cell($col_subcol_width[4], $lineheight, 'Info', 1, 0, 'C', true);
                         $pdf->Cell($col_subcol_width[5], $lineheight, 'Qty', 1, 0, 'C', true);
                         $rowpos += $lineheight;
                     }
                     $pue_counter++;
                     $pue_number++;
                     $e = $this->elements[$element['elements_id']];
                     $element_image = $this->getImageForPDF($e->image, '80', '80');
                     $element_info = array();
                     $element_info['n'] = substr($e->detail['name'], 0, $element_name_max_chars) . (strlen($e->detail['name']) > $element_name_max_chars ? '...' : '');
                     //var_dump($e->attributes); exit;
                     $element_info['c'] = $e->attributes['color']['name'];
                     //$element_info['s'] = $e->attributes['size']['name'];
                     $material_name = array();
                     $material_name = explode(',', $e->attributes['material']['name']);
                     $element_info['m'] = count($material_name) > 1 ? $material_name[1] : $material_name[0];
                     $element_info['sh'] = '';
                     if (!eregi('other', $e->attributes['size']['name'])) {
                         $element_info['sh'] = $e->attributes['size']['name'];
                     }
                     if (!eregi('other', $e->attributes['shape']['name'])) {
                         if ($element_info['sh'] != '') {
                             $element_info['sh'] .= '.';
                         }
                         $element_info['sh'] .= $e->attributes['shape']['name'];
                     }
                     //$element_info['h'] = $e->attributes['shape']['name'];
                     if ($this->products[$product_key]['elements'][$element['elements_id']]['finishing_hammer'] == '1') {
                         $element_info['f'][] = 'Hammered';
                     }
                     if ($this->products[$product_key]['elements'][$element['elements_id']]['finishing_brush'] == '1') {
                         $element_info['f'][] = 'Brushed';
                     }
                     if ($this->products[$product_key]['elements'][$element['elements_id']]['finishing_oxid'] == '1') {
                         $element_info['f'][] = 'Oxidized/No Antitarnish';
                     }
                     if ($this->products[$product_key]['elements'][$element['elements_id']]['finishing_goldplate'] == '1') {
                         $element_info['f'][] = 'Yellow Goldplated';
                     }
                     if ($this->products[$product_key]['elements'][$element['elements_id']]['finishing_rosegoldplate'] == '1') {
                         $element_info['f'][] = 'Rose Goldplate';
                     }
                     $element_info['f'] = count($element_info['f']) > 0 ? implode(',', $element_info['f']) : '';
                     if ($element_image != '') {
                         $pdf->Image($element_image, $colpos + $col_subcol_imgepos, $rowpos, $col_subcol_width[2]);
                     }
                     $pdf->setXY($colpos, $rowpos);
                     $pdf->setFont('Arial', '', $fontsize_med);
                     $pdf->Cell($col_subcol_width[1], $colheight, $pue_number, 1, 0, 'C', true);
                     $pdf->Cell($col_subcol_width[2], $colheight, '', 1, 0, 'C');
                     $pdf->Cell($col_subcol_width[3], $colheight, $element['elements_id'], 1, 0, 'C');
                     $pdf->Cell($col_subcol_width[4], $colheight, '', 1, 0, 'C');
                     $pdf->Cell($col_subcol_width[5], 10, $product_qty * $element['quantity'], 1, 0, 'C');
                     $pdf->setXY($colpos + $col_subcol_width[1] + $col_subcol_width[2] + $col_subcol_width[3] + $col_subcol_width[4], $rowpos + 10);
                     $pdf->SetTextColor(209, 209, 209);
                     $pdf->setFont('Arial', 'B', $fontsize_big + 2);
                     $pdf->Cell($col_subcol_width[5], 10, 'QC', 1, 0, 'C');
                     $pdf->SetTextColor(0, 0, 0);
                     $pdf->setFont('Arial', '', $fontsize_med);
                     //$pdf->setXY($colpos + $col_subcol_infopos, $rowpos);
                     //$pdf->MultiCell($col_subcol_width[4], 4, implode("\n", $element_info), 0, 'C');
                     $rowpos_incol = $rowpos + 1;
                     //TODO: make column table could wrapped for text and have flexible height, for example please find this reference : http://www.fpdf.de/downloads/addons/3/
                     $ei_labels = array('s' => 'Size: ', 'm' => 'Material: ', 'h' => 'Shape: ');
                     foreach ($element_info as $key => $ei) {
                         if ($ei != '') {
                             if ($key == 'c') {
                                 $pdf->setFont('Arial', 'B', $fontsize_big + 2);
                                 $lineheight = 4;
                             } elseif ($key == 'f') {
                                 $pdf->setFont('Arial', 'B', $fontsize_big);
                                 $lineheight = 4;
                             } else {
                                 $pdf->setFont('Arial', '', $fontsize_med);
                                 $lineheight = 3.5;
                             }
                             if (array_key_exists($key, $ei_labels)) {
                                 $ei = $ei_labels[$key] . $ei;
                             }
                             $pdf->setXY($colpos + $col_subcol_infopos, $rowpos_incol);
                             $pdf->Cell($col_subcol_width[4], $lineheight, $ei, 0, 0, 'C');
                             $rowpos_incol += $lineheight;
                         }
                     }
                     if ($pue_rows > $max_rows_el_per_page) {
                         //IF ELEMENT USED MORE THAN MAX ROWS ELEMENT COULD FIT PER PAGE
                         $n_rows = $max_rows_el_per_page;
                     } else {
                         $n_rows = $pue_rows;
                     }
                     if ($pue_counter == $n_rows) {
                         $colpos = $margin + $colwidth + 5;
                         $rowpos = $YPOS;
                         $print_header_el = true;
                     } else {
                         $print_header_el = false;
                         $rowpos += $colheight;
                         if ($pue_counter % $max_rows_el_per_page == 0 && $pue_counter / $max_rows_el_per_page > 1) {
                             //IF ELEMENT USED REACH THE END OF PAGE AND THERE STILL ELEMENT NEED TO BE PRINTED
                             $pdf->AddPage();
                             if ($pdf->PageNo() > 1) {
                                 $max_rows_el_per_page = $max_rows_el_per_page_n;
                             }
                             //SET MARGIN TO THE VERY TOP OF PAGE
                             $colpos = $margin + 1;
                             $rowpos = $margin;
                             $YPOS = $rowpos;
                             $pue_rows = ceil(($pue_total - $pue_number) / 2);
                             //RECALCULATE THE REST OF ELEMENTS THAT COULD DIVIDED INTO 2 COLUMNS
                             $pue_counter = 0;
                         }
                     }
                 }
                 $YPOS += 5 + 3 + $pue_rows * $colheight;
             }
             //PRODUCT INFORMATION
             if ($pue_rows > 9) {
                 $pdf->AddPage();
                 $item_page_count++;
                 $YPOS = $margin;
             }
             $lineheight = 4;
             $imgbig_width = 60;
             $imgsml_width = 25;
             $rowpos = $YPOS;
             $colpos = $margin + 1;
             $pdf->SetXY($margin, $YPOS);
             $pdf->setFont('Arial', 'B', $fontsize_big);
             $pdf->Cell(100, $lineheight, 'Product Information');
             $YPOS += $lineheight + 1;
             $rowpos = $YPOS;
             $imgbig = $this->getImageForPDF($p['p']['products_image'], '', '212');
             //if($imgbig!='') $pdf->Image($imgbig, $colpos, $rowpos, $imgbig_width);
             if ($imgbig != '') {
                 $colposmainimage = $colpos;
                 $image_metadata = getimagesize($imgbig);
                 //MAKE IMAGE CENTERED WHEN SIZE IS PORTRAIT
                 if ($image_metadata[0] == 147) {
                     $colposmainimage = $colpos + 9;
                 }
                 $pdf->Image($imgbig, $colposmainimage, $rowpos, 0, $imgbig_width);
             }
             $pdf->Rect($colpos, $rowpos, $imgbig_width, $imgbig_width);
             $rowpos_main_image = $YPOS + $imgbig_width + 2;
             $rowpos = $YPOS;
             $img_h_resized = 0;
             //SHOW LOGO DIAMORE AND ELLI PREMIUM FOR NON OTTO B2B ORDERS
             if ($i['products_id'] > 0 && ($is_diamore || $is_elli_premium)) {
                 $pb = $class_pb->retrieveDetail($p['p']['products_brand_id']);
                 $img_path = DIR_WS_IMAGES . $pb['brand_image'];
                 $imgsize = getimagesize($img_path);
                 $img_w = $imgsize[0];
                 $img_h = $imgsize[1];
                 $h_ratio = $img_h / $img_w;
                 $img_w_resized = 50;
                 $img_h_resized = $img_w_resized * $h_ratio;
                 $pdf->Image($img_path, 150, $YPOS, $img_w_resized, $img_h_resized);
             }
             /*USE IMAGE DIAMOND
               if($class_pm->productContainMaterials($i['products_id'], 52)) {
                   $img_path = FPDF_IMGPATH.'diamond.jpg';
                   $imgsize = getimagesize($img_path);
                   $img_w = $imgsize[0];
                   $img_h = $imgsize[1];
                   $h_ratio = $img_h/$img_w;
                   $img_w_resized = 40;
                   $img_h_resized = $img_w_resized * $h_ratio;
                   $pdf->Image($img_path,165,$YPOS,$img_w_resized,$img_h_resized);
               }
                */
             if ($is_gold_product) {
                 $lineheight = 6;
                 $leftpos = 150;
                 $rowpos = $YPOS + $img_h_resized + 2;
                 $pdf->SetFontSize($fontsize_big + 5);
                 $pdf->SetXY($leftpos, $rowpos);
                 $pdf->Cell(50, $lineheight, 'G O L D', 0, 2, 'C');
             }
             //SPECIAL TREATMENT
             $product_finishing_array_st = ProductAttribute::getOldStylesFunction()->retrieveList(ProductAttribute::GROUP_ID_PRODUCT_FINISHING);
             $finishing_product_st = ProductAttribute::displayAttributeName($i['products_id'], ProductAttribute::GROUP_ID_PRODUCT_FINISHING, '2');
             //echo "<pre>";var_dump($finishing_product_st);die();
             if (empty($finishing_product_st)) {
                 unset($finishing_product_st);
             }
             if ($finishing_product_st == NULL) {
                 $isset_product_finishing = false;
             } else {
                 $isset_product_finishing = true;
             }
             if (!$is_diamore && !$is_elli_premium) {
                 if ($isset_product_finishing) {
                     $rowpos = $YPOS + $img_h_resized;
                     $lineheight = 6;
                     $leftpos = 150;
                     //special treament
                     $pdf->SetFontSize($fontsize_big + 3);
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->Cell(50, $lineheight, 'SPECIAL TREATMENT', 0, 2, 'C');
                     if ($i['products_id'] > 0 && ($is_gold_product || $is_pearl)) {
                         if ($is_gold_product) {
                             //gold
                             $rowpos = $rowpos + 7;
                             $pdf->SetFontSize($fontsize_big + 1);
                             $pdf->SetXY($leftpos, $rowpos);
                             $pdf->Cell(50, $lineheight, 'G O L D', 0, 2, 'C');
                         }
                         /*
                                                     if ($is_elli_premium) {
                            $products_used_materials = $class_pm->retrieveProductMaterialsUsed($i['products_id']);
                            if (in_array(52, $products_used_materials)) {
                                $rowpos = $rowpos + 5;
                                $pdf->SetFontSize($fontsize_big+1);
                                $pdf->SetXY($leftpos, $rowpos);
                                $pdf->Cell(50, $lineheight, 'D I A M O N D', 0, 2, 'C');
                            }
                            if (in_array(5, $products_used_materials)) {
                                $rowpos = $rowpos + 5;
                                $pdf->SetFontSize($fontsize_big+1);
                                $pdf->SetXY($leftpos, $rowpos);
                                $pdf->Cell(50, $lineheight, 'P E A R L', 0, 2, 'C');
                            }
                                                     }
                                                     if ($is_diamore) {
                            //diamore
                            $rowpos = $rowpos + 5;
                            $pdf->SetFontSize($fontsize_big+1);
                            $pdf->SetXY($leftpos, $rowpos);
                            $pdf->Cell(50, $lineheight, 'D I A M O N D', 0, 2, 'C');
                                                     }
                         * 
                         */
                         if ($is_pearl) {
                             //pearl
                             $rowpos = $rowpos + 5;
                             $pdf->SetFontSize($fontsize_big + 1);
                             $pdf->SetXY($leftpos, $rowpos);
                             $pdf->Cell(50, $lineheight, 'P E A R L', 0, 2, 'C');
                         }
                     }
                     //$pdf->Rect(150, 120, $img_w_resized, 30);
                 }
             }
             $leftpos = $colpos + $imgbig_width + 2;
             $rowpos = $YPOS;
             $lineheight = 4;
             $linesep = 1;
             $pilbl = array();
             $pinfo = array();
             $pilbl[] = 'Product Category';
             $pinfo[] = ': ' . $product_categories_name[$p['categories_id']];
             $pilbl[] = 'Product ID';
             $pinfo[] = ': ' . $i['products_id'];
             $pilbl[] = 'Product Code';
             $pinfo[] = ': ' . $p['p']['products_model'];
             /* HIDE PRICE (REQUESTED BY CANTY & WAYAN TO PREVENT SMITH SPOTTED THE PRICE)
                $pilbl[] = 'Product Price';
                $pinfo[] = ': '.displayCurrency('EUR', $p['p']['products_price']);
                 */
             if ($p['length'] > 0) {
                 $pilbl[] = 'Product Length';
                 $pinfo[] = ': ' . textLength($p['length']);
             }
             $pilbl[] = 'Product Quantity';
             $pinfo[] = ': ' . $product_qty;
             $lbl_width = 30;
             $pdf->SetXY($leftpos, $rowpos);
             $pdf->setFont('Arial', 'B', $fontsize_big);
             $pdf->MultiCell($lbl_width, $lineheight + $linesep, implode("\n", $pilbl), 0, 'L');
             $pdf->SetXY($leftpos + $lbl_width, $rowpos);
             $pdf->MultiCell($lbl_width, $lineheight + $linesep, implode("\n", $pinfo), 0, 'L');
             $rowpos += count($pilbl) * ($lineheight + $linesep) + 2 * $linesep;
             //                $pdf->SetXY($leftpos, $rowpos);
             //                $pdf->setFont('Arial','B',$fontsize_med);
             //                $prodinfo = 'Product ID: '.$p['p']['products_id'];
             //                $pdf->Cell(100, $lineheight, $prodinfo);
             //                $rowpos += $lineheight + $linesep;
             //                $pdf->SetXY($leftpos, $rowpos);
             //                $pdf->setFont('Arial','B',$fontsize_med);
             //                $prodinfo = 'Product Code: '.$p['p']['products_model'];
             //                $pdf->Cell(100, $lineheight, $prodinfo);
             //                $rowpos += $lineheight + $linesep;
             //                if($p['length']>0) {
             //                    $pdf->SetXY($leftpos, $rowpos);
             //                    $pdf->setFont('Arial','B',$fontsize_med);
             //                    $prodinfo = 'Product Length: '.textLength($p['length']);
             //                    $pdf->Cell(100, $lineheight, $prodinfo);
             //                    $rowpos += $lineheight + $linesep;
             //                }
             $pdf->SetXY($leftpos, $rowpos);
             $pdf->setFont('Arial', 'B', $fontsize_big);
             $pdf->Cell(100, $lineheight, 'Product Name:');
             $rowpos += $lineheight;
             $pdf->SetXY($leftpos, $rowpos);
             $pdf->setFont('Arial', '', $fontsize_big);
             $pdf->Cell(100, $lineheight, $p['pd'][2]['products_name']);
             $rowpos += $lineheight + 2 * $linesep;
             if ($p['pnc']['production_instruction_id'] != '') {
                 $rowpos += $lineheight;
                 $piids = explode(",", $p['pnc']['production_instruction_id']);
                 $pdf->SetXY($leftpos, $rowpos);
                 $pdf->setFont('Arial', 'B', $fontsize_big);
                 $pdf->Cell(100, $lineheight, 'Production Instruction:');
                 $pdf->setFont('Arial', '');
                 $pims = array();
                 //MERGE ALL MANUAL PI THAT ATTACHED TO PRODUCT
                 foreach ($piids as $piid) {
                     $pim = new production_instruction_manual($piid);
                     $pi_temp = "\n" . $pim->cat_name . ' - ' . $pim->name;
                     if (trim($pim->description) != '') {
                         $pi_temp .= "\n" . $pim->description;
                     }
                     $pims[] = $pi_temp;
                 }
                 //EXPLODE EACH MANUAL PI WITH LINE FEED
                 $pi_manual = implode("\n", $pims);
                 $rowpos += $lineheight;
                 $pdf->SetXY($leftpos, $rowpos);
                 $pdf->MultiCell(0, $lineheight, trim($pi_manual), 0, 'L');
                 $manpi_rows = explode("\n", trim($pi_manual));
                 //            $rowpos += $lineheight * 3;
             } else {
                 if ($p['pnc']['products_instruction'] != '') {
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', 'B', $fontsize_big);
                     $pdf->Cell(100, $lineheight, 'Production Instruction:');
                     $pdf->setFont('Arial', '');
                     $rowpos += $lineheight;
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->MultiCell(0, $lineheight, $p['pnc']['products_instruction'], 0, 'L');
                     $manpi_rows = explode("\n", $p['pnc']['products_instruction']);
                     //$rowpos += ceil(($lineheight-1)*count($manpi_rows));
                 }
             }
             $rowpos_manpi = $pdf->GetY();
             $rowpos = $rowpos_manpi + 5;
             $leftpos = $colpos + $imgbig_width + 2;
             $rowpos_addimage = 0;
             $nei = 0;
             if (strtoupper($o['type']) == 'JG' && $i['custom_img'] != '') {
                 //$imgcus_width = 37; //150px
                 $imgcus_width = $imgsml_width;
                 //100px
                 $imgcus = $this->getImageForPDF($i['custom_img'], '100', '100');
                 if ($imgcus != '') {
                     $pdf->Image($imgcus, $leftpos, $rowpos, $imgcus_width);
                     $pdf->Rect($leftpos, $rowpos, $imgcus_width, $imgcus_width);
                 }
                 $leftpos += $imgcus_width + 2;
                 //                } elseif((count($p['pei'])>0 && ($p['categories_id']==2||$p['categories_id']==3||$p['categories_id']==30)) || (count($p['pei'])>1 && $p['categories_id']==9)) {
                 //Show Extra Images only for NL,BL,SETS OR CH that have 2 extra images (only show 1st extra_images)
             } elseif (count($p['pei']) > 0) {
                 //                    show extra images for all categories since tends now extra images is used for explain detailly of a product
                 $rowpos = $YPOS + $imgbig_width + 2;
                 $pdf->SetXY($margin, $rowpos);
                 $pdf->setFont('Arial', 'B', $fontsize_big);
                 $pdf->Cell(100, $lineheight, 'Additional Images');
                 $rowpos += $lineheight + 1;
                 foreach ($p['pei'] as $pei) {
                     $nei++;
                     //                        if($p['categories_id']==9 && $nei>1) continue;    //display only 1st extra image for CH
                     $reset_leftpos = true;
                     if ($is_diamore) {
                         //IF DIAMORE PRODUCTS
                         $print_image = false;
                         if (($p['categories_id'] == 2 || $p['categories_id'] == 30) && in_array($nei, array(1, 3))) {
                             $print_image = true;
                         }
                         if ($p['categories_id'] == 4 && in_array($nei, array(2, 3))) {
                             $print_image = true;
                         }
                         if (($p['categories_id'] == 29 || $p['categories_id'] == 3) && in_array($nei, array(1, 2))) {
                             $print_image = true;
                         }
                         if (($p['categories_id'] == 9 || $p['categories_id'] == 28) && in_array($nei, array(1))) {
                             $print_image = true;
                         }
                         if ($print_image) {
                             $leftpos = $colpos;
                             if ($rowpos > 214) {
                                 $pdf->show_footer_page_info = true;
                                 $pdf->AddPage();
                                 $YPOS = $margin + 5;
                                 $rowpos = $YPOS;
                                 $rowpos_manpi = $YPOS;
                             }
                             $imgsml = $this->getImageForPDF($pei, '212', '212');
                             if ($imgsml != '') {
                                 $pdf->Image($imgsml, $leftpos, $rowpos, $imgbig_width);
                                 $pdf->Rect($leftpos, $rowpos, $imgbig_width, $imgbig_width);
                                 $rowpos += $imgbig_width + 2;
                             }
                         }
                     } else {
                         //IF NOT DIAMORE PRODUCTS
                         $check_nei = $nei % 2;
                         if ($check_nei == 1) {
                             if ($nei != 1) {
                                 $reset_leftpos = false;
                                 //print additional image using 2 columns when manual pi is exceeded bottom of main image
                                 if ($nei > 2 && $rowpos_manpi > $rowpos_main_image) {
                                     $rowpos += $imgsml_width + 2;
                                     $reset_leftpos = true;
                                 }
                             }
                         } else {
                             $reset_leftpos = false;
                         }
                         if ($reset_leftpos) {
                             $leftpos = $colpos;
                         } else {
                             $leftpos += $imgsml_width + 2;
                         }
                         $imgsml = $this->getImageForPDF($pei, '100', '100');
                         if ($imgsml != '') {
                             $pdf->Image($imgsml, $leftpos, $rowpos, $imgsml_width);
                             $pdf->Rect($leftpos, $rowpos, $imgsml_width, $imgsml_width);
                             //$rowpos += $imgsml_width + 2;
                         }
                     }
                 }
                 if ($is_diamore) {
                     //IF DIAMORE PRODUCTS
                     $rowpos_addimage = $rowpos + 2;
                 } else {
                     $rowpos_addimage = $rowpos + $imgsml_width + 2;
                     $leftpos += $imgsml_width + 2;
                 }
             }
             //CUSTOMIZE PRODUCTS & PRINTED GIFT VOUCHER FROM JULIE & GRACE
             if (strtoupper($o['type']) == 'JG') {
                 if (strpos($p['p']['products_model'], 'GIFT-P') !== false) {
                     $gift_amount = substr($p['p']['products_model'], 7);
                     $cgq_query = "SELECT c.coupon_code, c.coupon_amount, c.coupon_expire_date FROM coupon_gv_queue cgq";
                     $cgq_query .= " LEFT JOIN coupons c ON c.coupon_id=cgq.coupon_id";
                     $cgq_query .= " WHERE cgq.order_id={$o['id']} AND cgq.amount={$gift_amount}";
                     $cgq_result = tep_db_query($cgq_query);
                     $vouchers = array();
                     while ($row = tep_db_fetch_array($cgq_result)) {
                         $vouchers[] = $row;
                     }
                     $vcounter = 0;
                     foreach ($vouchers as $v) {
                         $vcounter++;
                         $pdf->SetXY($leftpos, $rowpos);
                         $pdf->setFont('Arial', 'B', $fontsize_med);
                         $pdf->Cell(100, $lineheight, 'Voucher ' . $vcounter . ':');
                         $rowpos += $lineheight;
                         $vilbl = array();
                         $vinfo = array();
                         $vilbl[] = '- Code';
                         $vinfo[] = ': ' . $v['coupon_code'];
                         $vilbl[] = '- Amount';
                         $vinfo[] = ': ' . number_format($v['coupon_amount'], 0) . ' EUR';
                         $vilbl[] = '- Expired Date';
                         $vinfo[] = ': ' . date('d. M Y', strtotime($v['coupon_expire_date']));
                         $pdf->setFont('Arial', '', $fontsize_med);
                         $pdf->SetXY($leftpos, $rowpos);
                         $pdf->MultiCell($lbl_width, $lineheight, implode("\n", $vilbl));
                         $pdf->SetXY($leftpos + $lbl_width, $rowpos);
                         $pdf->MultiCell(100, $lineheight, implode("\n", $vinfo));
                         $rowpos += count($vilbl) * $lineheight + 2 * $linesep;
                     }
                 }
                 if ($i['custom_text'] != '') {
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', 'B', $fontsize_big);
                     $pdf->Cell(100, $lineheight, 'Custom Text:');
                     $rowpos += $lineheight;
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', '', 12);
                     $pdf->MultiCell(0, 4, $i['custom_text']);
                     $rowpos += 2 * $lineheight + 2 * $linesep;
                 }
                 if ($i['custom_img'] != '') {
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', 'B', $fontsize_big);
                     $pdf->Cell(100, $lineheight, 'Custom Image:');
                     $rowpos += $lineheight;
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', '', $fontsize_big);
                     $pdf->Cell(0, $lineheight, basename($i['custom_img']));
                     $rowpos += $lineheight + 2 * $linesep;
                 }
                 if ($i['custom_imgcm'] != '') {
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', 'B', $fontsize_big);
                     $pdf->Cell(100, $lineheight, 'Custom Image Comment:');
                     $rowpos += $lineheight;
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', '', $fontsize_big);
                     $pdf->MultiCell(0, $lineheight, basename($i['custom_imgcm']), 0, 'L');
                 }
             } else {
                 if ($p['article']['text'] != '') {
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', 'B', $fontsize_big);
                     $pdf->Cell(100, $lineheight, 'Custom Text:');
                     $rowpos += $lineheight;
                     $pdf->SetXY($leftpos, $rowpos);
                     $pdf->setFont('Arial', '', 12);
                     $pdf->MultiCell(0, 4, $p['article']['text']);
                     $rowpos += 2 * $lineheight + 2 * $linesep;
                 }
             }
             //$YPOS += (($rowpos>($YPOS+$imgbig_width)) ? $rowpos : $imgbig_width) + 10;    //CHANGE THIS TO BELOW
             //if($rowpos>($YPOS+$imgbig_width)) $YPOS = $rowpos + 5;
             //else $YPOS += $imgbig_width + 10;
             if (in_array($p['p']['products_brand_id'], $DIAMOND_BRAND_IDS)) {
                 if ($rowpos_manpi > $rowpos_addimage) {
                     $YPOS = $rowpos_manpi + 5;
                 } elseif ($rowpos_addimage > $rowpos_manpi) {
                     $YPOS = $rowpos_addimage + 15;
                 }
                 //if manual pi printed smaller than displayed additional images
                 if ($rowpos_main_image > $rowpos_manpi && $nei == 0) {
                     $YPOS = $rowpos_main_image + 5;
                 }
                 //if manual pi printed smaller than displayed main images and theres no additional images printed
                 if ($rowpos_manpi == $rowpos_addimage) {
                     $YPOS = $rowpos_manpi;
                 }
                 //if manual pi printed and additional images were the same row height
             } else {
                 if ($rowpos_manpi > $rowpos_addimage) {
                     $YPOS = $rowpos_manpi + 5;
                 } elseif ($rowpos_addimage > $rowpos_manpi) {
                     $YPOS = $rowpos_addimage + 5;
                 }
                 //if manual pi printed smaller than displayed additional images
                 if ($rowpos_main_image > $rowpos_manpi && $nei == 0) {
                     $YPOS = $rowpos_main_image + 5;
                 }
                 //if manual pi printed smaller than displayed main images and theres no additional images printed
                 if ($rowpos_manpi == $rowpos_addimage) {
                     $YPOS = $rowpos_manpi;
                 }
                 //if manual pi printed and additional images were the same row height
             }
             //PRODUCTION
             if ($YPOS > 240) {
                 $pdf->show_footer_page_info = true;
                 $pdf->AddPage();
                 $YPOS = $margin + 5;
             }
             $lineheight = 5;
             $pdf->SetXY($margin, $YPOS);
             $pdf->setFont('Arial', 'B', $fontsize_big);
             $pdf->Cell(100, $lineheight, 'Production');
             $YPOS += $lineheight + 1;
             //IF NEED NEW QC COLUMN, ONLY NEED TO ADD BELOW ARRAY
             $col = array();
             $col[1] = 'Workshop';
             $col[2] = 'Beading';
             $col[3] = 'Enamel';
             $col[4] = 'Ferido';
             $col[5] = 'Packing';
             $leftpos = $margin + 1;
             $pdf->setXY($leftpos, $YPOS);
             $qc_table_max_width = 198;
             $colwidth = number_format($qc_table_max_width / count($col), 1);
             //$colwidth = 39.6;
             foreach ($col as $cval) {
                 $pdf->Cell($colwidth, $lineheight, $cval, 1, 0, 'C', true);
             }
             $YPOS += $lineheight;
             $leftpos = $margin + 1;
             $pdf->setFont('Arial', 'B', $fontsize_big + 5);
             $pdf->SetTextColor(209, 209, 209);
             $pdf->setXY($leftpos, $YPOS);
             for ($x = 1; $x <= count($col); $x++) {
                 $pdf->Cell($colwidth, 15, 'QC', 1, 0, 'C');
             }
             //PRODUCT FINISHING
             //echo "<pre>";var_dump($finishing);die();
             $finishing = array();
             /* UPDATE: NOW WE USE PRODUCTS FINISHING IN PRODUCT ATTRIBUTES TO 
                   FLAG WHETHER THE PRODUCTS NEEDS RHODIUM OR MICRON
                */
             /* RHODIUM RULES
                   Rule1: OttoB2B, Elli Premium which Silver "without plated" and whitegold product
                   Rule2: Diamore
                */
             /*
                             $rhodium_rule1 = ( ($is_ottob2b || $is_elli_premium) 
                    && ($obj_product->metal_stamp_code == Product::METAL_STAMP_CODE_925 
                        || $obj_product->metal_stamp_info == Product::METAL_STAMP_INFO_WHITEGOLD) );
                             $rhodium_rule2 = $is_diamore;
             */
             //$rhodium_and_micron_rule = in_array_r($finishing_product, $product_finishing_array);
             //if ($rhodium_rule1 || $rhodium_rule2) {
             //if ($rhodium_and_micron_rule) {
             //$finishing[] = 'Rhodium';
             //}
             $is_partial_plated = $p['p']['is_partial_plated'] == '1';
             $is_goldplated = false;
             foreach ($p['finishing'] as $ftext => $fval) {
                 if ($fval) {
                     $is_goldplated = $fval == 'Goldplated' || $fval == 'Rose Goldplate';
                     if ($is_partial_plated) {
                         if ($fval == 'Goldplated' || $fval == 'Rose Goldplate') {
                             continue;
                         }
                     }
                     //OttoB2B and Elli Premium goldplated products need to be added with 1.5 micron
                     /*
                     if (($is_ottob2b || $is_elli_premium) 
                             && ($fval == 'Goldplated' || $fval == 'Rose Goldplate')) {
                         $ftext .= ' 1.5 micron';
                     }
                     */
                     $finishing[] = $ftext;
                 }
             }
             if ($is_partial_plated) {
                 //OttoB2B and Elli Premium goldplated products need to be added with 1.5 micron
                 //if (($is_ottob2b || $is_elli_premium)
                 //$finishing_micron_key = array_search('micron', $finishing);
                 //if ($finishing_micron_key !== false
                 //&& ($fval == 'Goldplated' || $fval == 'Rose Goldplate')) {
                 //$finishing[] = 'Partial Plated 1.5 micron';
                 //} else {
                 $finishing[] = 'Partial Plated';
                 //}
             }
             $product_finishing_array = ProductAttribute::getOldStylesFunction()->retrieveList(ProductAttribute::GROUP_ID_PRODUCT_FINISHING);
             $finishing_product = ProductAttribute::displayAttributeName($i['products_id'], ProductAttribute::GROUP_ID_PRODUCT_FINISHING, '2');
             if (!empty($finishing_product)) {
                 $finishing[] = $finishing_product;
             }
             /*
             if ($is_goldplated || $is_partial_plated) {
                 //If using plating, removed finishing Rhodium since it will antitarnished as standard for plated products
                 $finishing_rhodium_key = array_search('Rhodium', $finishing);
                 if ($finishing_rhodium_key !== false) {
                     unset($finishing[$finishing_rhodium_key]);
                 }
             }
             */
             //echo "<pre>";var_dump($finishing);die();
             if (count($finishing) > 0) {
                 if ($YPOS > 250) {
                     $pdf->show_footer_page_info = true;
                     $pdf->AddPage();
                     $YPOS = $margin + 5;
                 }
                 $finishing = implode(', ', $finishing);
                 $pdf->SetTextColor(0, 0, 0);
                 $YPOS += $lineheight + 15;
                 $lineheight = 4;
                 $pdf->SetXY($margin, $YPOS);
                 $pdf->setFont('Arial', 'B', $fontsize_big);
                 $pdf->Cell(100, $lineheight, 'Product Finishing');
                 $YPOS += $lineheight + 1;
                 $lineheight = 15;
                 $colwidth = array();
                 $colwidth[1] = 178;
                 $colwidth[2] = 20;
                 $leftpos = $margin + 1;
                 $pdf->setXY($leftpos, $YPOS);
                 $pdf->setFont('Arial', 'B', $fontsize_big + 5);
                 $pdf->Cell($colwidth[1], $lineheight, $finishing, 1, 2, 'C');
                 $leftpos += $colwidth[1];
                 $pdf->setXY($leftpos, $YPOS);
                 $pdf->SetTextColor(209, 209, 209);
                 $pdf->Cell($colwidth[2], $lineheight, 'QC', 1, 2, 'C');
             }
             $pdf->SetTextColor(0, 0, 0);
             //PRODUCT GOLD WEIGHT CHECK (PGWC)
             if ($is_gold_product) {
                 if ($YPOS > 220) {
                     $pdf->show_footer_page_info = true;
                     $pdf->AddPage();
                     $YPOS = $margin + 5;
                 }
                 $YPOS += $lineheight + 15;
                 $lineheight = 5;
                 $pdf->SetXY($margin, $YPOS);
                 $pdf->setFont('Arial', 'B', $fontsize_big);
                 $pdf->Cell(100, $lineheight, 'Product Gold Weight Check');
                 $YPOS += $lineheight + 1;
                 $gold_weight_check_process = array();
                 $gold_weight_check_process["Safe-WH"] = 'Safe to WH';
                 $gold_weight_check_process["WH-QC"] = 'WH to QC';
                 $gold_weight_check_process["QC-GS"] = 'QC to Goldsmith';
                 $gold_weight_check_process["GS-QC"] = 'Goldsmith to QC';
                 $leftpos = $margin + 1;
                 $pdf->SetXY($leftpos, $YPOS);
                 $gwc_table_max_width = $qc_table_max_width;
                 $n_col_weight_check = 8;
                 $colwidth = number_format($gwc_table_max_width / $n_col_weight_check, 1);
                 foreach ($gold_weight_check_process as $key => $val) {
                     if ($key == "QC-GS" || $key == "GS-QC") {
                         $pdf->Cell($colwidth * 3, $lineheight, $val, 1, 0, 'C', true);
                     } else {
                         $pdf->Cell($colwidth, $lineheight, $val, 1, 0, 'C', true);
                     }
                 }
                 //Draw PGWC Total Weight Box
                 $YPOS += $lineheight;
                 $leftpos = $margin + 1;
                 $pdf->setFont('Arial', 'B', $fontsize_sml);
                 $pdf->SetTextColor(209, 209, 209);
                 $pdf->SetXY($leftpos, $YPOS);
                 $gw_colheight_big = 10;
                 $gw_colheight_sml = number_format($gw_colheight_big / 2, 1);
                 for ($x = 1; $x <= $n_col_weight_check; $x++) {
                     if ($x == 1) {
                         $pdf->Cell($colwidth, $gw_colheight_sml, 'GW:', 1, 2, 'L');
                         $pdf->SetX($leftpos);
                         $pdf->Cell($colwidth, $gw_colheight_sml, 'NW:', 1, 0, 'L');
                     } else {
                         if ($x == 2) {
                             $pdf->SetXY($leftpos + $colwidth, $YPOS);
                         }
                         $box_start = $x == $n_col_weight_check ? 2 : 0;
                         $pdf->Cell($colwidth, $gw_colheight_sml, "Total Weight", 'LR', $box_start, 'C');
                     }
                 }
                 $pdf->SetX($leftpos + $colwidth);
                 for ($x = 2; $x <= $n_col_weight_check; $x++) {
                     $box_start = $x == $n_col_weight_check ? 2 : 0;
                     $pdf->Cell($colwidth, $gw_colheight_sml, '', 'LR', $box_start, 'C');
                 }
                 //Draw PGWC Total Signature Box
                 $colwidth_signature = number_format($colwidth / 2, 1);
                 $pdf->SetX($leftpos);
                 $pdf->SetFontSize($fontsize_med);
                 foreach ($gold_weight_check_process as $key => $val) {
                     if ($key == "QC-GS" || $key == "GS-QC") {
                         $loop = 3;
                     } else {
                         $loop = 1;
                     }
                     list($lsign, $rsign) = explode("-", $key);
                     for ($x = 1; $x <= $loop; $x++) {
                         $pdf->Cell($colwidth_signature, $gw_colheight_big, $lsign, 1, 0, 'C');
                         $pdf->Cell($colwidth_signature, $gw_colheight_big, $rsign, 1, 0, 'C');
                     }
                 }
                 $YPOS += $lineheight - 2 + $gw_colheight_big * 2;
                 $pdf->setFont('Arial', '', $fontsize_sml);
                 $pdf->Text($leftpos, $YPOS, 'GW: Total Weight of Gold Elements');
                 $YPOS += $lineheight - 2;
                 $pdf->Text($leftpos, $YPOS, 'NW: Total Weight of Non-Gold Elements');
                 //Draw PGWC Dust Box
                 if ($YPOS > 250) {
                     $pdf->show_footer_page_info = true;
                     $pdf->AddPage();
                     $YPOS = $margin + 5;
                 }
                 $YPOS += $lineheight;
                 $pdf->SetXY($leftpos, $YPOS);
                 $pdf->setFont('Arial', 'B', $fontsize_big);
                 $pdf->SetTextColor(0, 0, 0);
                 $pdf->Cell($colwidth, $lineheight, 'Dust', 1, 2, 'C', true);
                 $pdf->SetFontSize($fontsize_sml);
                 $pdf->SetTextColor(209, 209, 209);
                 $pdf->Cell($colwidth, $gw_colheight_sml, 'Total Weight', 'LR', 2, 'C');
                 $pdf->Cell($colwidth, $gw_colheight_sml, '', 'LR', 2, 'C');
                 $pdf->Cell($colwidth_signature, $gw_colheight_big, 'QC', 1, 0, 'C');
                 $pdf->Cell($colwidth_signature, $gw_colheight_big, 'GS', 1, 0, 'C');
             }
             $pdf->SetTextColor(0, 0, 0);
             //ENGRAVING ORDER SLIP
             global $ENGRAVED_PRODUCTS;
             if (strtoupper($o['type']) == 'JG' && in_array($i['products_id'], $ENGRAVED_PRODUCTS)) {
                 if ($this->duplex_printing && $item_page_count % 2 != 0) {
                     $pdf->AddPage();
                     $item_page_count++;
                 }
                 $pdf->AddPage();
                 $item_page_count++;
                 $lineheight = 4;
                 $midpage = 148.5;
                 $rowpos = $margin + 10;
                 //repeat 2 times
                 for ($s = 1; $s <= 2; $s++) {
                     if ($s == 2) {
                         $rowpos = $midpage + 10;
                         $slipinfo = 'Face2Face';
                     } else {
                         $slipinfo = 'Bonofactum';
                     }
                     $colpos = $margin + 1;
                     $pdf->OrderBarcode($o['type'], $oiid, $barcode_pos, $rowpos, $barcode_width);
                     $pdf->SetXY($margin, $rowpos);
                     $pdf->setFont('Arial', 'B', '12');
                     $pdf->Cell(100, $lineheight, 'Engraving Order Slip (' . $slipinfo . ')');
                     $rowpos += $lineheight + 5;
                     $rowpos_fixed = $rowpos;
                     if ($imgbig != '') {
                         $pdf->Image($imgbig, $colpos, $rowpos, $imgbig_width);
                     }
                     $pdf->Rect($colpos, $rowpos, $imgbig_width, $imgbig_width);
                     $colpos += $imgbig_width + 5;
                     $es_ilbl_width = 30;
                     $es_ilbl = array();
                     $es_info = array();
                     $es_ilbl[] = 'Order By';
                     $es_info[] = ': Bonofactum';
                     $es_ilbl[] = 'Order Date';
                     $es_info[] = ': ' . date('d. M Y');
                     $es_ilbl[] = 'Order Quantity';
                     $es_info[] = ': ' . $product_qty;
                     $pdf->setFont('Arial', 'B', $fontsize_med);
                     $pdf->SetXY($colpos, $rowpos);
                     $pdf->MultiCell($es_ilbl_width, $lineheight, implode("\n", $es_ilbl));
                     $pdf->SetXY($colpos + $es_ilbl_width, $rowpos);
                     $pdf->MultiCell($es_ilbl_width * 2, $lineheight, implode("\n", $es_info));
                     $rowpos += (count($es_ilbl) + 1) * $lineheight + 1;
                     $pdf->SetXY($colpos, $rowpos);
                     $pdf->Cell(100, $lineheight, 'Custom Text');
                     $rowpos += $lineheight + 1;
                     $pdf->SetDrawColor(128, 128, 128);
                     $pdf->Rect($colpos + 1, $rowpos, 132, 30);
                     $pdf->SetDrawColor(0, 0, 0);
                     if ($i['custom_text'] != '') {
                         $pdf->SetXY($colpos + 3, $rowpos + 3);
                         $pdf->setFont('Arial', 'B', '12');
                         $pdf->MultiCell(100, $lineheight, $i['custom_text']);
                     }
                     $rowpos = $rowpos_fixed + $imgbig_width + 5;
                     if ($i['custom_img'] != '') {
                         $leftpos = $margin + 1;
                         if ($imgcus != '') {
                             $pdf->Image($imgcus, $leftpos, $rowpos, $imgcus_width);
                             $pdf->Rect($leftpos, $rowpos, $imgcus_width, $imgcus_width);
                         }
                         $leftpos += $imgcus_width + 2;
                         $pdf->setXY($leftpos, $rowpos);
                         $pdf->setFont('Arial', 'B', $fontsize_med);
                         $pdf->Cell(100, $lineheight, 'Custom Image:');
                         $rowpos += $lineheight;
                         $pdf->setXY($leftpos, $rowpos);
                         $pdf->setFont('Arial', '', $fontsize_med);
                         $pdf->Cell(100, $lineheight, basename($i['custom_img']));
                         $rowpos += $lineheight + 1;
                         $pdf->setXY($leftpos, $rowpos);
                         $pdf->setFont('Arial', 'B', $fontsize_med);
                         $pdf->Cell(100, $lineheight, 'Graving Request:');
                         $rowpos += $lineheight;
                         $engraving_options_pos = $leftpos + $lineheight + 1;
                         $engraving_options = array();
                         $engraving_options[] = 'Full (gravir penuh)';
                         $engraving_options[] = 'Centered (gravir tengah, atas dan bawah kosong)';
                         $engraving_options[] = 'Bottom (gravir bawah penuh, atas kosong)';
                         $pdf->setXY($engraving_options_pos, $rowpos);
                         $pdf->setFont('Arial', '', $fontsize_med);
                         $pdf->MultiCell(100, $lineheight, implode("\n", $engraving_options));
                         $cb_sep = 0.5;
                         $cbsize = $lineheight - $cb_sep;
                         $leftpos += 1;
                         $pdf->SetDrawColor(128, 128, 128);
                         foreach ($engraving_options as $eo) {
                             $pdf->Rect($leftpos, $rowpos, $cbsize, $cbsize);
                             $rowpos += $lineheight;
                         }
                         $pdf->SetDrawColor(0, 0, 0);
                     }
                 }
                 $pdf->Line($margin, $midpage, 210 - $margin, $midpage);
             }
             if ($i['print_count'] == '0' || $i['print_count'] == '') {
                 $this->qty_total_first_printed++;
             }
         }
         //end looping items
     }
     //end looping orders
     if ($output == 'F') {
         $filename = $this->filename != '' ? $this->filename : DIR_FS_MINIERP . DIR_WS_GATEWAY . "ready_orders/" . strtoupper($o['type']) . '/' . strtoupper($o['type']) . '-' . $oiid;
         //            $priority_rule_1 = in_array($o['jng_sp_id'], $sp_using_red_paper);
         //            $priority_rule_2 = $o['customer_is_vip'];
         $priority_rule_1 = $o['priority'] == '1';
         //            if($priority_rule_1 || $priority_rule_2 || $priority_rule_3) $filename .= '-RED';
         if ($priority_rule_1 && $this->filename == '') {
             $filename .= '-RED';
         }
         $pdf->Output($filename . '.pdf', $output);
     }
 }
function getComplexity($complexity = null)
{
    //$complexities = array('E'=>'Easy', 'M'=>'Medium', 'H'=>'Hard', 'X'=>'Extreme');
    $complexities = productComplexityName();
    $result = $complexities;
    if (!is_null($complexity)) {
        $result = $complexities[$complexity];
    }
    return $result;
}
     $products_id = tep_db_prepare_input($_GET['products_id']);
     if ($update == 'add') {
         $class_mu->addToWatchlist($session_userinfo['id'], $products_id);
     } else {
         $class_mu->removeFromWatchlist($session_userinfo['id'], $products_id);
     }
     $result = array();
     $result['pid'] = $products_id;
     $result['update'] = $update;
     ajaxReturn($result);
     exit;
 } elseif ($_POST['me_action'] == 'UPDATECOMPLEXITY') {
     $products_id = tep_db_prepare_input($_GET['products_id']);
     $complexity = tep_db_prepare_input($_POST['complexity']);
     $class_pm->updateComplexity($products_id, $complexity);
     echo utf8_encode(productComplexityName($complexity));
     exit;
 } elseif ($_POST['me_action'] == 'UPDATEPRODUCTINFO') {
     //UPDATE PRODUCT DETAIL
     $products_id = tep_db_prepare_input($_POST['products_id']);
     //Update Table products
     $sql_data_array = array();
     $sql_data_array['active_status'] = tep_db_prepare_input($_POST['active_status']);
     $sql_data_array['products_status'] = tep_db_prepare_input($_POST['products_status']);
     //	$sql_data_array['products_date_added']		  = tep_db_prepare_input($_POST['products_date_added']).' '.tep_db_prepare_input($_POST['products_date_added_time']);
     //	$sql_data_array['products_last_modified']	  = tep_db_prepare_input($_POST['products_last_modified']).' '.tep_db_prepare_input($_POST['products_last_modified_time']);
     $sql_data_array['products_last_modified'] = date('Y-m-d H:i:s');
     if (isset($_POST['products_weight'])) {
         $sql_data_array['products_weight'] = tep_db_prepare_input($_POST['products_weight']);
     }
     /*
 $res = $res[0];
 $products_image = webImageWithDetailLink($res['products_image'], IMAGE_SIZE_THUMBNAIL_1, IMAGE_SIZE_THUMBNAIL_1, 'Product ' . $pids[0], 'img-border');
 $products_price_old = displayCurrency('', $res['products_price_old']);
 $products_price = displayCurrency('', $res['products_price']);
 $discount = number_format($res['products_discount'], 2);
 $products_created = date('d-M-Y', strtotime($res['products_date_added']));
 $returned_rate = number_format($res['returned_rate'], 2);
 $total_sales = number_format($res['total_sales'], 2);
 $vc_now = number_format($res['vc_now'], 2);
 $total_vc = number_format($res['total_vc'], 2);
 $vc_percent = number_format($res['vc_percent'], 2);
 $margin = $res['margin'];
 $margin = '<span class="' . ($class_pm->priceMargindIsGood($res['products_price'], $margin) ? 'green' : 'red') . '">' . number_format($margin, 1) . '%</span>';
 $sales_monthly = number_format($res['sales_monthly'], 1);
 $sales_weekly = number_format($res['sales_weekly'], 1);
 $products_complexity = productComplexityName($res['complexity']);
 $products_stars = $class_pm->getDisplayStars('', $res['stars']);
 $t = array();
 $t['no'] = '<div>' . $n . '</div>';
 $t['image'] = '<div>' . $products_image . '</div>';
 $t['info'] = '<div><a href="?open=product-detail&products_id=' . $res['products_id'] . '" target="_blank">';
 $t['info'] .= $res['products_id'] . ' / ' . $res['products_model'] . '</a><br/>' . $res['products_name'] . '<br/>' . $products_stars . '<br/><br/>&raquo;&nbsp;';
 $hh_stock = $res['hh_stock'] > 0 ? $res['hh_stock'] : '0';
 $t['info'] .= '<strong class="' . ($res['hh_stock'] > 0 ? 'green' : '') . '">Depot HH Stock = ' . $hh_stock . '</strong>';
 $t['info'] .= '<br/>&raquo;&nbsp;Complexity = ' . $products_complexity . '</div>';
 $t['created'] = '<div>' . $products_created . '</div>';
 $t['priceold'] = '<div>' . $products_price_old . '</div>';
 $t['price'] = '<div>' . $products_price . '</div>';
 $t['disc'] = "<div>{$discount}%</div>";
 $t['vc'] = '<div>' . $vc_now . '</div>';
 $t['vcpct'] = "<div>{$vc_percent}%</div>";
function loadProductRow($pid, $pos, $curgroup_id)
{
    global $class_s, $header, $maxnav;
    use_class('products_minierp');
    $class_pm = new products_minierp();
    $product = $class_pm->retrieveDetail($pid, 'p,pl,sp');
    $cols = array();
    foreach ($header as $hk => $hv) {
        $value = '';
        switch ($hk) {
            case 'img':
                $value .= webImageAddPosition($pos, webImageWithDetailLink($product['p']['products_image'], IMAGE_SIZE_THUMBNAIL_2, IMAGE_SIZE_THUMBNAIL_2, "Product {$pid}"));
                break;
            case 'name':
                $value .= $pid . ' / ' . $product['p']['products_model'];
                $value .= '<br />' . $product['pd']['2']['products_name'];
                $value .= '<br />' . $class_pm->getDisplayStars('', $product['p']['stars']);
                $value .= '<br /><br />&raquo; Complexity = ' . productComplexityName($product['p']['complexity']);
                break;
            case 'age':
                $value .= $product['sp']['0']['active_age'] . '<br />days';
                break;
            case 'ts1':
                $value .= $product['sp']['0']['total_sold'];
                break;
            case 'ts2':
                $value .= displayCurrency('EUR', $product['sp']['0']['total_sales'], false);
                break;
            case 'ps':
                $value .= 'L30D=' . intval($product['pl']['sold_monthly_1']);
                $value .= '<br />L60D=' . intval($product['pl']['sold_monthly_2']);
                $value .= '<br />L90D=' . intval($product['pl']['sold_monthly_3']);
                break;
            case 'pspw':
                $value .= round($product['sp']['0']['sales_weekly'], 1);
                break;
            case 'pspm':
                $value .= round($product['sp']['0']['sales_monthly'], 1);
                break;
            case 'pb':
                use_class('products_brand');
                $value .= $product['p']['products_brand_name'];
                break;
            case 'cur':
                $attrs = $class_s->getProductStyles($pid);
                if (count($attrs[$curgroup_id]) > 0) {
                    foreach ($attrs[$curgroup_id] as $attr_id => $attr) {
                        $value .= drawAttribute($pid, $attr_id, $attr);
                    }
                }
                break;
            case 'act':
                $combo = array();
                for ($x = 1; $x <= $maxnav; $x++) {
                    $combo[] = '<select name="cmb-onebyone" class="input"></select>';
                }
                $value .= implode('<br />', $combo);
                $value .= '<br /><input type="button" class="input" name="save" value="Save" />';
        }
        if ($value == '') {
            $value = '&nbsp;';
        }
        $cols[$hk] = $value;
    }
    $productrow = '<tr id="temp-' . $pid . '">';
    foreach ($cols as $ck => $cv) {
        $productrow .= '<td class="' . $ck . '">' . $cv . '</td>';
    }
    $productrow .= '</tr>';
    return $productrow;
}
 /**
  * Build input for $filters
  * @return string
  */
 private function createFiltersInput()
 {
     // >,>=,=,<=,<
     $input .= $this->createInputTextRange('filters-prod-id', 'products id', '', '', '', '', true);
     $input .= $this->createInputTextRange('filters-prod-price', 'price', '', '', ' ' . DEFAULT_CURRENCY, 'currency');
     $input .= $this->createInputTextRange('filters-prod-age', 'days');
     $input .= $this->createInputTextRange('filters-prod-disc', 'discount % ', 3, '', '%');
     $input .= $this->createInputTextRange('filters-prod-vc', 'vc ');
     $input .= $this->createInputTextRange('filters-prod-vcpct', 'vc % ', '', '', '%');
     $input .= $this->createInputTextRange('filters-prod-margin', 'margin % ', '', '', '%');
     $input .= $this->createInputTextRange('filters-prod-soldlast30', 'pieces', '', '', ' pieces');
     $input .= $this->createInputTextRange('filters-prod-soldlast60', 'pieces', '', '', ' pieces');
     $input .= $this->createInputTextRange('filters-prod-soldlast90', 'pieces', '', '', ' pieces');
     for ($y = product::STATIC_LOG_YEAR_START; $y <= date('Y'); $y++) {
         $input .= $this->createInputTextRange('filters-prod-sold' . $y, 'pieces', '', '', ' pieces');
     }
     $input .= $this->createInputTextRange('filters-prod-totalsold', 'pieces', '', '', ' pieces');
     $input .= $this->createInputTextRange('filters-prod-stars', 'stars', '', '', ' stars');
     $input .= $this->createInputTextRange('filters-prod-matexp', 'amount on EUR', '', '', ' EUR');
     $input .= $this->createInputTextRange('filters-hh-stock', 'pieces', '', '', ' pieces');
     $input .= $this->createInputTextRange('filters-prod-deflength', 'default length');
     $input .= $this->createInputTextRange('filters-prod-returnrate', 'return %');
     $input .= $this->createInputTextRange('filters-pd2-ttlstones', 'pieces', '', '', ' pieces');
     $input .= $this->createInputTextRangeDate('filters-date-killed');
     $input .= $this->createInputTextRangeDate('filters-date-keep');
     $input .= $this->createInputTextRangeDate('filters-date-keep-exclude');
     $input .= $this->createInputTextRangeDate('filters-date-finalized');
     // =, != with input free text
     $input .= $this->createInputTextEqualOrNot('filters-el-used', 'elements id', '', '', '', true);
     $input .= $this->createInputTextEqualOrNot('filters-prod-ean', 'product ean', '', '', '', true);
     $input .= $this->createInputTextEqualOrNot('filters-prod-model', 'products model', '', '', '', true);
     // like %input%, not like %input%
     $input .= $this->createInputTextContainOrNot('filters-prod-name', 'name');
     $input .= $this->createInputTextContainOrNot('filters-prod-description', 'description');
     $input .= $this->createInputTextContainOrNot('filters-prod-promoname', 'promoname');
     // =, != with input drop down combo
     //prepare data combo
     $combo_element_finishing = $this->createCombo('filters-el-finishing', 'status', array('1' => 'Yellow Goldplate', '11' => 'Hammer', '111' => 'Brush', '1111' => 'Oxid', '11111' => 'Rose Goldplate'), null, null);
     $combo_prod_clearimage = $this->createCombo('filters-prod-clearimage', 'status', array('0' => 'Has NO Clear Image', '1' => 'Has a Clear Image'), null, null);
     $combo_prod_complexity = $this->createCombo('filters-prod-complexity', 'status', productComplexityName(), null, null);
     $combo_prod_content = $this->createCombo('filters-prod-content', 'status', array('0' => 'NOT Improved', '1' => 'Improved'), null, null);
     $combo_prod_discounted = $this->createCombo('filters-prod-discounted', 'status', array('0' => 'No', '1' => 'Yes'), null, null);
     $combo_prod_family = $this->createCombo('filters-prod-family', 'status', array('0' => 'Has NO Family', '1' => 'Has a Family'), null, null);
     $combo_prod_image = $this->createCombo('filters-prod-image', 'status', array('0' => 'NOT Improved', '1' => 'Improved'), null, null);
     $combo_prod_margin_status = $this->createCombo('filters-prod-margin-status', 'status', array('0' => 'Bad', '1' => 'Good'), null, null);
     $combo_prod_outsourced = $this->createCombo('filters-prod-outsourced', 'status', array('0' => 'No (Produce in House)', '1' => 'Yes (Outsourced)'), null, null);
     $combo_prod_wholesale = $this->createCombo('filters-prod-wholesale', 'status', array('0' => 'No', '1' => 'Yes'), null, null);
     //prepare input filters
     // =
     $input .= $this->createInputComboEqual('filters-prod-clearimage', '', '', '', '', null, '', '', false, $combo_prod_clearimage);
     $input .= $this->createInputComboEqual('filters-prod-content', '', '', '', '', null, '', '', false, $combo_prod_content);
     $input .= $this->createInputComboEqual('filters-prod-discounted', '', '', '', '', null, '', '', false, $combo_prod_discounted);
     $input .= $this->createInputComboEqual('filters-prod-family', '', '', '', '', null, '', '', true, $combo_prod_family);
     $input .= $this->createInputComboEqual('filters-prod-image', '', '', '', '', null, '', '', false, $combo_prod_image);
     $input .= $this->createInputComboEqual('filters-prod-outsourced', '', '', '', '', null, '', '', false, $combo_prod_outsourced);
     $input .= $this->createInputComboEqual('filters-prod-wholesale', '', '', '', '', null, '', '', false, $combo_prod_wholesale);
     // =, !=
     $input .= $this->createInputComboEqualOrNot('filters-el-finishing', 'finishing', '', '', '', null, '', '', false, $combo_element_finishing);
     $input .= $this->createInputComboEqualOrNot('filters-prod-brand', '', '', '', '', null, '', '', true, comboProductsBrand('filters-prod-brand', '', '', 'filters-val', 'style="display:none;margin-left:20px;"'));
     $input .= $this->createInputComboEqualOrNot('filters-prod-cat-top', '', '', '', '', null, '', '', true, CategoryTop::displayAsComboBox('filters-prod-cat-top', '', '', 'filters-val', 'display:none;margin-left:20px;'));
     $input .= $this->createInputComboEqualOrNot('filters-prod-cat', '', '', '', '', null, '', '', true, comboProductsCategory('filters-prod-cat', '', '', 'filters-val', 'style="display:none;margin-left:20px;"'));
     $input .= $this->createInputComboEqualOrNot('filters-prod-description-imp-stat', '', '', '', '', null, '', '', true, comboProductsDescriptionImprovedStatus('filters-prod-description-imp-stat', '', '', 'filters-val', 'style="display:none;margin-left:20px;"'));
     $input .= $this->createInputComboEqualOrNot('filters-prod-color', 'color', 'color_pattern_description', 'color_pattern_id', 'name', null, "languages_id = '1'", '', true);
     $input .= $this->createInputComboEqualOrNot('filters-prod-complexity', '', '', '', '', null, '', '', true, $combo_prod_complexity);
     $input .= $this->createInputComboEqualOrNot('filters-prod-margin-status', 'status', '', '', '', null, '', '', false, $combo_prod_margin_status);
     $input .= $this->createInputComboEqualOrNot('filters-prod-mat', 'material', 'products_materials', 'products_materials_id', 'material_name', null, '', '', true);
     $input .= $this->createInputComboEqualOrNot('filters-watchlist-of', '', '', '', '', null, '', '', true, comboWatchlistUsers('filters-watchlist-of', '', '', 'filters-val', 'style="display:none;margin-left:20px;"'));
     foreach ($this->class_styles->groups as $gk => $gv) {
         $input .= $this->createInputComboEqualOrNot("filters-prod-styles-{$gk}", 'attribute', 'styles s LEFT JOIN styles_description sd ON sd.styles_id=s.styles_id AND sd.languages_id=2', 's.styles_id', 'sd.name', null, "groups='{$gk}'", '', true);
     }
     return $input;
 }
 function templateElementsUsed($submit_action = '')
 {
     $products_id = isset($_POST['products_id']) ? $_POST['products_id'] : tep_db_prepare_input($_GET['products_id']);
     $act = isset($_POST['act']) ? $_POST['act'] : tep_db_prepare_input($_GET['act']);
     switch ($act) {
         case 'UPDATE_MATEXP_MANUAL':
             $matexp = tep_db_prepare_input($_POST['new_matexp']);
             $p = new Product($products_id);
             $p->updateMaterialExpense($matexp);
             $result = $matexp;
             break;
         case 'LOAD':
             $product = $this->retrieveDetail($products_id, 'p,pnc,pc');
             $p = $product['p'];
             $pc = $product['pc'];
             $pnc = $product['pnc'];
             $result = '';
             //ELEMENTS USED
             if ($pc !== false) {
                 //For Customized Products:
                 //CHECK FOR IMAGES OF CUSTOMIZED ELEMENTS
                 $pe_image = array();
                 $pci_query = "SELECT phe.elements_id, pci.*";
                 $pci_query .= " FROM products_has_elements phe";
                 $pci_query .= " INNER JOIN phe_custom_image pci ON pci.products_has_elements_id=phe.products_has_elements_id";
                 $pci_query .= " WHERE phe.products_id={$products_id}";
                 $pci_query .= " ORDER BY orientation ASC, position ASC";
                 $pci_result = tep_db_query($pci_query);
                 if (tep_db_num_rows($pci_result) > 0) {
                     while ($row = tep_db_fetch_array($pci_result)) {
                         if (!isset($pe_image[$row['elements_id']])) {
                             $pe_image[$row['elements_id']] = array();
                         }
                         $pe_image[$row['elements_id']][] = '<a href="?open=pe-uploaded-image&amp;id=' . $row['elements_custom_image_uploaded_id'] . '&amp;hidemenu=true" class="view_webpage" title="View uploaded image and comment">Image</a>';
                     }
                 }
                 //CHECK FOR TEXT OF CUSTOMIZED ELEMENTS
                 $pe_text = array();
                 $pct_query = "SELECT phe.elements_id, pct.*";
                 $pct_query .= " FROM products_has_elements phe";
                 $pct_query .= " INNER JOIN phe_custom_text pct ON pct.products_has_elements_id=phe.products_has_elements_id";
                 $pct_query .= " WHERE phe.products_id={$products_id}";
                 $pct_query .= " ORDER BY orientation ASC, position ASC";
                 $pct_result = tep_db_query($pct_query);
                 if (tep_db_num_rows($pct_result) > 0) {
                     $fulltext = array();
                     while ($textrow = tep_db_fetch_array($pct_result)) {
                         if (!isset($fulltext[$textrow['elements_id']])) {
                             $fulltext[$textrow['elements_id']] = array();
                         }
                         $fulltext[$textrow['elements_id']][] = $textrow['entry_text'];
                     }
                     foreach ($fulltext as $elements_id => $elements_text) {
                         $elements_fulltext = implode('\\n', $elements_text);
                         $pe_text[$elements_id] = '<a href="javascript:alert(\'' . $elements_fulltext . '\')">Text</a>';
                     }
                 }
                 //QUERY ELEMENTS
                 $phe_query = "SELECT phe.elements_id, COUNT(phe.elements_id) AS quantity, e.elements_code";
                 $phe_query .= ", ed.name, ei.image_path, ei.image_filename, (etes.elements_price/etes.pieces_per_qty_type) AS price, etes.price_currency";
                 $phe_query .= " FROM products_has_elements phe";
                 $phe_query .= " LEFT JOIN elements e ON e.elements_id=phe.elements_id";
                 $phe_query .= " LEFT JOIN elements_description ed ON ed.elements_id=e.elements_id AND ed.languages_id=1";
                 $phe_query .= " LEFT JOIN elements_images ei ON ei.elements_id=phe.elements_id AND elements_sample_name='EC1'";
                 $phe_query .= " LEFT JOIN elements_to_elements_suppliers etes ON etes.elements_id=phe.elements_id AND etes.is_default='1'";
                 $phe_query .= " WHERE phe.products_id={$products_id}";
                 $phe_query .= " GROUP BY phe.elements_id";
                 $phe_result = tep_db_query($phe_query);
                 if (tep_db_num_rows($phe_result) > 0) {
                     $result .= '<div class="draw-table">';
                     $result .= '<table class="el-used" border="0" cellpadding="0" cellspacing="0">';
                     //Header
                     $result .= '<tr><th>Image</th><th>ID</th>';
                     //$result .= '<th>Code</th>';
                     $result .= '<th>Info</th><th>Qty</th><th>Unit</th><th><abbr title="Material Expenses">Mat.Exp.</abbr></th></tr>';
                     $counter = 0;
                     while ($phe = tep_db_fetch_array($phe_result)) {
                         if ($phe['elements_code'] != '07-0001BS') {
                             $counter++;
                             $rowclass = $counter % 2 == 0 ? 'e' : 'o';
                             $qty_type = 'piece';
                             if ($phe['quantity'] > 1 && $qty_type == 'piece') {
                                 $qty_type .= 's';
                             }
                             $el_img = 'elements/' . $phe['image_path'] . $phe['image_filename'];
                             $el_img_src = webImageSource($el_img);
                             $el_img_link = '<a href="' . $el_img_src . '" class="view_image" title="Element ID ' . $phe['elements_id'] . '">';
                             $result .= '<tr class="' . $rowclass . '">';
                             $result .= '<td>' . $el_img_link . webImage($el_img, '80', '80') . '</a></td>';
                             $result .= '<td><strong>' . $phe['elements_id'] . '</strong></td>';
                             //$result .= '<td><strong>'.$phe['elements_code'].'</strong></td>';
                             $result .= '<td style="width:300px;text-align:left;">';
                             $result .= $phe['name'];
                             if (isset($pe_image[$phe['elements_id']]) || isset($pe_text[$phe['elements_id']])) {
                                 $result .= '<br /><br /><span class="red">Personized Elements:</span><br />';
                                 if (isset($pe_image[$phe['elements_id']])) {
                                     $result .= implode(' &bull; ', $pe_image[$phe['elements_id']]);
                                 }
                                 if (isset($pe_text[$phe['elements_id']])) {
                                     $result .= $pe_text[$phe['elements_id']];
                                 }
                             }
                             $result .= '</td>';
                             $result .= '<td>' . $phe['quantity'] . '</td>';
                             $result .= '<td>' . $qty_type . '</td>';
                             $result .= '<td style="text-align:right;"><a href="?open=elements-suppliers&id=' . $phe['elements_id'] . '&hidemenu=true" class="view_webpage" title="View elements suppliers detail">';
                             $matexp = calculateCurrency($phe['quantity'] * $phe['price'], $phe['price_currency']);
                             $result .= displayCurrency('EUR', $matexp);
                             $result .= '</a></td>';
                             $result .= '</tr>';
                         }
                     }
                     $result .= '</table>';
                     $result .= '</div>';
                 }
             } else {
                 //ELEMENTS USED
                 //For standard Products:
                 $result .= '<div id="add_el_used_form" style="display:none;">';
                 $submit_action = $submit_action == '' ? '?open=product-detail&amp;products_id=' . $products_id . '#prodet-tab2' : $submit_action;
                 $result .= '<form name="elements_used_add" action="' . $submit_action . '" method="post">';
                 $result .= '<input type="hidden" name="me_action" value="ELEMENTSUSEDADD" />';
                 $result .= '<input type="hidden" name="products_id" value="' . $products_id . '" />';
                 $result .= '<div class="form"><table border="0" cellpadding="0" cellspacing="0">';
                 $result .= '<tr><td class="label">Element ID/Code</td><td><input type="text" name="add_id" value="" /></td>';
                 $result .= '<tr><td>Element Qty</td><td><input type="text" name="add_qty" value="1" onfocus="$(this).select();" /></td>';
                 $result .= '</table></div>';
                 $result .= '<div class="buttons"><input type="submit" name="submit" value="Add Element" /></div>';
                 $result .= '</form>';
                 $result .= '</div>';
                 //OVERRIDE FORMS
                 $result .= '<div id="ovr_el_used_form" style="display:none;">';
                 $result .= '<form name="elements_used_add" action="' . $submit_action . '" method="post">';
                 $result .= '<input type="hidden" name="me_action" value="ELEMENTSUSEDOVR" />';
                 $result .= '<input type="hidden" id="pid" name="products_id" value="' . $products_id . '" />';
                 $result .= '<input type="hidden" id="ovr_pean" name="ovr_pean" value=""/>';
                 $result .= '<input type="hidden" id="ovr_paid" name="ovr_paid" value=""/>';
                 $result .= '<input type="hidden" id="ovr_pueid" name="ovr_pueid" value=""/>';
                 $result .= '<input type="hidden" id="ovr_elid_def" name="ovr_elid_def" value=""/>';
                 $result .= '<input type="hidden" id="ovr_qty_def" name="ovr_qty_def" value=""/>';
                 $result .= '<input type="hidden" id="ovr_elid_old" name="ovr_elid_old" value=""/>';
                 $result .= '<input type="hidden" id="ovr_qty_old" name="ovr_qty_old" value=""/>';
                 $result .= '<input type="hidden" id="type" name="ovr_type" value=""/>';
                 $result .= '<div class="form"><table border="0" cellpadding="0" cellspacing="0">';
                 $result .= '<tr><td class="label">Element ID/Code</td><td><input type="text" id="ovr_id" name="ovr_id" value="" onfocus="$(this).select();" /></td>';
                 $result .= '<tr><td>Element Qty</td><td><input type="text" id="ovr_qty" name="ovr_qty" value="1" onfocus="$(this).select();" /></td>';
                 $result .= '</table></div>';
                 $result .= '<div class="buttons"><input type="button" class="submit" value="Override Element" /></div>';
                 $result .= '</form>';
                 $result .= '</div>';
                 //QUESTION FORMS
                 $result .= '<div id="confirm_form" style="display:none;">';
                 $result .= '<div class="form"><table border="0" cellpadding="0" cellspacing="0">';
                 $result .= '<tr><td>There element ID overridden on Additional Lengths, do you want to also replace with element <span id="el_id" class="bold"></span>?</td></tr>';
                 $result .= '</table></div>';
                 $result .= '<div class="buttons"><button name="act_yes" id="act_yes">Yes</button><button name="act_no" id="act_no">No</button></div>';
                 $result .= '</div>';
                 $form_width = 845;
                 $result .= '<form name="elements_used_update" action="' . $submit_action . '" method="post">';
                 $result .= '<input type="hidden" name="me_action" value="ELEMENTSUSEDUPDATE" />';
                 $result .= '<input type="hidden" name="products_id" value="' . $products_id . '" />';
                 if ($elements_use_msg != '') {
                     $result .= '<div style="margin:10px 0px;font-weight:bold;" class="red">' . $elements_use_msg . '</div>';
                 }
                 $pue_query = "SELECT pue.*, e.elements_code, e.elements_name, e.elements_image, e.elements_price, e.stars, e.elements_description";
                 $pue_query .= " FROM products_use_elements pue";
                 $pue_query .= " LEFT JOIN element e ON e.elements_id=pue.elements_id";
                 //$pue_query .= " LEFT JOIN `products_non_configurator` pnc ON pue.`products_id` = pnc.`products_id`";
                 //$pue_query .= " LEFT JOIN elements e ON e.elements_id=pue.elements_id";
                 //$pue_query .= " LEFT JOIN elements_description ed ON ed.elements_id=e.elements_id AND ed.languages_id=1";
                 //$pue_query .= " LEFT JOIN elements_images ei ON ei.elements_id=pue.elements_id AND elements_sample_name='EC1'";
                 //$pue_query .= " LEFT JOIN elements_to_elements_suppliers etes ON etes.elements_id=pue.elements_id AND etes.is_default='1'";
                 $pue_query .= " WHERE pue.products_id={$products_id}";
                 $pue_query .= " GROUP BY pue.elements_id";
                 $pue_result = tep_db_query($pue_query);
                 $products_length = $pnc['products_length'];
                 $form_footer = '<div class="pro-button" style="width:' . ($form_width + 5) . 'px;">';
                 $form_footer .= '<a href="?open=products-add-elements&amp;pid=' . $products_id . '&amp;hidemenu=true" class="view_webpage"></a>';
                 $form_footer .= '<input type="button" id="add_el_used" value="Add Element" />';
                 $form_footer .= '<input type="submit" name="submit" value="Save Changes" {BTNUPDDIS} />';
                 $form_footer .= '</div>';
                 $form_footer .= '</form>';
                 if (tep_db_num_rows($pue_result) == 0) {
                     //No Elements attached to product
                     $dis = SERVER_IS_LOCAL ? ' disabled="disabled"' : '';
                     $dis_note = SERVER_IS_LOCAL ? '<br /><span class="smallText notice">* can only' . ' be updated in Manobo Central!</span>' : '';
                     $result .= '<div class="box w500" style="margin-bottom:20px;">' . 'Material Expense (set manually in ' . CURRENCY_CODE_EURO . '): &nbsp; <input type="text"' . ' id="p-matexp-manual" class="w080 tar" value="' . $p['material_expenses'] . '"' . $dis . ' />' . $dis_note . '</div>';
                     $result .= '<h3 class="red bold">No Element is attached to this product</h3>';
                     $result .= str_replace('{BTNUPDDIS}', 'disabled="disabled"', $form_footer);
                 } else {
                     $complexity_manual = array_keys(productComplexityName(null, 2));
                     $title_complexity = 'This complexity sets ';
                     $title_complexity .= '<strong>' . (in_array($p['complexity'], $complexity_manual) ? 'manually by user' : 'automatically by manobo') . '</strong>';
                     $title_complexity .= ', if you need to change this,<br/>please do as explained below:<ol><li>Click on complexity</li><li>Select new complexity from displayed list</li></ol>Done, should be complexity will updated to the new values';
                     $complexity = drawIconInfo($title_complexity, true, 'float-left', 'margin-right:5px;') . '<span id="elused-complexity" class="pointer" title="Click to set complexity manually">' . productComplexityName($p['complexity']) . '</span><select id="elused-complexity-manual" style="display:none;"><option value="">Please select complexity</option>' . loadComboListFromArray(productComplexityName(null, 2)) . '</select> Complexity &laquo;';
                     $deflength = $products_length <= 0 ? '&nbsp;' : '&raquo; Default Length ' . textLength($products_length);
                     $result .= '<div style="margin-top:10px;width:' . $form_width . 'px;"><h2 style="float:right;">' . $complexity . '</h2><h2>' . $deflength . '</h2></div>';
                     $result .= '<div class="smallText notice" style="margin-bottom:2px;">* Remove elements by updating Qty to 0 (zero). To save all changes you MUST click on button "Save Changes"</div>';
                     $result .= '<div class="draw-table">';
                     $result .= '<table class="proman" border="0" cellpadding="0" cellspacing="0">';
                     //Header
                     $result .= '<tr>';
                     $result .= '<th>Image</th><th>ID</th><th class="w100">Main&nbsp;Element<br> <a href="javascript:void(0)" id="clear-main-image">Clear</a></th>';
                     $result .= '<th>Name</th><th>Qty</th>';
                     $result .= '<th>Finishing</th>';
                     $result .= '<th><abbr title="Material Expenses">Mat.Exp.</abbr></th>';
                     $result .= '<th>Action</th>';
                     $result .= '</tr>';
                     $counter = 0;
                     $matexp_total = 0;
                     while ($pue = tep_db_fetch_array($pue_result)) {
                         $products_analysis_link = '';
                         $counter++;
                         $rowclass = $counter % 2 == 0 ? 'e' : 'o';
                         $pueid = $pue['products_use_elements_id'];
                         $elid = $pue['elements_id'];
                         $qty = $pue['quantity'];
                         $is_main_el = $pue['is_main'];
                         $lr_check = $pue['length_relevance'] == '1' ? 'checked="checked"' : '';
                         $is_main_el_check = $pue['is_main'] == '1' ? 'checked="checked"' : '';
                         $is_main_el_result = '<input type="radio" id="' . $elid . '" class="is_main" name="is_main[' . $pue['elements_id'] . ']" value="1"' . $is_main_el_check . '/>';
                         $el_img = webImageWithDetailLink($pue['elements_image'], '80', '80', 'Element ' . $pue['elements_id']);
                         $quantity = '<input type="text" name="upd_qty[' . $pue['elements_id'] . ']" value="' . $pue['quantity'] . '" style="width:50px;text-align:center;" onfocus="this.select();" />';
                         $fin_gp = $pue['finishing_goldplate'] == '1' ? 'checked="checked"' : '';
                         $fin_hm = $pue['finishing_hammer'] == '1' ? 'checked="checked"' : '';
                         $fin_br = $pue['finishing_brush'] == '1' ? 'checked="checked"' : '';
                         $fin_ox = $pue['finishing_oxid'] == '1' ? 'checked="checked"' : '';
                         $fin_rg = $pue['finishing_rosegoldplate'] == '1' ? 'checked="checked"' : '';
                         $finishing = '<div style="margin-left:15px;"><table border="0" cellpadding="0" cellspacing="0">';
                         $finishing .= '<tr><td style="width:20px;"><input type="checkbox" id="fin_gp_' . $counter . '" class="fin" name="finishing_goldplate[' . $pue['elements_id'] . ']" value="1"' . $fin_gp . ' /></td><td class="load"><label for="fin_gp_' . $counter . '">Yellow Goldplate</label></td></tr>';
                         $finishing .= '<tr><td style="width:20px;"><input type="checkbox" id="fin_rg_' . $counter . '" class="fin" name="finishing_rosegoldplate[' . $pue['elements_id'] . ']" value="1"' . $fin_rg . ' /></td><td class="load"><label for="fin_rg_' . $counter . '">Rose Goldplate</label></td></tr>';
                         $finishing .= '<tr><td style="width:20px;"><input type="checkbox" id="fin_hm_' . $counter . '" class="fin" name="finishing_hammer[' . $pue['elements_id'] . ']" value="1"' . $fin_hm . ' /></td><td class="load"><label for="fin_hm_' . $counter . '">Hammer</label></td></tr>';
                         $finishing .= '<tr><td style="width:20px;"><input type="checkbox" id="fin_br_' . $counter . '" class="fin" name="finishing_brush[' . $pue['elements_id'] . ']" value="1"' . $fin_br . ' /></td><td class="load"><label for="fin_br_' . $counter . '">Brush</label></td></tr>';
                         $finishing .= '<tr><td style="width:20px;"><input type="checkbox" id="fin_ox_' . $counter . '" class="fin" name="finishing_oxid[' . $pue['elements_id'] . ']" value="1"' . $fin_ox . ' /></td><td class="load"><label for="fin_ox_' . $counter . '">Oxid</label></td></tr>';
                         $finishing .= '</table></div>';
                         //$matexp = $pue['quantity'] * $pue['elements_price'];
                         $matexp = $this->elementMaterialExpenses($pue['quantity'], $pue['elements_price']);
                         if ($pue['finishing_goldplate'] == '1') {
                             $matexp += FINISHING_PRICE_YELLOWGOLD;
                         }
                         if ($pue['finishing_hammer'] == '1') {
                             $matexp += FINISHING_PRICE_HAMMER;
                         }
                         if ($pue['finishing_brush'] == '1') {
                             $matexp += FINISHING_PRICE_BRUSH;
                         }
                         if ($pue['finishing_oxid'] == '1') {
                             $matexp += FINISHING_PRICE_OXID;
                         }
                         if ($pue['finishing_rosegoldplate'] == '1') {
                             $matexp += FINISHING_PRICE_ROSEGOLD;
                         }
                         $matexp_total += $matexp;
                         $matexp_link = '<a href="?open=elements-suppliers&id=' . $pue['elements_id'] . '&hidemenu=true" class="view_webpage" title="View elements suppliers detail">' . displayCurrency('EUR', $matexp) . '</a>';
                         //$products_analysis_link = '<a href="?open=products-analysis&sp=allsp&filter=el-used&sign=e&value='.$pue['elements_id'].'" target="_blank">Show all Products using this element</a>';
                         $products_analysis_link = '<a href="?open=products-analysis&sp=allsp&filter=el-used&sign=e&value=' . $pue['elements_id'] . '" target="_blank" title="Show all Products using Element ' . $pue['elements_id'] . '">&laquo; Show All Products &raquo;</a>';
                         $result .= '<tr class="' . $rowclass . '">';
                         $result .= '<td>' . $el_img . '</td>';
                         $result .= '<td><a class="view_webpage" href="?open=element&amp;id=' . $pue['elements_id'] . '&amp;hidemenu=true" title="Manage Element Detail">' . $pue['elements_id'] . '</a></td>';
                         $result .= '<td>' . $is_main_el_result . '</td>';
                         $result .= '<td class="name">' . $pue['elements_description'] . '<br />' . drawStars($pue['stars']) . '<br />' . $products_analysis_link . '</td>';
                         $result .= '<td>' . $quantity . '</td>';
                         $result .= '<td style="width:120;">' . $finishing . '</td>';
                         $result .= '<td class="pri">' . $matexp_link . '</td>';
                         $btn_o_def = '<input class="btn_ovr_def" type="button" value="Replace" title="Replace this element" />';
                         $h_pueid = '<input type="hidden" id="d_pueid" value="' . $pueid . '"/>';
                         $h_elid_def = '<input type="hidden" id="d_elid" value="' . $elid . '"/>';
                         $h_qty_def = '<input type="hidden" id="d_qty" value="' . $qty . '"/>';
                         $result .= '<td>' . $btn_o_def . $h_pueid . $h_elid_def . $h_qty_def . '</td>';
                         $result .= '</tr>';
                     }
                     $products_finishing = array();
                     $products_finishing_styles = $this->productHaveStylePrice('PF', $products_id);
                     $products_finishing_cost = 0;
                     if (count($products_finishing_styles) > 0) {
                         foreach ($products_finishing_styles as $styles_id) {
                             $products_finishing_cost = $this->getStylePrice($styles_id);
                             $matexp_total += $products_finishing_cost;
                             //not use class styles related to php5 issues for J&G webshop
                             $f_r = tep_db_query("SELECT name FROM styles_description WHERE styles_id = {$styles_id} AND languages_id = 2");
                             $f_row = tep_db_fetch_array($f_r);
                             $products_finishing[$f_row['name']] = $products_finishing_cost;
                         }
                     }
                     //$result .= '<tr><td colspan=""></td></tr>';
                     $result .= '</table></div>';
                     $chk_partial_plated = $product['p']['is_partial_plated'] == '1' ? 'checked="checked"' : '';
                     $title_product_is_partial_plated = 'Check this when product plated partially';
                     $result .= '<div style="margin:10px 0;float:left;" title="' . $title_product_is_partial_plated . '"><input type="checkbox" id="is_pp" value="1" name="is_partial_plated" ' . $chk_partial_plated . '>' . '<label for="is_pp"> Product is Partially Plated</label></div>';
                     if (count($products_finishing) > 0) {
                         $result .= '<div style="margin:10px 0;width:' . $form_width . 'px;text-align:right;">';
                         foreach ($products_finishing as $pfin_name => $pfin_cost) {
                             $result .= 'Product Finishing ' . $pfin_name . ': ' . displayCurrency('EUR', $pfin_cost) . '<br/>';
                         }
                         $result .= '</div>';
                     }
                     $result .= '<h3 style="margin:10px 0;width:' . $form_width . 'px;text-align:right;">Total Material Expenses: ' . displayCurrency('EUR', $matexp_total) . '</h3>';
                     $result .= str_replace('{BTNUPDDIS}', '', $form_footer);
                     //ARTICLES (ADDITIONAL LENGTH) TABLES
                     use_class('products_articles');
                     $class_pa = new products_articles();
                     $articles = $class_pa->retrieveList($products_id);
                     if (count($articles) > 0) {
                         $result .= '<div style="margin-top:30px;"><h2>Additional Length</h2></div>';
                         foreach ($articles as $key => $article) {
                             $p_aid = $article['products_articles_id'];
                             $qaue = "SELECT pa.*, pue.`quantity`,pue.`elements_id`, pue.`products_use_elements_id`, e.elements_image\n                                        FROM  products_articles pa\n                                        INNER JOIN `products_use_elements` pue ON pue.`products_id` = pa.`products_id`\n                                        LEFT JOIN element e ON e.`elements_id` = pue.`elements_id`\n                                        WHERE pa.`products_articles_id` = {$p_aid}";
                             $dbqaue = tep_db_query($qaue);
                             $p_ean = '';
                             $result .= '<div style="border:solid 1px #ababab;float:left;margin:0 20px 20px 0;background:#fff;">';
                             $articles_data = array();
                             while ($row = tep_db_fetch_array($dbqaue)) {
                                 $articles_data[$p_aid][] = $row;
                             }
                             foreach ($articles_data as $paid => $dt) {
                                 $p_ean = $dt[0]['products_ean'];
                                 $p_length = textLength($dt[0]['length']);
                                 $result .= '<h3 style="margin:5px;">Length ' . $p_length . '</h3>';
                                 $result .= '<table class="paid" border="0" celpadding="0" cellspacing="0"><tr><th>Image</th><th>ID</th><th>Qty.</th><th>Action</th></tr>';
                                 $n = 0;
                                 foreach ($dt as $key => $rd) {
                                     $el_img = $dt[$n]['elements_image'];
                                     $elid_def = $rd['elements_id'];
                                     $qty_def = $rd['quantity'];
                                     $qty_ovr = '0';
                                     $elid_ovr = '0';
                                     $pueid = $rd['products_use_elements_id'];
                                     $q_check = "SELECT paue.*, e.elements_image FROM products_articles_use_elements paue LEFT JOIN element e ON e.`elements_id` = paue.`elements_id` WHERE products_articles_id = {$p_aid} AND products_use_elements_id = {$pueid}";
                                     $dbqc = tep_db_query($q_check);
                                     if (tep_db_num_rows($dbqc) > 0) {
                                         while ($rc = tep_db_fetch_array($dbqc)) {
                                             $elid_ovr = $rc['elements_id'];
                                             $qty_ovr = $rc['quantity'];
                                             if ($elid_ovr != '' && $elid_ovr != '0') {
                                                 $el_img = $rc['elements_image'];
                                             }
                                         }
                                     }
                                     $style_elid = $elid_ovr != '0' && $elid_ovr != $elid_def ? ' bold' : '';
                                     $style_qty = $qty_ovr != '0' && $qty_ovr != $qty_def ? ' bold' : '';
                                     $elid = $elid_ovr != '0' ? $elid_ovr : $elid_def;
                                     $qty = $qty_ovr != '0' ? $qty_ovr : $qty_def;
                                     $result .= "<div>";
                                     $result .= '<tr id="' . $p_aid . $elid_def . '"' . ($style_elid != '' || $style_qty != '' ? 'style="background:#fbff96;"' : "") . ">";
                                     $result .= '<td class="img">' . webImage($el_img, '80', '80') . '</td>';
                                     $result .= '<td class="id' . $style_elid . '">' . ($style_elid != '' ? '<a href="?open=element&amp;id=' . $elid . '&amp;hidemenu=true" class="view_webpage">' . $elid . '</a>' : $elid) . '</td>';
                                     $result .= '<td class="qty' . $style_qty . '">' . $qty . '</td>';
                                     $h_paid = '<input type="hidden" id="h_paid" value="' . $p_aid . '"/>';
                                     $h_pean = '<input type="hidden" id="h_pean" value="' . $p_ean . '"/>';
                                     $h_pueid = '<input type="hidden" id="h_pueid" value="' . $pueid . '"/>';
                                     $h_elid_def = '<input type="hidden" id="h_elid_def" value="' . $elid_def . '"/>';
                                     $h_qty_def = '<input type="hidden" id="h_qty_def" value="' . $qty_def . '"/>';
                                     $h_elid = '<input type="hidden" id="h_elid" value="' . $elid . '"/>';
                                     $h_qty = '<input type="hidden" id="h_qty" value="' . $qty . '"/>';
                                     $btn_o = '<input class="btn_ovr" type="button" style="font-size:10;color:blue;margin:0;padding:0;" value="O" title="Override this element" />';
                                     $btn_r = $elid_ovr != 0 && $elid_ovr != $elid_def || $qty_ovr != 0 && $qty_ovr != $qty_def ? '<input class="btn_ovr_r" type="button" style="font-size:10;color:red;margin:0;padding:0;" value="R" title="Reset this element to ' . $elid_def . ' / ' . $qty_def . '"/>' : '<input class="btn_ovr_r" type="button" style="font-size:10;margin:0;padding:0;color:grey;" value="R" title="Reset this element to ' . $elid_def . ' / ' . $qty_def . '" disabled="disabled"/>';
                                     $result .= "<td>{$btn_o} {$btn_r} {$h_paid} {$h_pean} {$h_pueid} {$h_elid_def} {$h_qty_def} {$h_elid} {$h_qty}</td>";
                                     $result .= "</tr>";
                                     $n++;
                                 }
                                 $result .= '</table>';
                             }
                             $result .= '</div>';
                         }
                     }
                 }
                 $result .= '<div style="clear:both;"></div>';
             }
             $result = utf8_encode($result);
             break;
         case 'UPDATE':
             break;
         case 'ADD':
             break;
     }
     return $result;
 }