<?php
/**
 * Sprema PDF radnog naloga na server
 * Dohvaća PDF s print_work_order URL-a i sprema ga u res/files/
 */
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;
$message = '';

if(isset($_GET['radni_nalog_id'])){
	$radni_nalog_id = intval($_GET['radni_nalog_id']);
	$with_notes = isset($_GET['with_notes']) ? intval($_GET['with_notes']) : 0;
	
	// Destinacija
	$g_path_abs = get_item('select value from settings where name = "putanja.abs" ');
	$destination = $g_path_abs.'app/webroot/res/files/radni-nalog.pdf';
	
	// URL PDF-a - koristi hostname iz requesta
	$host = $_SERVER['HTTP_HOST'];
	$pdfUrl = 'http://'.$host.'/malo/reports/print_work_order/'.$radni_nalog_id.'/'.$with_notes;
	
	// Prenesi cookies iz trenutnog requesta
	$cookies = '';
	if(isset($_SERVER['HTTP_COOKIE'])){
		$cookies = $_SERVER['HTTP_COOKIE'];
	}
	
	// Koristi cURL s cookies
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $pdfUrl);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_COOKIE, $cookies);
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	
	$pdfContent = curl_exec($ch);
	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	$error = curl_error($ch);
	curl_close($ch);
	
	if ($pdfContent !== false && strlen($pdfContent) > 500) {
		// Provjeri da li je stvarno PDF (počinje s %PDF)
		if (substr($pdfContent, 0, 4) === '%PDF') {
			$saved = file_put_contents($destination, $pdfContent);
			
			if ($saved !== false) {
				$result = 1;
				$message = 'PDF spremljen: ' . $destination;
			} else {
				$message = 'Greška pri spremanju na disk';
			}
		} else {
			// Debug - spremi što smo dobili
			file_put_contents($g_path_abs.'app/webroot/res/files/debug_rn.html', $pdfContent);
			$message = 'Dohvaćeni sadržaj nije PDF (HTTP '.$httpCode.'). Prvih 100 znakova: '.substr($pdfContent, 0, 100);
		}
	} else {
		$message = 'Greška pri dohvaćanju: '.$error;
	}
}

$la_data = array();
$la_data['result'] = $result;
$la_data['message'] = $message;

echo json_encode($la_data);
exit;
?>
