<?php
/**
 * Generira PDF ponude i sprema u res/files/ponuda.pdf
 * Koristi istu logiku kao print_offer funkcija
 */
header("Content-Type: application/json; charset=utf-8");

$la_tmp = explode('/app/', $_SERVER['SCRIPT_FILENAME']);
$g_path = $la_tmp[0].'/app/webroot/iso/my/';

include $g_path."u_globals.php";
include $g_path."html/f.php";
include $g_path."u_spoj_na_bazu.php";

$can_live_alone = 1;
include $g_path."u_headers.php";

$result = 0;

if(isset($_GET['offer_id'])){
	$offer_id = intval($_GET['offer_id']);
	$g_path_abs = get_item('select value from settings where name = "putanja.abs" ');
	$l_path = $g_path_abs.'app/webroot/res/files/';
	$l_name = 'ponuda_'.$offer_id.'.pdf';
	
	// Uključi FPDF i Document klasu
	require_once($g_path_abs.'app/libs/fpdf/fpdf.php');
	require_once($g_path_abs.'app/libs/qrcode/tcpdf_barcodes_2d.php');
	
	// Document klasa
	class Document extends FPDF {
		var $fut1,$fut2;
		function __construct($h="",$f1="",$f2="") {
			$this->fut1=$f1;
			$this->fut2=$f2;
			parent::__construct();
		}
		function Header() {
			$this->SetFont('Helvetica','B',12);
		}
		function Footer() {
			$this->SetY(-20);
			$this->SetFont('Helvetica','',8);
			if($this->CurOrientation == 'P'){
				$this->Cell(190,0,'','T');
			}else{
				$this->Cell(280,0,'','T');
			}
			$this->Ln();
			$this->SetY(-20);
			$this->SetX(-200);
			if($this->CurOrientation == 'P'){
				$this->Cell(190,4,'Stranica: '.$this->PageNo().'/{nb}',0,0,'R');
			}else{
				$this->Cell(280,4,'Stranica: '.$this->PageNo().'/{nb}',0,0,'R');
			}
			$this->Ln();
			$this->Cell(190,4,$this->fut1,0,0,'C');
		}
	}
	
	// Helper funkcija za UTF-8
	function _utf8ToIso($text) {
		if (empty($text)) return '';
		$search = array('č', 'ć', 'š', 'ž', 'đ', 'Č', 'Ć', 'Š', 'Ž', 'Đ');
		$replace = array('c', 'c', 's', 'z', 'd', 'C', 'C', 'S', 'Z', 'D');
		return str_replace($search, $replace, $text);
	}
	
	// Dohvati podatke
	$g_v = get_item('select value from settings where name = "valuta" ');
	if(empty($g_v)) $g_v = 'EUR';
	
	$restFooter = get_item('select value from settings where name = "invoice.footer" ');
	$restName = get_item('select value from settings where name = "general.name" ');
	$restpost = get_item('select value from settings where name = "general.post" ');
	$restComm = get_item('select value from settings where name = "general.resort" ');
	$restStreet = get_item('select value from settings where name = "general.street" ');
	$restStrNum = get_item('select value from settings where name = "general.str_num" ');
	$restStrNumMark = get_item('select value from settings where name = "general.str_num_mark" ');
	$restPlaceid = get_item('select value from settings where name = "general.placeid" ');
	
	// Dohvati ponudu
	$offer = get_row('select * from offers where id = '.$offer_id);
	$customer = get_row('select * from customers where id = '.$offer['customer_id']);
	$items = get_rows('select oi.*, a.name as article_name, a.barcode, 
		au.marka, au.model, au.registarska_oznaka,
		u.naziv_uredjaja, u.serijski_broj
		from offer_items oi 
		left join articles a on a.id = oi.article_id
		left join automobils au on au.id = oi.automobil_id
		left join uredjajs u on u.id = oi.uredjaj_id
		where oi.offer_id = '.$offer_id);
	
	if($offer){
		$doc = new Document("", $restFooter, "");
		$doc->AddPage();
		
		// Header
		$doc->Cell(100);
		$doc->Cell(0, 5, _utf8ToIso($restName), 0, 2);
		$doc->SetFont('Helvetica', '', 8);
		
		$adresa = $restpost . ' ' . $restComm . ',' . $restStreet . ' ' . $restStrNum . $restStrNumMark;
		$doc->Cell(0, 5, _utf8ToIso($adresa), 0, 2);
		$doc->Cell(0, 5, _utf8ToIso($restPlaceid), 0, 0);
		
		$doc->Ln(6);
		
		// Kupac i ponuda
		$doc->Ln();
		$doc->SetFont('Helvetica', 'B', 12);
		$doc->Cell(80, 8, _utf8ToIso($customer['name']), 'LTR', 0);
		$doc->Cell(20);
		$doc->SetFont('Helvetica', 'B', 10);
		$doc->Cell(80, 8, 'Ponuda *' . $offer['number'], 'LTRB', 0, 'C');
		
		$dt = date('d.m.Y', strtotime($offer['created']));
		
		$doc->Ln();
		$doc->SetFont('Helvetica', 'B', 8);
		$doc->Cell(80, 5, '  ', 'LR', 0);
		$doc->Cell(20);
		$doc->SetFont('Courier', '', 8);
		$doc->Cell(80, 5, "Broj dokumenta:    " . $offer['number'], 'LR', 0);
		
		$doc->Ln();
		$doc->SetFont('Helvetica', 'B', 8);
		$doc->Cell(80, 5, _utf8ToIso($customer['address'] . ' ' . $customer['city']), 'LR', 0);
		$doc->Cell(20);
		$doc->SetFont('Courier', '', 8);
		$doc->Cell(80, 5, "Datum dokumenta:   " . $dt, 'LBR', 0);
		$doc->Ln();
		
		$doc->SetFont('Helvetica', '', 8);
		$doc->Cell(80, 5, "OIB: " . $customer['oib'], 'LRB', 0, 'R');
		$doc->Ln(10);
		
		// Tablica stavki
		$doc->SetFont('Helvetica', 'B', 8);
		$doc->SetFillColor(255, 255, 255);
		
		$header = array('RB', 'Naziv artikla/usluge', 'Kolicina', 'PC', 'Rabat %', 'Cijena', 'Vrijednost ' . $g_v);
		$w = array(10, 70, 22, 22, 18, 22, 26);
		
		for ($i = 0; $i < count($header); $i++)
			$doc->Cell($w[$i], 7, $header[$i], 0, 0, 'C', true);
		$doc->Ln();
		
		// Stavke
		$doc->SetFont('Helvetica', '', 8);
		$rb = 1;
		$uk = 0;
		
		foreach ($items as $item) {
			$tipStavke = isset($item['tip_stavke']) ? $item['tip_stavke'] : 'artikl';
			$naziv = '';
			
			if ($tipStavke == 'automobil' && !empty($item['marka'])) {
				$naziv = $item['marka'] . ' ' . $item['model'];
			} elseif ($tipStavke == 'uredjaj' && !empty($item['naziv_uredjaja'])) {
				$naziv = $item['naziv_uredjaja'];
			} else {
				$naziv = $item['article_name'];
			}
			
			$naziv = _utf8ToIso($naziv);
			
			$doc->Cell($w[0], 6, $rb, 0, 0, 'C');
			$doc->Cell($w[1], 6, $naziv, 0, 0, 'L');
			$doc->Cell($w[2], 6, number_format($item['amount'], 2, '.', ' '), 0, 0, 'R');
			$doc->Cell($w[3], 6, number_format($item['price_sell'], 2, '.', ' '), 0, 0, 'R');
			$doc->Cell($w[4], 6, number_format($item['discount'], 2, '.', ' '), 0, 0, 'R');
			$doc->Cell($w[5], 6, number_format($item['price_sell'] * (1 - $item['discount'] / 100), 2), 0, 0, 'R');
			$doc->Cell($w[6], 6, number_format($item['price_sell'] * $item['amount'] * (1 - $item['discount'] / 100), 2, '.', ' '), 0, 0, 'R');
			$doc->Ln();
			
			$rb++;
			$uk += $item['price_sell'] * $item['amount'] * (1 - $item['discount'] / 100);
		}
		
		// Ukupno
		$doc->Cell(190, 0, '', 'T');
		$doc->Ln();
		$doc->Cell(190 - $w[6]);
		$doc->Cell($w[6], 6, number_format($uk, 2, '.', ' '), 0, 0, 'R');
		
		$doc->Ln(20);
		$doc->Cell(65);
		$doc->Cell(50, 20, "Obradio", 'B', 0, 'C');
		
		// Spremi PDF
		$doc->Output($l_path.$l_name, 'F');
		
		if(is_file($l_path.$l_name) && filesize($l_path.$l_name) > 100){
			$result = 1;
		}
	}
}

$la_data = array();
$la_data['result'] = $result;
$la_data['file'] = isset($l_name) ? $l_name : '';

echo json_encode($la_data);
exit;
?>
