<?php

//echo __FILE__;
//exit;

global $app_list_strings, $mod_strings, $db, $sugar_config;

$pdf->focus = $this;

//$mod_strings = return_module_language($sugar_config['default_language'], 'EcmInvoiceOuts', true);
$mod_strings = return_module_language('pl_pl', 'EcmInvoiceOuts', true);
//$mod_strings2 = return_module_language('en_us', 'EcmInvoiceOuts', true);

/* BOF: Seller, buyer. */
$buyer = htmlspecialchars_decode($this->parent_name);//str_replace(array('&lt;', '&gt;'), array('<', '>'), $this->parent_name);

if ($this->parent_contact_name) {
    $buyer .= PHP_EOL . $this->parent_contact_name;

    if ($this->parent_contact_title) {
        $buyer .= PHP_EOL . $this->parent_contact_title;
    }

    $personplus = 5;
} else {
    $personplus = 0;
}

if ($this->parent_address_street) {
    $buyer .= PHP_EOL . $this->parent_address_street;
}

if ($this->parent_address_postalcode) {
    $buyer .= PHP_EOL . $this->parent_address_postalcode;
}

if ($this->parent_address_city) {
    $buyer .= " " . $this->parent_address_city;
}

//if($this->to_vatid) {
//    $buyer .= PHP_EOL.$mod_strings['LBL_PDF_VATID']." ".$this->to_vatid;
//}

if ($this->to_nip) {
    $buyer .= PHP_EOL . $mod_strings['LBL_PDF_NIP'] . ": " . $this->to_nip;
} elseif (!$this->to_nip && $this->to_vatid) {
    $buyer .= PHP_EOL . $mod_strings['LBL_PDF_NIP'] . ": " . $this->to_vatid;
}


//to address
$old_x = $pdf->GetX();
$old_y = $pdf->GetY();

$pdf->SetXY(10, 53);
$pdf->SetFont('arialpl', 'B', 8);

$pdf->Cell(35, 1, strtoupper($mod_strings['LBL_PDF_SELLER']), 0, 0, 'L', 1);

$pdf->Ln(3);

$pdf->SetX(10);
$pdf->SetFont('arialpl', '', 8);

$qr = 'SELECT to_vatid FROM accounts WHERE id = \'' . $pdf->edt->account_id . '\'';
$r = $db->fetchByAssoc($db->query($qr));

$wys = $pdf->edt->name . PHP_EOL;

if ($pdf->edt->footer_address) {
    $wys .= $pdf->edt->footer_address . PHP_EOL;
}

if ($r['to_vatid']) {
    $wys.= $mod_strings['LBL_PDF_NIP'] . ': ' . $r['to_vatid'];
}

$pdf->MultiCell(60, 4, $wys, 0, 'L');

$pdf->SetXY(76, 53);
$pdf->SetFont('arialpl', 'B', 8);

$pdf->Cell(35, 1, strtoupper($mod_strings['LBL_PDF_BUYER']), 0, 0, 'L', 1);

$pdf->Ln(3);

$pdf->SetX(76);
$pdf->SetFont('arialpl', '', 8);
$pdf->MultiCell(60, 4, $buyer, 0, 'L');
/* EOF: Seller, buyer. */

if ($this->type == "correct") {
    $qr = "SELECT wz_id FROM ecminvoiceouts WHERE id = '" . $this->ecminvoiceout_id . "'";
    $r = $db->fetchByAssoc($db->query($qr));

    $wz_id = $r['wz_id'];
} else {
    $wz_id = $this->wz_id;
}

$qr = "SELECT * FROM ecmstockdocouts WHERE id='" . $wz_id . "'";
$r = $db->fetchByAssoc($db->query($qr));

if ($r['parent_id'] == $this->parent_id) {
    $qr = "SELECT name as parent_name,shipping_address_street as parent_address_street,shipping_address_city as parent_address_city,shipping_address_postalcode as parent_address_postalcode,shipping_address_country as parent_address_country FROM accounts WHERE id='" . $this->parent_id . "'";
    $r = $db->fetchByAssoc($db->query($qr));
}

/* BOF: Delivery. */
$address='';
if ($this->parent_shipping_address_name) {
	$address .= str_replace(array('&lt;', '&gt;'), array('<', '>'), $this->parent_shipping_address_name).PHP_EOL;
}
if ($this->parent_shipping_address_street) {
    $address .= $this->parent_shipping_address_street;
}

if ($this->parent_shipping_address_postalcode) {
    $address .= PHP_EOL . $this->parent_shipping_address_postalcode;
}

if ($this->parent_shipping_address_city) {
    $address .= ' ' . $this->parent_shipping_address_city;
}

//if ($r['to_nip']) {
//    $address .= PHP_EOL . $mod_strings['LBL_PDF_NIP'] . ": " . $r['to_nip'];
//} elseif (!$r['to_nip'] && $r['to_vatid']) {
//    $address .= PHP_EOL . $mod_strings['LBL_PDF_NIP'] . ": " . $r['to_vatid'];
//}
//
$rr = $db->fetchByAssoc($db->query("SELECT iln FROM accounts WHERE name='".$this->parent_shipping_address_name."'"));
if ($rr['iln']) {
    $address .= "\nILN: " . $rr['iln'];
}

if ($address) {
    $pdf->SetXY(143, 53);

    $pdf->SetFont('arialpl', 'B', 8);
    $pdf->Cell(35, 1, strtoupper($mod_strings['LBL_PDF_DELIVERY']), 0, 0, 'L', 1);

    $pdf->Ln(3);

    $pdf->SetX(143);

    $pdf->SetFont('arialpl', '', 8);
    $pdf->MultiCell(60, 4, $address, 0, 'L');
}
/* EOF: Delivery. */

$ynew = 53 + 12;

$pc = null;

if ($this->ecmpaymentcondition_id) {
    require_once("modules/EcmPaymentConditions/EcmPaymentCondition.php");
    $pc = new EcmPaymentCondition();
    $pc->retrieve($this->ecmpaymentcondition_id);
}

$pdf->SetXY(160, $old_y + 15 + $personplus);

$table = array();

$table[0]['place_of_register'] = array(
    'width' => 20,
    'value' => $mod_strings['LBL_PDF_PLACE_OF_REGISTER'],
    'border' => 0,
    'overflow' => 1,
    'align' => 'L',
    'font-size' => 8,
);

$table[0]['place_of_register_value'] = array(
    'width' => 25,
    'value' => $this->template->place_of_register,
    'border' => 0,
    'overflow' => 1,
    'align' => 'L',
    'font-style' => 'b',
    'font-size' => 8,
);

$table[1]['date_reg'] = array(
    'width' => 20,
    'value' => $mod_strings['LBL_PDF_DATE_REGISTER'],
    'border' => 0,
    'overflow' => 1,
    'align' => 'L',
    'font-size' => 8,
);

$table[1]['date_reg_value'] = array(
    'width' => 36,
    'value' => $this->register_date,
    'border' => 0,
    'overflow' => 1,
    'align' => 'L',
    'font-style' => 'b',
    'font-size' => 8,
);

$table[2]['date_sell'] = array(
    'width' => 20,
    'value' => $mod_strings['LBL_PDF_DATE_SELL'],
    'border' => 0,
    'overflow' => 1,
    'align' => 'L',
    'font-size' => 8,
);

$table[2]['date_sell_value'] = array(
    'width' => 36,
    'value' => $this->sell_date,
    'border' => 0,
    'overflow' => 1,
    'align' => 'L',
    'font-style' => 'b',
    'font-size' => 8,
    'valign' => 'C',
);

$q = 'select s.`document_no` as `number`, s.`parent_document_no` as `doc_number`, s.`date_entered` as `date` from `ecminvoiceoutitems` as ii join `ecmsales` as s on s.`id` = ii.`parent_doc_id` where ii.`ecminvoiceout_id` = \''.  $this->id . '\' and ii.`parent_doc_type` = \'EcmSales\' group by s.`document_no`;';

$result = $db->query($q);
$results = $db->fetchByAssoc($result);

// echo '<pre>' . var_export($results['doc_number'], true);
// echo '<pre>' . var_export(preg_split ('/( )/', $results['doc_number']), true);
// exit;
 
if($results) {
    
    $table[3]['date_sell'] = array(
        'width' => 16,
        'value' => 'Zamówienie klienta',
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );

    $table[3]['date_sell_value'] = array(
        // 'width' => 36 + 16 + 4,
        'width' => 36 + 4,
        'value' =>  chunk_split($results['doc_number'], 15),
        // 'value' =>  chunk_split('Zamówienie: ' . $results['doc_number'], 35), //chunk_split($results['doc_number'], 15),
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => 'b',
        'font-size' => 8,
        'valign' => 'C',
    );
    
    
    //echo '<pre>' . var_dump($results['doc_number'], chunk_split($results['doc_number'], 9), true); exit;
    
    $table[4]['date_sell'] = array(
        'width' => 16,
        'value' => 'Nr ZS',
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );

    $table[4]['date_sell_value'] = array(
        'width' => 36 + 4,
        'value' => $results['number'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => 'b',
        'font-size' => 8,
        'valign' => 'C',
    );
    
    $table[5]['date_sell'] = array(
        'width' => 16,
        'value' => 'Data ZS',
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );

    $table[5]['date_sell_value'] = array(
        'width' => 36 + 4,
        'value' => date('d.m.Y', strtotime($results['date'])),
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => 'b',
        'font-size' => 8,
        'valign' => 'C',
    );
}

if ($this->ecmpaymentcondition_id) {
    $table[4]['payment_termin'] = array(
        'width' => 20,
       'value' => $mod_strings['LBL_PDF_PAYMENT_TERMIN'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
       'font-size' => 8,
    );

    $r = $db->fetchByAssoc($db->query("SELECT paid FROM ecminvoiceouts WHERE id='" . $_REQUEST['record'] . "'"));

    if ($r['paid'] == 1) {
        $paid = "zaplacono";
    } else {
        $paid = $this->payment_date;
    }

    if ($this->document_no == "FV 1421/10") {
        $table[4]['payment_termin_value'] = array(
            'width' => 36,
            'value' => "prepayment",
            'border' => 0,
            'overflow' => 1,
            'align' => 'L',
           'font-style' => 'b',
            'font-size' => 8,
        );
    } else {
        $table[4]['payment_termin_value'] = array(
            'width' => 36,
            'value' => $paid,
            'border' => 0,
            'overflow' => 1,
            'align' => 'L',
            'font-style' => 'b',
            'font-size' => 8,
        );
    }
}

if ($this->ecmpaymentcondition_id) {
    $table[5]['payment_method'] = array(
        'width' => 20,
        'value' => $mod_strings['LBL_PDF_PAYMENT_METHOD'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );

    if ($this->document_no == "FV 1421/10") {
        $table[5]['payment_method_value'] = array(
            'width' => 25,
            'value' => "money transfer",
            'border' => 0,
            'overflow' => 1,
            'align' => 'L',
            'font-style' => 'b',
            'font-size' => 8,
        );
    } else {
        $table[5]['payment_method_value'] = array(
            'width' => 25,
            'value' => $app_list_strings['ecmpaymentconditions_payment_method_dom'][$pc->payment_method],
            'border' => 0,
            'overflow' => 1,
            'align' => 'L',
            'font-style' => 'b',
            'font-size' => 8,
        );
    }
}

if ($this->supplier_code) {
    $table[6]['cr'] = array(
        'width' => 20,
        'value' => $mod_strings['LBL_PDF_SUPPLIER_CODE'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );
    $table[6]['cr_value'] = array(
        'width' => 25,
        'value' => $this->supplier_code,
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => 'b',
        'font-size' => 8,
    );
}

if ($this->type == "normal") {
    if (file_exists("modules/EcmStockDocOuts/EcmStockDocOut.php")) {
        require_once("modules/EcmStockDocOuts/EcmStockDocOut.php");
        $wz = new EcmStockDocOut();
        $wz->retrieve($this->wz_id);
    }

    $table[7]['wz'] = array(
        'width' => 20,
        'value' => $mod_strings['LBL_PDF_TO_WZ'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );

    $table[7]['wz_value'] = array(
        'width' => 25,
        'value' => $wz->document_no,
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => 'b',
        'font-size' => 8,
    );
} else {
    $this->loadEcmInvoiceOut();
    $this->ecminvoiceout->format_all_fields();

    $table[7]['wz'] = array(
        'width' => 20,
        'value' => $mod_strings['LBL_PDF_DOCUMENT_NAME_CORRECT_TO'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );
    $table[7]['wz_value'] = array(
        'width' => 25,
        'value' => $this->ecminvoiceout->document_no,
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => 'b',
        'font-size' => 8,
    );
}

$r = $db->fetchByAssoc($db->query("SELECT so_id FROM ecminvoiceouts WHERE id='" . $this->id . "'"));
$this->so_id = $r['so_id'];

if (!$this->so_id) {
    $this->so_id = $_SESSION['invoice_so_id'];
}

$qr = "SELECT wz_id FROM ecminvoiceouts WHERE id = '" . $this->id . "'";
$r = $db->fetchByAssoc($db->query($qr));

$qr = "SELECT so_id FROM ecmstockdocouts WHERE id = '" . $r['wz_id'] . "'";
$r = $db->fetchByAssoc($db->query($qr));

$qr = "SELECT parent_document_no FROM ecmsales WHERE id = '" . $r['so_id'] . "'";
$r = $db->fetchByAssoc($db->query($qr));

if ($r['parent_document_no'] && $this->type != "correct") {
    $table[8]['order_no'] = array(
        'width' => 20,
        'value' => $mod_strings['LBL_PDF_ORDER_NO'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );
    $table[8]['order_no_value'] = array(
        'width' => 25,
        'value' => $r['parent_document_no'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => 'b',
        'font-size' => 8,
    );
}

if ($this->type != "normal") {
    if (!$this->so_id) {
        $this->so_id = $_SESSION['invoice_so_id'];
    }

    $qr_so = "SELECT * FROM ecmsales WHERE id='" . $this->so_id . "'";
    $r_so = $db->fetchByAssoc($db->query($qr_so));

    $table[9]['cr'] = array(
        'width' => 20,
        'value' => $mod_strings['LBL_PDF_CORRECT_REASON'],
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-size' => 8,
    );
    $table[9]['cr_value'] = array(
        'width' => 25,
        'value' => $this->order_no,
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => 'b',
        'font-size' => 8,
    );
}

$pdf->SetXY(143, $pdf->tMargin + 2);
$pdf->DrawTable($table, null, 0.5, 0.5, 3);

$pdf->Ln(9);

$pdf->SetFont('arialpl', '', '18');
$pdf->SetXY(60, $pdf->tMargin + 25);

if ($this->type == "normal") {
    $pdf->MultiCell(80, 7, "Faktura nr " . $this->document_no, 0, 'C');
    $pdf->SetFont('arialpl', 'B', 7);
    $pdf->Ln(3);
    $pdf->SetX(60);
} else if ($this->type == "correct") {
    $pdf->MultiCell(80, 7, $mod_strings['LBL_PDF_DOCUMENT_NAME_CORRECT'] . " " . $this->document_no, 0, 'C');
    $pdf->SetFont('arialpl', 'B', 7);
    //$pdf->Ln(3);
    //$pdf->SetX(60);
    //$pdf->Cell(80, 1, $mod_strings['LBL_PDF_ORIGINAL_COPY'], 0, 0, 'C', 1);
}

$this->loadParser();

$this->header_text = $this->template->mfp->parseText($this->header_text);
$this->footer_text = $this->template->mfp->parseText($this->footer_text);
$this->ads_text = $this->template->mfp->parseText($this->ads_text);

$pdf->SetY($ynew);

$pdf->SetFont('arialpl', '', '7');

$currency = new Currency();
$currency->retrieve($this->currency_id);

$this->currency_symbol = $currency->iso4217;

//if($this->currency_symbol == 'PLN') {
//    $this->currency_symbol = 'zł';
//}

//echo '<pre>' . var_export($this->currency_symbol, true) . '</pre>'; exit;

//$this->currency_value  = $currency->conversion_rate;

if (!isset($this->position_list) || !is_array($this->position_list)) {
    $this->position_list = $this->getPositionList(true);
}

$calc = $this->calculate($this->position_list, true);
//$this->position_list = $this->formatPositions($this->position_list);

$calc['total'] .= ' ' . $this->currency_symbol;
$calc['subtotal'] .= ' ' . $this->currency_symbol;

if ($calc['discount']) {
    $calc['total2'] .= ' ' . $this->currency_symbol;
    $calc['discount']['value'] .= ' ' . $this->currency_symbol;
}

if (isset($calc['vats']) && is_array($calc['vats']) && count($calc['vats']) > 0) {
    foreach ($calc['vats'] as $key => $value) {
        $calc['vats'][$key] .= ' ' . $this->currency_symbol;
    }
}

$summary_offset = 118;

//$calc['draw_discount'] = 0;

$widths = array(
    // List.
    'position' => 4,
    'description' => 40,
    'recipient_code' => 10,	
    'quantity' => 8,// 7 + 5,
    //'unit' => 5,
    'draw_discount' => 11,
    'unit_price' => 11,
    'unit_price_total' => 11,
    'vat_id' => 5,
    'vat_value' => 11,
    'total' => 11,
    // Summary.
    'fix' => 61,
    'vat_rate' => 10,
    'netto_total' => 11,
    'vat_total' => 16,
    'brutto_total' => 11,
);

$pdf->Ln(7);

//$calc['draw_discount'] = 0;
//echo '<pre>' . var_export($calc, true) . '</pre>';exit;

if ($calc['draw_discount']) {
    $widths['description'] -= $widths['draw_discount'] - 1;
    $widths['quantity'] -= 1;
}


if (!$calc['draw_recipient_code']) {
	$widths['description'] += $widths['recipient_code'];
	$widths['recipient_code'] = 0;
}

/* BOF: Position list. */
$list = array();

$list[0]['position'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['position'],
    'value' => $mod_strings['LBL_PDF_LIST_POSITION'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 8,
);

$list[0]['description'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['description'],
    'value' => $mod_strings['LBL_PDF_LIST_DESCRIPTION'] . PHP_EOL . $mod_strings['LBL_PDF_LIST_INDEX'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 7,
);
if ($calc['draw_recipient_code']) {
$list[0]['recipient_code'] = array(
		'background' => array(233, 233, 233),
		'width' => $widths['recipient_code'],
		'value' => $mod_strings['LBL_PDF_RECIPIENT_CODE'],
		'border' => 1,
		'overflow' => 1,
		'align' => 'C',
		'font-style' => 'b',
		'font-size' => 7,
);
}
//$list[0]['tax_code'] = array(
//    'background' => array(233, 233, 233),
//    'width' => $widths['tax_code'],
//    'value' => $mod_strings['LBL_PDF_LIST_TAX_CODE'],
//    'border' => 1,
//    'overflow' => 1,
//    'align' => 'C',
//    'font-style' => 'b',
//    'font-size' => 7,
//);
//
//$list[0]['recipient_code'] = array(
//    'background' => array(233, 233, 233),
//    'width' => $widths['recipient_code'],
//    'value' => $mod_strings['LBL_PDF_LIST_TAX_CODE'],
//    'border' => 1,
//    'overflow' => 1,
//    'align' => 'C',
//    'font-style' => 'b',
//    'font-size' => 7,
//);

$list[0]['quantity'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['quantity'],
    'value' => $mod_strings['LBL_PDF_LIST_QUANTITY'] . PHP_EOL . $mod_strings['LBL_PDF_LIST_UNIT'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 7,
);

/*
$list[0]['unit'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['unit'],
    'value' => $mod_strings['LBL_PDF_LIST_UNIT'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 8,
);
*/

if ($calc['draw_discount']) {
    $list[0]['draw_discount'] = array(
        'background' => array(233, 233, 233),
        'width' => $widths['draw_discount'],
        'value' => 'Cena' . PHP_EOL . $mod_strings['LBL_PDF_LIST_DISCOUNT'],
        'border' => 1,
        'overflow' => 1,
        'align' => 'C',
        'font-style' => 'b',
        'font-size' => 7,
    );
}

$list[0]['unit_price'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['unit_price'],
    'value' => $mod_strings['LBL_PDF_LIST_UNIT_PRICE'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 7,
);

$list[0]['unit_price_total'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['unit_price_total'],
    'value' => $mod_strings['LBL_PDF_LIST_UNIT_PRICE_TOTAL'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 7,
);

//if($calc['draw_vat']) {
//if ($this->currency_symbol != "USD") {

$list[0]['vat_id'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['vat_id'],
    'value' => $mod_strings['LBL_PDF_LIST_VAT_ID'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 7,
);

$list[0]['vat_value'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['vat_value'],
    'value' => $mod_strings['LBL_PDF_LIST_VAT_VALUE'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 7,
);

//}
//}
//
//if ($this->currency_symbol == "USD") {
//    $list[0]['nw'] = array(
//        'background' => array(233, 233, 233),
//        'width' => 9,
//        'value' => "Netto weight",
//        'border' => 1,
//        'overflow' => 1,
//        'align' => 'C',
//        'font-style' => 'b',
//        'font-size' => 7,
//    );
//
//    $list[0]['bw'] = array(
//        'background' => array(233, 233, 233),
//        'width' => 9,
//        'value' => "Brutto weight",
//        'border' => 1,
//        'overflow' => 1,
//        'align' => 'C',
//        'font-style' => 'b',
//        'font-size' => 7,
//    );
//}

$list[0]['total'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['total'],
    'value' => $mod_strings['LBL_PDF_LIST_TOTAL'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 7,
);

if ($this->type != "normal") {
    $pdf->SetY(76);
}

//$pdf->SetY($pdf->GetY() - $calc['draw_discount'] ? $widths['draw_discount'] : 0);

/* EOF: Positions list. */

//$pdf->Ln(0);
//$table = array();

$lv = return_app_list_strings_language($this->ecmlanguage);

$i = 1;
$j = 1;
$netto_weight = $brutto_weight = 0;

if ($this->position_list != '') {
    //$p = array_pop($this->position_list);

    //$this->position_list = array_fill(0, 4, $p);
    //echo '<pre>' . var_export($this->position_list);exit;

    foreach ($this->position_list as $key => $position) {
        if ($this->type == "correct") {        	
        	$oi = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT ii.quantity, ii.subtotal, ii.total, ii.ecmvat_value, ii.discount, ii.dd_unit_id, ii.subprice, ii.price, ii.ecmvat_value, ii.ecmvat_name, ii.ecmvat_id FROM ecminvoiceoutitems as ii INNER JOIN ecminvoiceouts AS i ON i.id=ii.ecminvoiceout_id WHERE i.canceled='0' AND i.deleted='0' AND ii.ecminvoiceoutitem_id='".$position['item_id']."' AND ii.ecminvoiceout_id!='".$this->id."' AND i.date_entered < '".$position['date_entered']."' order by ii.date_entered desc limit 0,1"));
			//die("SELECT ii.quantity, ii.subtotal, ii.total, ii.ecmvat_value, ii.discount, ii.dd_unit_id, ii.subprice, ii.price, ii.ecmvat_value, ii.ecmvat_name, ii.ecmvat_id FROM ecminvoiceoutitems as ii INNER JOIN ecminvoiceouts AS i ON i.id=ii.ecminvoiceout_id AND WHERE i.canceled='0' AND i.deleted='0' AND ii.ecminvoiceoutitem_id='".$position['item_id']."' AND ii.ecminvoiceout_id!='".$this->id."' AND i.date_entered < '".$position['date_entered']."' order by ii.date_entered desc limit 0,1");
        	if ($oi && $oi['subtotal']!='') {
        		//była wcześniejsza korekta
        		if ((float)$position['total'] == (float)$oi['total'])
        			continue;
        	} else {
        		//nie było korekty - weź dane z FV
        		$oi = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT quantity, subtotal, total, ecmvat_value, discount, dd_unit_id, subprice, price, ecmvat_value, ecmvat_name, ecmvat_id FROM ecminvoiceoutitems WHERE id='".$position['item_id']."'"));
        		if ((float)$position['total'] == (float)$oi['total'])
        			continue;
        	}			 
        }

        $list[$i]['position'] = array(
            'width' => $widths['position'],
            'value' => $j,
            'border' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        $list[$i]['description'] = array(
            'width' => $widths['description'],
            //'value' => implode(array_fill(0, 50, 'x')),
            'value' => htmlspecialchars_decode($position['name']) . PHP_EOL . $position['code'],
            'border' => 1,
            'align' => 'L',
            'font-size' => 7,
            //'font-family' => 'courier',
        );

    if ($calc['draw_recipient_code']) {
        $list[$i]['recipient_code'] = array(
        		'width' => $widths['recipient_code'],
        		//'value' => implode(array_fill(0, 50, 'x')),
        		'value' => $position['recipient_code'],
        		'border' => 1,
        		'align' => 'C',
        		'font-size' => 7,
        		//'font-family' => 'courier',
        );
    }
        $list[$i]['quantity'] = array(
            'width' => $widths['quantity'],
            'value' => $position['quantity'] . PHP_EOL . $position['unit_name'],
            'border' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        /*
        $list[$i]['unit'] = array(
            'width' => $widths['unit'],
            'value' => $position['unit_id'],
            'border' => 1,
            'align' => 'C',
            'font-size' => 7,
        );
        */

        if ($calc['draw_discount']) {
            $list[$i]['draw_discount'] = array(
                'width' => $widths['draw_discount'],
                //'value' => format_number((100 * $position['price']) / (100 - $position['discount'])) . PHP_EOL . format_number($position['discount']),
                'value' => format_number($position['startprice']) . PHP_EOL . format_number($position['discount']),
                'border' => 1,
                'align' => 'R',
                'font-size' => 7,
            );
        }

        $list[$i]['unit_price'] = array(
            'width' => $widths['unit_price'],
            //'value' => format_number($position['price']),
            'value' => format_number($position['subprice']),
            'border' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        //$price_total = $position['price'] * $position['quantity'];
        $price_total = $position['subtotal'];

        $list[$i]['unit_price_total'] = array(
            'width' => $widths['unit_price_total'],
            'value' => format_number($price_total),
            //'value' => format_number($position['subtotal']),
            'border' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        $list[$i]['vat_id'] = array(
            'width' => $widths['vat_id'],
            'value' => format_number($position['vat_value']),
            'border' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        // $vat_value = round($price_total * ($position['vat_value'] / 100), 2);
           $vat_value = round($position['total'] - $position['subtotal'], 2);

        $list[$i]['vat_value'] = array(
            'width' => $widths['vat_value'],
            'value' => format_number($vat_value),
            //'value' => format_number($position['total'] - $position['subtotal']),
            'border' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        $list[$i]['total'] = array(
            'width' => $widths['total'],
            //'value' => format_number($price_total + $vat_value),
            'value' => format_number($position['total']),
            'border' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        $totals[$position['vat_id']]['price'] += $price_total;
        $totals[$position['vat_id']]['total'] += $price_total + $vat_value;
        $totals[$position['vat_id']]['vat'] += $vat_value;

        $sum_total += $price_total + $vat_value;
        $sum_netto += $price_total;

        
        if ($this->type == "correct") {
            $i++;

			$r = $oi; //oi! oi! oi!
			
            if ($position['id'] == $position['item_id']) {
                $ssss = "t";
            }

            $list[$i]['position'] = array(
                'width' => $widths['position'],
                'value' => '',
                'border' => 1,
                'align' => 'R',
                'font-size' => 7,
            );

            $list[$i]['description'] = array(
                'width' => $widths['description'],
                'value' => "bylo" . $ssss,
                'border' => 1,
                'align' => 'L',
                'font-size' => 7,
            );

            if ($calc['draw_recipient_code']) {
            	$list[$i]['recipient_code'] = array(
            			'width' => $widths['recipient_code'],
            			//'value' => implode(array_fill(0, 50, 'x')),
            			'value' => $position['recipient_code'],
            			'border' => 1,
            			'align' => 'C',
            			'font-size' => 7,
            			//'font-family' => 'courier',
            	);
            }

            $list[$i]['quantity'] = array(
                'width' => $widths['quantity'],
                'value' => (int) $r['quantity'] . PHP_EOL . $lv['ecmproducts_unit_dom'][$r['dd_unit_id']],
                'border' => 1,
                'align' => 'R',
                'font-size' => 7,
            );


            $list[$i]['unit_price'] = array(
                'width' => $widths['unit_price'],
                'value' => format_number($r['subprice']),
                'border' => 1,
                'align' => 'R',
                'font-size' => 7,
            );

            $list[$i]['unit_price_total'] = array(
                'width' => $widths['unit_price_total'],
                'value' => format_number($r['subtotal']),
                'border' => 1,
                'align' => 'R',
                'font-size' => 7,
            );

            $list[$i]['vat_id'] = array(
                'width' => $widths['vat_id'],
                'value' => format_number($r['ecmvat_value']),
                'border' => 1,
                'align' => 'R',
                'font-size' => 7,
            );

            $vat_value = round($r['subtotal'] - $r['total']);

            $list[$i]['vat_value'] = array(
                'width' => $widths['vat_value'],
                'value' => format_number($r['total']-$r['subtotal']),
                'border' => 1,
                'align' => 'R',
                'font-size' => 7,
            );

            $list[$i]['total'] = array(
                'width' => $widths['total'],
                'value' => format_number($r['total']),
                'border' => 1,
                'align' => 'R',
                'font-size' => 7,
            );

            $totals[$position['vat_id']]['price'] -= $r['subtotal'];
            $totals[$position['vat_id']]['total'] -= $r['total'];
            $totals[$position['vat_id']]['vat'] -= $vat_value;

            $sum_total -= $r['total'];
            $sum_netto -= $r['subtotal'];
        }        
        $i++;
        $j++;
    }
}
$pdf->Ln(4);
global $current_user;
//if ($current_user->id=='1') die();
if(strlen($wys) > 70 || strlen($buyer) > 70 || strlen($address) > 70) {
    $pdf->Ln(6);
}

$pdf->setX(7);

$pdf->DrawTable($list, array(0));


/* EOF: Position list. */
$pdf->Ln(1);

$pdf->setX(10);

//$pdf->SetFont('arialpl', '', '6');
//$pdf->Cell(25, 4, 'Waga całkowita netto: ', 0, 0, 'L', 1);

//$pdf->SetFont('arialpl', 'B', '6');
//$pdf->Cell(10, 4, format_number($calc['weight_netto']) . ' KG', 0, 0, 'L', 1);

$pdf->Ln(4);

$pr = ($pdf->fw - $pdf->lMargin - $pdf->rMargin) / 100;


//$q = 'SELECT i.`document_no` FROM `ecmprepaymentinvoices` AS i WHERE i.`ecmsale_id` IN (SELECT DISTINCT(ii.`parent_doc_id`) FROM `ecminvoiceoutitems` AS ii JOIN `ecminvoiceouts` AS i ON ii.`ecminvoiceout_id` = i.`id` WHERE i.`id` = \'' . $this->id . '\' AND ii.`parent_doc_type` = \'EcmSales\');';
//$rr_prepayment = $db->fetchByAssoc($db->query($q));

$summary = array();

$i = 0;

//echo '<pre>' . var_export($totals, true) . '</pre>';
//exit;

if ($calc['vats']) {
//    $summary[] = array(
//        'subtotal1' => array(
//            'width' => 42,
//            'value' => $mod_strings['LBL_PDF_TOTAL'],
//            'background' => array(255, 255, 255),
//            'border' => 1,
//            'overflow' => 1,
//            'align' => 'L',
//            'font-size' => 7,
//        ),
//        'subtotal2' => array(
//            'width' => 14,
//            'value' => $calc['subtotal'],
//            'border' => 1,
//            'overflow' => 1,
//            'align' => 'R',
//            'font-size' => 7,
//        ),
//    );

    $summary[$i]['fix'] = array(
        'width' => $widths['fix'],
        'value' => '',
        'border' => 0,
        'overflow' => 1,
        'align' => 'C',
        'font-style' => 'b',
        'font-size' => 7,
    );

    $summary[$i]['vat_rate'] = array(
        'width' => $widths['vat_rate'],
        'value' => $mod_strings['LBL_PDF_LIST_VAT_RATE'],
        'border' => 1,
        'overflow' => 1,
        'align' => 'C',
        'font-style' => 'b',
        'font-size' => 7,
    );

    $summary[$i]['netto_total'] = array(
        'width' => $widths['netto_total'],
        'value' => $mod_strings['LBL_PDF_LIST_NETTO_TOTAL'], //$mod_strings['LBL_PDF_LIST_TOTAL_PRICE'],
        'background' => array(255, 255, 255),
        'border' => 1,
        'overflow' => 1,
        'align' => 'C',
        'font-style' => 'b',
        'font-size' => 7,
    );

    $summary[$i]['vat_total'] = array(
        'width' => $widths['vat_total'],
        'value' => $mod_strings['LBL_PDF_LIST_VAT_TOTAL'],
        'background' => array(255, 255, 255),
        'border' => 1,
        'overflow' => 1,
        'align' => 'C',
        'font-style' => 'b',
        'font-size' => 7,
    );

    $summary[$i]['brutto_total'] = array(
        'width' => $widths['brutto_total'],
        'value' => $mod_strings['LBL_PDF_LIST_BRUTTO_TOTAL'],
        'border' => 1,
        'overflow' => 1,
        'align' => 'C',
        'font-style' => 'b',
        'font-size' => 7,
    );

    foreach ($calc['vats'] as $key => $value) {
        $i++;

        $qr = "SELECT id, name, value FROM ecmvats WHERE id = '" . $key . "'";
        $r = $db->fetchByAssoc($db->query($qr));

        $summary[$i]['fix'] = array(
            'width' => $widths['fix'],
            'value' => '',
            'border' => 0,
            'overflow' => 1,
            'align' => 'C',
            'font-style' => 'b',
            'font-size' => 7,
        );

        $summary[$i]['vat_rate'] = array(
            'width' => $widths['vat_rate'],
            'value' => format_number($r['value']),
            'background' => array(255, 255, 255),
            'border' => 1,
            'overflow' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        $summary[$i]['netto_total'] = array(
            'width' => $widths['netto_total'],
            'value' => format_number($totals[$r['id']]['price']),
            'background' => array(255, 255, 255),
            'border' => 1,
            'overflow' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        $cVatPlnTmp = $totals[$r['id']]['price'] * ($r['value']/100) ;
        $cVatPln += $cVatPlnTmp * $this->currency_value_nbp;

        // echo '<pre>' . $cVatPlnTmp . '</pre>';
        $summary[$i]['vat_total'] = array(
            'width' => $widths['vat_total'],
            'value' => format_number($cVatPlnTmp),
            'background' => array(255, 255, 255),
            'border' => 1,
            'overflow' => 1,
            'align' => 'R',
            'font-size' => 7,
        );

        $summary[$i]['brutto_total'] = array(
            'width' => $widths['brutto_total'],
            'value' => format_number($totals[$r['id']]['price']+$cVatPlnTmp),
            'border' => 1,
            'overflow' => 1,
            'align' => 'R',
            'font-size' => 7,
        );
    }
}
$brutto = ($totals[$r['id']]['price']+$cVatPlnTmp) - $disc;
//if ($current_user->id=='1') die($sum_total);
$netto = $sum_netto;
$vvat = $cVatPlnTmp;

$i++;

$summary[$i]['fix'] = array(
    'width' => $widths['fix'],
    'value' => '',
    'border' => 0,
    'overflow' => 1,
    'align' => 'C',
    'font-style' => 'b',
    'font-size' => 7,
);

$summary[$i]['vat_rate'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['vat_rate'],
    'value' => $mod_strings['LBL_PDF_LIST_SUMMARY_TOTAL'],
    'border' => 1,
    'overflow' => 1,
    'align' => 'C',
    'font-size' => 7,
    'font-style' => 'b',
);

$summary[$i]['netto_total'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['netto_total'],
    'value' => format_number($netto),
    'border' => 1,
    'overflow' => 1,
    'align' => 'R',
    'font-size' => 7,
    'font-style' => 'b',
);

$summary[$i]['vat_total'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['vat_total'],
    'value' => format_number($vvat),
    'border' => 1,
    'overflow' => 1,
    'align' => 'R',
    'font-size' => 7,
    'font-style' => 'b',
);

$summary[$i]['brutto_total'] = array(
    'background' => array(233, 233, 233),
    'width' => $widths['brutto_total'],
    'value' => format_number($brutto),
    'border' => 1,
    'align' => 'R',
    'font-size' => 7,
    'font-style' => 'b',
);

// echo '<pre>' . var_export($this->prepaid, true) . '</pre>';
// exit;

if($this->prepaid_nr && $this->prepaid) {
    $i++;

    $summary[$i]['fix'] = array(
        'width' => $widths['fix'],
        'value' => $this->prepaid_nr ? ($mod_strings['LBL_PDF_PREPAID_DOCUMENTS'] . ': ' . $this->prepaid_nr) : '',
        'border' => 0,
        'overflow' => 1,
        'align' => 'L',
        'font-style' => '',
        'font-size' => 7,
    );

    $summary[$i]['vat_rate'] = array(
        'width' => $widths['vat_rate'],
        'value' => format_number(23),
        'background' => array(255, 255, 255),
        'border' => 1,
        'overflow' => 1,
        'align' => 'R',
        'font-size' => 7,
    );

    $summary[$i]['netto_total'] = array(
        'width' => $widths['netto_total'],
        'value' => format_number(-($this->prepaid / 1.23)),
        'background' => array(255, 255, 255),
        'border' => 1,
        'overflow' => 1,
        'align' => 'R',
        'font-size' => 7,
    );

        $cVatPlnTmp = number_format(($this->prepaid * 0.23) / 1.23, 2);
        $cVatPln -= $cVatPlnTmp * $this->currency_value_nbp;

        // echo '<pre>' . $cVatPlnTmp . '</pre>';
    $summary[$i]['vat_total'] = array(
        'width' => $widths['vat_total'],
        'value' => format_number(-($cVatPlnTmp)),
        'background' => array(255, 255, 255),
        'border' => 1,
        'overflow' => 1,
        'align' => 'R',
        'font-size' => 7,
    );

    $summary[$i]['brutto_total'] = array(
        'width' => $widths['brutto_total'],
        // 'value' => format_number(-$this->prepaid ),
        'value' => format_number(-$this->prepaid ),
        'border' => 1,
        'overflow' => 1,
        'align' => 'R',
        'font-size' => 7,
    );

    $i++;

    $summary[$i]['fix'] = array(
        'width' => $widths['fix'],
        'value' => '',
        'border' => 0,
        'overflow' => 1,
        'align' => 'C',
        'font-style' => 'b',
        'font-size' => 7,
    );

    $summary[$i]['vat_rate'] = array(
        'background' => array(233, 233, 233),
        'width' => $widths['vat_rate'],
        'value' => $mod_strings['LBL_PDF_LIST_SUMMARY_TOTAL'],
        'border' => 1,
        'overflow' => 1,
        'align' => 'C',
        'font-size' => 7,
        'font-style' => 'b',
    );

    $summary[$i]['netto_total'] = array(
        'background' => array(233, 233, 233),
        'width' => $widths['netto_total'],
        'value' => format_number($netto - ($this->prepaid / 1.23)),
        'border' => 1,
        'overflow' => 1,
        'align' => 'R',
        'font-size' => 7,
        'font-style' => 'b',
    );

    $summary[$i]['vat_total'] = array(
        'background' => array(233, 233, 233),
        'width' => $widths['vat_total'],
        'value' => format_number($vvat - (($this->prepaid * 0.23) / 1.23)),
        'border' => 1, 'overflow' => 1,
        'align' => 'R',
        'font-size' => 7,
        'font-style' => 'b',
    );

    $summary[$i]['brutto_total'] = array(
        'background' => array(233, 233, 233),
        'width' => $widths['brutto_total'],
        'value' => format_number($brutto - $this->prepaid),
        'border' => 1,
        'align' => 'R',
        'font-size' => 7,
        'font-style' => 'b',
    );
}

// ~~~~~~~~~~~~~~

/*
echo '<pre>' . var_export($pdf->GetY(), true). '</pre>';
echo '<pre>' . var_export($pdf->fh, true). '</pre>';
echo '<pre>' . var_export($pdf->bMargin, true). '</pre>';

exit;
*/
//if ($this->currency_symbol == "USD") {
//    $pdf->SetX(103);
//} else {
$pdf->SetX(10);
//}
//
//echo '<pre>' . var_export($summary, true) . '</pre>';exit;

$pdf->DrawTable($summary);

//$pdf->Ln(2);