<?php
include_once($_SERVER['DOCUMENT_ROOT'] . "/apps/billing/config/autoload.php");
$home=$_SERVER['DOCUMENT_ROOT'];
$invoice_no = 0;

if (isset($_GET['id']) && is_numeric($_GET['id']))
    $invoice_no = $_GET['id'];
else
    exit();

$pdf = new FPDF('P', 'in', array(6, 4));
$pdf->AddFont('PFDinTextCondPro-Bold', '', 'PFDinTextCondPro-Bold.php');
$pdf->AddFont('PFDinTextCondPro-Bold', 'B', 'PFDinTextCondPro-Bold.php');
$pdf->AddFont('PFDinTextCondPro-Light', '', 'PFDinTextCondPro-Light.php');
$pdf->AddFont('PFDinTextCondPro-Light', 'B', 'PFDinTextCondPro-Light.php');
$pdf->SetMargins(.15, .4, 0);


$Category = 'Cachitos';
$delivery_date = "11 Nov 2022";
$boxes = "10/10";
$boxQty = 12;
$boxName = 'Cto Jambon & Fromage';
$ImageDesc = $home . '/apps/billing/img/frozen.jpg';
$client_name = "Depaneur ROME";
$barcode_product = $home . '/apps/billing/img/barcodetest.png';

$invoice = Billing_Invoice::with_id($invoice_no,true);
$invoice_det=$invoice->invoice_detail;
//$invoice_det =invoice_details::with_field('invoice_id',$invoice_no,'id','asc');
$client=Billing_Client::with_id($invoice->client_id,false);
//$address=$client->client_address;
//$address=client_address::with_field('clients_id',$invoice->clients_id,'id','asc');
//$address=$client->client_address;
$address=billing_client_address::with_client_id($invoice->client_id);


foreach ($invoice_det  as $id){
    $p=Billing_Product::with_id($id->product_id);
    $id->child=$p;
    
}
function splitLabelByMaxQty(string $label, int $maxQty): array {
    // Normalize whitespace
   // $label = trim(preg_replace('/\s+/', ' ', $label));

    // If label fits, return as-is
    if (strlen($label) <= $maxQty) {
        return [$label];
    }

    // Group phrases with slashes or pipes into single tokens
    // e.g., "Andes / 2436-2030" → "Andes/2436-2030"
    //       "Brand | Subbrand" → "Brand|Subbrand"
    //$label = preg_replace('/\s+([\/|])\s+/', '$1', $label);

    // Split by space
    $tokens = explode(' ', $label);

    $part1 = '';
    $part2 = '';

    foreach ($tokens as $word) {
        $next = ($part1 === '' ? '' : ' ') . $word;
        if (strlen($part1 . $next) <= $maxQty) {
            $part1 .= $next;
        } else {
            $part2 .= ($part2 === '' ? '' : ' ') . $word;
        }
    }

    return [$part1, $part2];
}



class BoxesLabels
{

    public $Quantity = 0;
    public $Delivery_date = "";
    public $Category = "";
    public $product_name = "";
    public $Client = "";
    public $TotalBoxes = ""; // 1/10;
    public $Box_no = ""; // 1/10;
    public $ImageDesc = '/apps/billing/img/frozen.jpg';
    public $barcode_product = '';
    function __construct($Quantity, $Delivery_date, $Category, $product_name, $Client, $Box_no, $barcode)
    {
        $this->Quantity = $Quantity;
        $this->Delivery_date = $Delivery_date;
        $this->Category = $Category;
        $this->product_name = $product_name;
        $this->Client = $Client;
        $this->TotalBoxes = "";
        $this->Box_no = $Box_no;
        if ($barcode <> '')
            $this->barcode_product = '/apps/billing/img/product_barcode/' . $barcode . '.png';
        else
            $this->barcode_product = '';
    }
}



$box = 0;
$box_capacity = 12;
$Total_Boxes = 0;
$aux_qty = 0;
$array_labels = array();
$box_control = "";
$box_number = 0;
$HalfBoxes = array();

$y = 1;
foreach ($invoice_det as $row) { // fill Boxes full
if($row->product_id==240)//EMPANADAS
	$box_capacity=6;
if($row->product_id<>177)
{
    $row->child->name = str_replace('Cong.', '',   $row->child->name);
    if ($row->qty  >= $box_capacity) {
        $y = 1;
        for ($x = 1; $x <= $row->qty; $x++) { ///loop trought all quantities of same products
            if ($y == $box_capacity) { //Full box
                $newbox = new BoxesLabels($y, $invoice->issue_date, iconv('UTF-8', 'ISO-8859-1', $row->child->category), iconv('UTF-8', 'ISO-8859-1', $row->child->name), iconv('UTF-8', 'ISO-8859-1', $address[0]->name), count($array_labels) + 1, $row->child->barcode);
                $aux_qty = $aux_qty - $box_capacity;
                $box_capacity = 12; //its empty again
                $y = 0;
                $array_labels[] =  $newbox;
            }
            $y++;
        }

        $y--;

        if ($y > 0) { //remaining items
            $HalfBoxes[]   = new BoxesLabels($y, $invoice->issue_date, iconv('UTF-8', 'ISO-8859-1', $row->child->category), iconv('UTF-8', 'ISO-8859-1', $row->child->name), iconv('UTF-8', 'ISO-8859-1', $address[0]->name), '', $row->child->barcode);
        }
    } else
   if ($row->qty  <= $box_capacity) { //remaining items
        $HalfBoxes[]   = new BoxesLabels($row->qty, $invoice->issue_date, iconv('UTF-8', 'ISO-8859-1', $row->child->category), iconv('UTF-8', 'ISO-8859-1', $row->child->name), iconv('UTF-8', 'ISO-8859-1', $address[0]->name), '', $row->child->barcode);
    }
}
else //alfajores all of them in 1 single box
{
    $array_labels[]  = new BoxesLabels($row->qty, $invoice->issue_date, iconv('UTF-8', 'ISO-8859-1', $row->child->category), iconv('UTF-8', 'ISO-8859-1', $row->child->name), iconv('UTF-8', 'ISO-8859-1', $address[0]->name), count($array_labels) + 1, $row->child->barcode);
    
}
}

$boxes_no = count($array_labels);

for ($x = 0; $x <= count($HalfBoxes) - 1; $x++) { // grouping half boxes that sums 12 couples
    for ($y = $x + 1; $y <= count($HalfBoxes) - 1; $y++) { // grouping half boxes
        if ($HalfBoxes[$x]->Quantity + $HalfBoxes[$y]->Quantity == 12) {
            if ($HalfBoxes[$x]->Box_no == '' && $HalfBoxes[$y]->Box_no == '') {
                $boxes_no++;
                $HalfBoxes[$x]->Box_no = $boxes_no;
                $HalfBoxes[$y]->Box_no = $boxes_no;
                $array_labels[] = clone $HalfBoxes[$x];
                $array_labels[] = clone $HalfBoxes[$y];
                break;
            }
        }
    }
}

$boxes_no_count = 0;
if (count($HalfBoxes) > 0)
    for ($x = 0; $x <= count($HalfBoxes) - 1; $x++) {
        if ($HalfBoxes[$x]->Box_no == '') {
            $boxes_no++;
            break;
        }
    }


for ($x = 0; $x <= count($HalfBoxes) - 1; $x++) { // grouping half boxes that fits within a box of 12 by couples
    for ($y = $x + 1; $y <= count($HalfBoxes) - 1; $y++) { // grouping half boxes
        if ($HalfBoxes[$x]->Quantity + $HalfBoxes[$y]->Quantity + $boxes_no_count <= 12) {
            if ($HalfBoxes[$x]->Box_no == '' && $HalfBoxes[$y]->Box_no == '') {
                $boxes_no_count = $HalfBoxes[$x]->Quantity + $HalfBoxes[$y]->Quantity + $boxes_no_count;
                if ($boxes_no_count >= 12) {
                    $boxes_no++;
                    $boxes_no_count = 0;
                }

                $HalfBoxes[$x]->Box_no = $boxes_no;
                $HalfBoxes[$y]->Box_no = $boxes_no;
                $array_labels[] = clone $HalfBoxes[$x];
                $array_labels[] = clone $HalfBoxes[$y];
                break;
            }
        }
    }
}


for ($x = 0; $x <= count($HalfBoxes) - 1; $x++) { // grouping half boxes    
    if ($HalfBoxes[$x]->Quantity + $boxes_no_count <= 12) {
        if ($HalfBoxes[$x]->Box_no == '') {
            $boxes_no_count = $boxes_no_count + $HalfBoxes[$x]->Quantity;
            if ($boxes_no_count >= 12) {
                $boxes_no++;
                $boxes_no_count = 0;
            }
            $HalfBoxes[$x]->Box_no = $boxes_no;
            $array_labels[] = clone $HalfBoxes[$x];
        }
    }
}

for ($x = 0; $x <= count($HalfBoxes) - 1; $x++) { // grouping half boxes that wont fit anywhere
    if ($HalfBoxes[$x]->Box_no == '') {
        $boxes_no++;
        $HalfBoxes[$x]->Box_no = $boxes_no;
        $array_labels[] = clone $HalfBoxes[$x];
    }
}

for ($x = 0; $x <= count($array_labels) - 1; $x++) { // Setting Total no of Boxes for all labels
    $array_labels[$x]->TotalBoxes = $boxes_no;
}

foreach ($array_labels as $row) { //loop to create pdf for labels
    $box++;
    $Category = $row->Category;
    $delivery_date = $row->Delivery_date;
    $boxes = $row->Box_no . "/" . $row->TotalBoxes;
    $boxQty = $row->Quantity;
    //$boxName =  substr($row->product_name, 0, 26);
	$boxName =  $row->product_name;
    $ImageDesc = $home . '/apps/billing/img/frozen.jpg';
    $client_name =  $row->Client;
    if ($row->barcode_product <> '')
        $barcode_product = $home . $row->barcode_product;
    else
        $barcode_product = '';

    $BN=billing_parameter::with_name('BUSSINES_NAME');
    $BN=$BN[0];
    $pdf->AddPage();
    $pdf->SetFont('Arial', 'B', 16);

    // Logo
    $pdf->Image($home . '/apps/billing/img/logos/mainlogo.png', .2, .2, 1.4);
    $pdf->SetAutoPageBreak(false);

    $pdf->SetFont('PFDinTextCondPro-Bold', 'B', 11);
    $pdf->Cell(1.5, 0.5, '', 0, 0, 'C');
    $pdf->Cell(3.7, 0, $BN->val, 0, 1, 'L');

    $pdf->SetFont('PFDinTextCondPro-Light', 'B', 11);
    $pdf->Cell(1.5, 0.5, '', 0, 0, 'L');
    $pdf->Cell(3.7, 0.3, '614 Bd Guimond,Longueuil,QC,J4G1P8', 0, 1, 'L');

    $pdf->Cell(1.5, 0.5, '', 0, 0, 'L');
    $pdf->Cell(3.7, 0, 'production@cachitos.ca', 50, 1, 'L');

    $pdf->Cell(1.5, 0, '', 0, 0, 'L');
    $pdf->Cell(3.7, 0.3, 'www.cachitos.ca', 50, 1, 'L');

    $pdf->Cell(5, 0.1, '', 0, 1, 'R');

    $pdf->SetFont('Arial', '', 16);
    $pdf->SetFont('PFDinTextCondPro-Light', 'B', 20); // 26 supposed to be
    $pdf->Cell(2.2, 0.5, strtoupper($Category), 1, 0, 'L');

    $pdf->SetFont('PFDinTextCondPro-Light', 'B', 14); // 26 supposed to be
    $pdf->Cell(1.0, 0.5, strtoupper($delivery_date), 1, 0, 'C');

    $pdf->SetFont('PFDinTextCondPro-Bold', 'B', 14); // 26 supposed to be
    $pdf->Cell(.5, 0.5, strtoupper($boxes), 1, 1, 'C');

    $pdf->SetFont('Arial', '', 50);
    $pdf->Cell(1.2, 1, strtoupper($boxQty), 1, 0, 'C');
    
	$pdf->Cell(2.5, 1, '', 1, 1, 'C');//square for the barcode
	
    if ($barcode_product <> '' && file_exists($barcode_product))
        $pdf->Image($barcode_product, 1.7, 1.7, 1.7);

    $pdf->SetFont('PFDinTextCondPro-Bold', 'B', 20); // 26 supposed to be
    $BOXNAME_SPLIT=splitLabelByMaxQty($boxName, 26);
	
	if (count($BOXNAME_SPLIT)==1){ 
		$pdf->Cell(3.7, 0.5, strtoupper($BOXNAME_SPLIT[0]), 1, 1, 'C');
    }
	
	if (count($BOXNAME_SPLIT)>1){ 
		$pdf->SetFont('PFDinTextCondPro-Bold', 'B', 17); // 26 supposed to be
	    $pdf->Cell(3.7, 0.5, "",1,1,'C');
		$pdf->setY(2.6);
		$pdf->Cell(3.7, 0.25, strtoupper($BOXNAME_SPLIT[0]), 0, 1, 'C');	
		$pdf->Cell(3.7, 0.25, strtoupper($BOXNAME_SPLIT[1]), 0, 1, 'C');
	}
	
	//$pdf->Cell(3.7, 0.5, strtoupper(substr($boxName, 0, 26)), 1, 1, 'C');

    //if image desc
    $pdf->Cell(3.7, 2.0, "", 1, 1, 'C');
    $pdf->Image($ImageDesc, 0.8, 3.3, 2.5);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFont('PFDinTextCondPro-Bold', 'B', 20);

    $strpos = strpos($client_name, '|');
	
    if ($strpos == false)
        $strpos = 35;
	


    $array_name	=array();
    $array_name=splitLabelByMaxQty($client_name, 26);
/*
	echo $client_name."<br>";
	echo $array_name[0]." 1 <br>";
	echo $array_name[1]. " 2<br><br>";
  */   
    if (count($array_name)==1){ 
		$pdf->Cell(3.7, 0.5, strtoupper($array_name[0]), 1, 0, 'C', true);	
    }
	
	if (count($array_name)>1){ 
		$pdf->Cell(3.7, 0.4, strtoupper($array_name[0]), 1, 1, 'C', true);	
		$pdf->Cell(3.7, 0.4, strtoupper($array_name[1]), 1, 1, 'C', true);
	}
	
    $pdf->SetTextColor(0, 0, 0);
}

$pdf->Output();
