<?php
/**
 * Šalje radni nalog emailom
 */
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['radni_nalog_id']) && isset($_GET['email_to'])){
	$radni_nalog_id = intval($_GET['radni_nalog_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 = 'radni-nalog.pdf';
	
	$l_email_sender = get_item('select value from settings where name = "mailer.email" ');
	if(empty($l_email_sender)) $l_email_sender = 'prometi@itr.hr';
	$l_email_name = get_item('select value from settings where name = "mailer.name" ');
	
	$l_to = $_GET['email_to'];
	$l_radni_nalog = get_item('select number from radni_nalogs where id = '.$radni_nalog_id);
	$l_customer = get_item('select name from customers where id = (select customer_id from radni_nalogs where id = '.$radni_nalog_id.')');
	
	// Provjeri postoji li PDF (generiran prije slanja)
	$has_pdf = is_file($l_path.$l_name) && filesize($l_path.$l_name) > 100;
	
	if($has_pdf){
		// Šalji s PDF prilogom
		$is_sent = mail_attachment($l_name, $l_path,
			$l_to, $l_email_sender, $l_email_name, $l_email_sender, 'Radni nalog '.$l_radni_nalog,
			'Po&#353;tovani,<br><br>U privitku je radni nalog.<br><br>Srdacan pozdrav,<br>'.$l_email_name);
	} else {
		// Šalji bez PDF priloga
		$is_sent = @mail($l_to, 'Radni nalog '.$l_radni_nalog,
			'Po&#353;tovani, u privitku je radni nalog. Srdacan pozdrav, '.$l_email_name,
			'From: '.$l_email_sender);
	}
	
	if($is_sent){
		$result = 1;
	}
}

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

echo json_encode($la_data);
exit;
?>
