<?php
function serviser($postdata, $primary, $xcrud){
	$bio = $postdata->get('ser_been');
	$fix = $postdata->get('ser_resio');
	if($bio == 1 OR $fix == 1)
	{
	$db = Xcrud_db::get_instance();
	$query = 'SELECT `sent_mail` FROM `tickets` WHERE id =' . $db->escape($primary);
    $db->query($query);
    $result = $db->result();
	foreach($result as $row){
    $service = $row['sent_mail'];
	echo $service;
	}
	//echo $service;
	//selektujem sve iz reda
	$query2 = 'SELECT lokal,opis,vreme_open,vreme_close,status,ser_punoime,ser_been,ser_resio ,slot.name as sname,category.name as deo,broj,serviser,manager,department.name  as dname  FROM `tickets` INNER JOIN `category` ON category.category_id = tickets.category INNER JOIN `department` ON department.department_id = tickets.department INNER JOIN `slot` ON slot.slot_id = tickets.aparat WHERE id =' .$db->escape($primary);
    $db->query($query2);
    $result1 = $db->result();
	foreach($result1 as $row){
    $odeljenje = $row['dname'];
	$opis = "Opis kvara: ".$row['opis'];
	$vreme = strtotime($row['vreme_open']);
	$vremeo = date('d-m-Y H:i:s',$vreme);
	$vremez = strtotime($row['vreme_close']);
	$vremec = date('d-m-Y H:i:s',$vremez);
	$lokal = $row['lokal'];
	$aparat = "Uredjaj/Igra: ".$row['sname']." ".$row['broj'];
	$ser_ime = $row['ser_punoime'];
	$bio = $row['ser_been'];
	$status = $row['ser_resio'];
	if($status == 1)
	{
		$status = "Status: OPRAVLJEN u ".$vremec;
	}
	else
	{
		$status = "Status: NIJE OPRAVLJEN";
	}
	$deo = "Deo na uredjaju/Igri: ".$row['deo'];
	}
	$futer_m = "OVO JE AUTOMATSKA PORUKA.  MOLIMO VAS DA NE ODGOVARATE NA NJU.";
	//selektujem kome saljem
	$sql = "SELECT email FROM users WHERE id IN (".$service.") AND e_send = 1";
	$db->query($sql);
	$res = $db->result();
	$to='';
	foreach($res as $row)
	{
	 if($to=='')//this prevents from inserting comma on before the first element
		{		 
        $to.=$row['email'];
		}
        else
		{		
        $to.=','.$row['email'];
		}
	}
	//echo $to;
	$subject = "Serviser: ".$ser_ime.' - Bio u lokalu: '.$lokal;
	$message = $status. "\r\n" ."Odeljenje: ".$odeljenje. "\r\n".$aparat. "\r\n" . $deo. "\r\n" .$opis. "\r\n" .$futer_m;
	echo $subject."<br>";
	echo $message;
	$headers = 'From: HELPDesk <service@balkanbet.biz>' . "\r\n" .
    'Reply-To: nenad@balkanbet.biz' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
	mail($to, $subject, $message, $headers);//saljem mail*/
	}
}

function hash_password($postdata, $primary, $xcrud){//update lozinke
    $pas = $xcrud->get_var('password');
	$pravi = $postdata->get('password');
	//echo $pravi;
	$sad = md5($pravi.$pas);
	//echo "<br>".$sad;
	if($pravi != '') {	
	$db = Xcrud_db::get_instance();
    $query = 'UPDATE users SET password =  \'' . $sad . '\' WHERE id =' . $db->escape($primary);
    $db->query($query);
    }
	}
function saljem_kvar($postdata, $primary, $xcrud){
	$db = Xcrud_db::get_instance();
    $query = 'SELECT `staff_id` FROM `department` WHERE `department_id` = ' . $postdata->get('department');
    $db->query($query);
    $result = $db->result();
	foreach($result as $row){
    $service = $row['staff_id'];
	}
	$query1 = 'UPDATE tickets SET serviser =  \'' . $service . '\' WHERE id =' . $db->escape($primary);
	$db->query($query1);
	//selektujem sve iz reda
	//$query2 = 'SELECT lokal,opis,vreme_open, slot.name as sname,category.name as deo,broj,serviser,manager FROM `tickets` INNER JOIN `category` ON category.category_id = tickets.category INNER JOIN `slot` ON slot.slot_id = tickets.aparat WHERE id =' .$db->escape($primary);
	$query2 = 'SELECT lokal,opis,vreme_open,department.name  as dname, slot.name as sname,category.name as deo,broj,serviser,manager FROM `tickets` INNER JOIN `category` ON category.category_id = tickets.category 
	INNER JOIN `department` ON department.department_id = tickets.department INNER JOIN `slot` ON slot.slot_id = tickets.aparat WHERE id =' .$db->escape($primary);
    $db->query($query2);
    $result1 = $db->result();
	foreach($result1 as $row){
	$odeljenje = $row['dname'];	
    $opis = "Opis kvara: ".$row['opis'];
	$vreme = strtotime($row['vreme_open']);
	$vremeo = date('d-m-Y H:i:s',$vreme);
	$lokal = $row['lokal'];
	$aparat = "Uredjaj/Igra: ".$row['sname']." ".$row['broj'];
	$deo = "Deo na uredjaju/Igri: ".$row['deo'];
	$ser = $row['serviser'];
	$man = $row['manager'];
	}
	//selektujem kome saljem
	if ($row['serviser'] !== "" AND $row['manager'] !== "")//ako nema ni jedan serviser
	{
	$sql = "SELECT id,email FROM users WHERE (id IN (".$ser.") OR id IN (".$man.")) AND e_send = 1";
	//$sql = "SELECT id,email FROM users WHERE (id IN (".$ser.") OR FIND_IN_SET(".$odeljenje.",`dept_to`)  AND e_send = 1";
	}
	else
	{
	$xcrud->set_exception('Nije dobro', 'Vasa poruka je uspešno prosledjena centru ali nije prosledjena mailom, molim Vas pozovite menadžara!', 'error');
	}	
	$db->query($sql);
	$res = $db->result();
	$to='';
	$ids=array(); 
	foreach($res as $row)
	{
	 $ids[]=$row['id']; 
	 if($to=='')//this prevents from inserting comma on before the first element
		{		 
        $to.=$row['email'];
		}
        else
		{		
        $to.=','.$row['email'];
		}
	}
	//echo $to;
	$poslao = implode(',', $ids);
	if($poslao != '')
	{	
	$query7 = 'UPDATE tickets SET sent_mail =  \'' . $poslao . '\' WHERE id =' . $db->escape($primary);
    $db->query($query7);
    }
	$futer_m = "OVO JE AUTOMATSKA PORUKA.  MOLIMO VAS DA NE ODGOVARATE NA NJU.";
	$subject = $lokal.' - '.$odeljenje.' - Prijava novog kvara';
	$message = "Ova poruka je generisana iz lokala: ".$lokal. " u " .$vremeo. "\r\n" . "Odeljenju: " .$odeljenje. "\r\n" .$aparat. "\r\n" . $deo. "\r\n" .$opis. "\r\n" .$futer_m;
	$headers = 'From: HELPDesk <service@balkanbet.biz>' . "\r\n" .
    'Reply-To: nenad@balkanbet.biz' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
	//echo $subject;
	//echo $message;
	mail($to, $subject, $message, $headers);//saljem mail
}

function publish_action($xcrud)
{
    if ($xcrud->get('primary'))
    {
        $db = Xcrud_db::get_instance();
        $query = 'UPDATE products SET `status` = b\'1\' WHERE id = ' . (int)$xcrud->get('primary');
        $db->query($query);
    }
}
function unpublish_action($xcrud)
{
    if ($xcrud->get('primary'))
    {
        $db = Xcrud_db::get_instance();
        $query = 'UPDATE products SET `status` = b\'0\' WHERE id = ' . (int)$xcrud->get('primary');
        $db->query($query);
    }
}
function publish_order($xcrud)
{
    if ($xcrud->get('primary'))
    {
        $db = Xcrud_db::get_instance();
        $query = 'UPDATE orders SET `status` = b\'1\' WHERE id = ' . (int)$xcrud->get('primary');
        $db->query($query);
    }
}
function unpublish_order($xcrud)
{
    if ($xcrud->get('primary'))
    {
        $db = Xcrud_db::get_instance();
        $query = 'UPDATE orders SET `status` = b\'0\' WHERE id = ' . (int)$xcrud->get('primary');
        $db->query($query);
    }
}
function exception_example($postdata, $primary, $xcrud)
{
    // get random field from $postdata
    $postdata_prepared = array_keys($postdata->to_array());
    shuffle($postdata_prepared);
    $random_field = array_shift($postdata_prepared);
    // set error message
    $xcrud->set_exception($random_field, 'This is a test error', 'error');
}

function test_column_callback($value, $fieldname, $primary, $row, $xcrud)
{
    return $value . ' - nice!';
}

function after_upload_example($field, $file_name, $file_path, $params, $xcrud)
{
    $ext = trim(strtolower(strrchr($file_name, '.')), '.');
    if ($ext != 'pdf' && $field == 'uploads.simple_upload')
    {
        unlink($file_path);
        $xcrud->set_exception('simple_upload', 'This is not PDF', 'error');
    }
}

function movetop($xcrud)
{
    if ($xcrud->get('primary') !== false)
    {
        $primary = (int)$xcrud->get('primary');
        $db = Xcrud_db::get_instance();
        $query = 'SELECT `officeCode` FROM `offices` ORDER BY `ordering`,`officeCode`';
        $db->query($query);
        $result = $db->result();
        $count = count($result);

        $sort = array();
        foreach ($result as $key => $item)
        {
            if ($item['officeCode'] == $primary && $key != 0)
            {
                array_splice($result, $key - 1, 0, array($item));
                unset($result[$key + 1]);
                break;
            }
        }

        foreach ($result as $key => $item)
        {
            $query = 'UPDATE `offices` SET `ordering` = ' . $key . ' WHERE officeCode = ' . $item['officeCode'];
            $db->query($query);
        }
    }
}
function movebottom($xcrud)
{
    if ($xcrud->get('primary') !== false)
    {
        $primary = (int)$xcrud->get('primary');
        $db = Xcrud_db::get_instance();
        $query = 'SELECT `officeCode` FROM `offices` ORDER BY `ordering`,`officeCode`';
        $db->query($query);
        $result = $db->result();
        $count = count($result);

        $sort = array();
        foreach ($result as $key => $item)
        {
            if ($item['officeCode'] == $primary && $key != $count - 1)
            {
                unset($result[$key]);
                array_splice($result, $key + 1, 0, array($item));
                break;
            }
        }

        foreach ($result as $key => $item)
        {
            $query = 'UPDATE `offices` SET `ordering` = ' . $key . ' WHERE officeCode = ' . $item['officeCode'];
            $db->query($query);
        }
    }
}

function show_description($value, $fieldname, $primary_key, $row, $xcrud)
{
    $result = '';
    if ($value == '1')
    {
        $result = '<i class="fa fa-check" />' . 'OK';
    }
    elseif ($value == '2')
    {
        $result = '<i class="fa fa-circle-o" />' . 'Pending';
    }
    return $result;
}

function custom_field($value, $fieldname, $primary_key, $row, $xcrud)
{
    return '<input type="text" readonly class="xcrud-input" name="' . $xcrud->fieldname_encode($fieldname) . '" value="' . $value .
        '" />';
}
function unset_val($postdata)
{
    $postdata->del('Paid');
}

function format_phone($new_phone)
{
    $new_phone = preg_replace("/[^0-9]/", "", $new_phone);

    if (strlen($new_phone) == 7)
        return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $new_phone);
    elseif (strlen($new_phone) == 10)
        return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $new_phone);
    else
        return $new_phone;
}

function statpanel($list, $xcrud)
{
    
	$nivo = $xcrud->get_var('level');
	$cek = $xcrud->get_var('korisnik');
	$iduser = $xcrud->get_var('userid');
	//echo $cek;
	$kogde = $xcrud->get_var('kome');
	//echo $kogde;
	$db = Xcrud_db::get_instance();
	switch ($nivo) 
	{
    case 1:
        $db->query("Select user_name from tickets where user_name = '$cek' AND status = 1"); // executes query, returns count of affected rows
        break;
    case 2:
        $db->query("Select * from tickets where find_in_set('$iduser',serviser) AND status = 1");
        break;
    case 3:
        if($cek == "milan"){
		$db->query("Select * from tickets where status = 1"); // executes query, returns count of affected rows	
		}
		else{
		$db->query("Select * from tickets where find_in_set('$iduser',sent_mail) AND status = 1 AND department IN $kogde"); // executes query, returns count of affected rows
		}
        break;
	case 6:
        if($cek == "milan"){
		$db->query("Select * from tickets where status = 1"); // executes query, returns count of affected rows	
		}
		else{
		$db->query("Select * from tickets where find_in_set('$iduser',sent_mail) AND status = 1"); // executes query, returns count of affected rows
		}
        break;	
	case 9:
        $db->query("Select * from tickets where find_in_set('$iduser',sent_mail) AND status = 1"); // executes query, returns count of affected rows
        break;
	}
	$zatvoren = count($db->result()); // loads results as list of arrays
	$db1 = Xcrud_db::get_instance();
	switch ($nivo) 
	{
    case 1:
        $db1->query("Select user_name from tickets where user_name = '$cek' AND status = 0");
        break;
    case 2:
        $db1->query("Select * from tickets where find_in_set('$iduser',serviser) AND status = 0");
        break;
    case 3:
        if($cek == "milan"){
		$db->query("Select * from tickets where status = 0"); // executes query, returns count of affected rows	
		}
		else{
		$db1->query("Select * from tickets where find_in_set('$iduser',sent_mail) AND status = 0 AND department IN $kogde"); // executes query, returns count of affected rows
		}
        break;
	case 6:
        if($cek == "milan"){
		$db->query("Select * from tickets where status = 0"); // executes query, returns count of affected rows	
		}
		else{
		$db1->query("Select * from tickets where find_in_set('$iduser',sent_mail) AND status = 0"); // executes query, returns count of affected rows
		}
        break;	
	case 9:
        $db1->query("Select * from tickets where find_in_set('$iduser',sent_mail) AND status = 0"); // executes query, returns count of affected rows
        break;
	}
	$otvoren = count($db1->result());
	$svega = $otvoren + $zatvoren;
	if ($otvoren > 0)
	{
	$procenat = FLOOR(($otvoren / ($zatvoren + $otvoren))*100);
	}
	else
	{
	$procenat =	0;
	}
	echo "<script>
	document.getElementById('otvoren').innerHTML = '$otvoren';
	document.getElementById('zatvoren').innerHTML = '$zatvoren';
	document.getElementById('svega').innerHTML = '$svega';
	document.getElementById('procenat').innerHTML = '$procenat %';
	</script>";
}	

function after_update_test($pd, $pm, $xc)
{
    $xc->search = 0;
}

function check_un($postdata, $primary, $xcrud)
{
        $db = Xcrud_db::get_instance();
        $query = 'SELECT `username` FROM `users` WHERE `username` = ' . $db->escape($postdata->get('username'));
        $db->query($query);
        $result = $db->result();
        $count = count($result);
		echo $count;
        if ($count > 0) {
        $xcrud->set_exception('username', 'This email address is already in use', 'error');
        }
}
function ime_cat_up($postdata, $primary, $xcrud)
{
        //$delovi = $postdata->get('Delovi');
		//echo $delovi;
		$db = Xcrud_db::get_instance();
        $query = 'UPDATE slot_cat INNER JOIN category USING(category_id) SET slot_cat.name_cat = category.name';
        $db->query($query);
        //$result = $db->result();
        //$count = count($result);
		//var_dump ($result);
		//echo 'ok';
        
}

function ime_cat_in($postdata, $primary, $xcrud)
{
        //$delovi = $postdata->get('Delovi');
		//echo $delovi;
		$db = Xcrud_db::get_instance();
        $query = 'UPDATE slot_cat INNER JOIN category USING(category_id) SET slot_cat.name_cat = category.name';
        $db->query($query);
        //$result = $db->result();
        //$count = count($result);
		//var_dump ($result);
		//echo 'ok';
        
}
function check_meters($postdata, $meters){
	$in = $postdata->get('in_m');
	$out = $postdata->get('out_m');
	$bet = $postdata->get('bet_m');
	$win = $postdata->get('win_m');
	$inout = $in - $out;
	$betwin = $bet - $win;
	$jpot = $postdata->get('jackpot');
	$notes = $postdata->get('Note');
	if($inout <> $betwin){
		$meters->set_exception('Verifikacija', 'Upisani podaci nisu dobri, "in-out" mora biti isto kao "bet-win"!', 'error');
		echo "Razlika In-Out = ".$inout."<br>";
		echo "Razlika Bet-Win = ".$betwin;
	}
	$rc = $postdata->get('rc');
	$note = $postdata->get('Notes');
    if($rc ==  '1' && $notes == ''){ 
        $meters->set_exception('Verifikacija', 'Molimo Vas, da popunite napomenu kad je čekirano RAM CLEAR polje!', 'note');
    }
}
