<?php
class SettingsController extends AppController
{

	var $name = 'Settings';

	//function settings() {
	//}


	var $paginate = array(
		'limit' => 250

	);

	var $components = array(
		'Filter' => array(
			'index,updatePrice' => array(
				'name' => array(
					'form_options' => array('label' => 'Name'),
					'filter_options' => array('fields' => array('Setting.name'), 'operator' => 'like^'),
				),
			)
		),
	);



	function beforeFilter()
	{
		$l_id = $this->Session->read('Auth.User.id');
		if (empty($l_id)) {
			$this->redirect(array('action' => '../home/'));
			return;
		}

		$rez = mysql_query('select user_level_id from users where id = ' . $l_id);
		$row = mysql_fetch_array($rez);

		if ($row['user_level_id'] == 30) {
			$this->Session->setFlash(__('Nemate ovlasti za pristup postavkama!', true));
			$this->redirect(array('action' => '../home/'));
			return;
		}
	}




	function index()
	{
		$this->Auth->allow('update', 'updatePrice');
		$this->Auth->mapActions(array('updatePrice' => 'update'));
		$this->set('items', $this->paginate());
	}

	function view($id = null)
	{
		$this->set('item', $item);
	}

	function updatePrice($num)
	{

	}
	function add()
	{

	}


	function get_item($sql, $db_res = "", $test_mode = 0)
	{

		if ($db_res) {
			$rez = mysql_query($sql, $db_res);
		} else {
			$rez = mysql_query($sql);
		}

		// ova funkcija uvijek mora vratiti samo nula ili jedan redak
		$l_br_redaka = mysql_num_rows($rez);
		switch ($l_br_redaka) {
			case 0:
				$result = "";
				break;
			case 1:
				$row = mysql_fetch_array($rez);
				$result = trim($row[0]);
				break;
			default:
				if ($test_mode == 1) {
					die("Funkcija <i>get_item()</i> vratila je više od jednog retka iako je dozvoljeno vraćanje samo jednog" .
						"<br><br> &nbsp; :::=>> <b>" . $sql . "</b>");
				}
		}

		return $result;
	}

	function get_data($sql, $force_array = 0, $db_res = "")
	{
		$la_polje = array();

		if ($db_res) {
			$rez = mysql_query($sql, $db_res);
		} else {
			$rez = mysql_query($sql);
		}
		//echo $sql."\n<br><br>";
		//echo mysql_errno() . ": " . mysql_error() . "\n<br><br>";


		$l_br_polja = mysql_num_fields($rez);
		for ($i = 0; $i < $l_br_polja; $i++) {
			array_push($la_polje, mysql_field_name($rez, $i));
		}

		$l_br_redaka = mysql_num_rows($rez);
		if ($force_array && $l_br_redaka == 1) {
			// uvijek vrati array
			$l_br_redaka = -1;
		}
		switch ($l_br_redaka) {
			case 0:
				$result = array("");
				break;
			case 1:
				$row = mysql_fetch_array($rez);
				for ($i = 0; $i < $l_br_polja; $i++) {
					$result[$la_polje[$i]] = $row[$i];
				}
				break;
			default:
				for ($i = 0; $i < $l_br_polja; $i++) {
					$result[$la_polje[$i]] = array();
				}
				while ($row = mysql_fetch_array($rez)) {
					for ($i = 0; $i < $l_br_polja; $i++) {
						array_push($result[$la_polje[$i]], $row[$i]);
					}
				}
		}
		return $result;
	}

	function sql_exe($sql, $last_id = false, $db_res = "")
	{
		$db_res == "" ? $result = mysql_query($sql) : $result = mysql_query($sql, $db_res);
		if ($last_id && $result) {
			$result = mysql_insert_id();
		}
		return $result;
	}

	function slozi_stanje_robe_ugo($rbr_artikl = 0, $slozi_bez_racuna = 0)
	{

		// za $rbr_artikl = 0, preslaguju se svi... inace se preslaguje samo onaj ciji je rbr naveden

		if ($rbr_artikl > 0) {
			$l_uvjet_1 = ' where id = ' . $rbr_artikl;
			$l_uvjet_2 = ' and receiving_items.article_id = ' . $rbr_artikl;
			$l_uvjet_3 = ' and product_items.article_id = ' . $rbr_artikl;
			$l_uvjet_4 = ' and product_items.article_id = ' . $rbr_artikl;
		} else {
			$l_uvjet_1 = '';
			$l_uvjet_2 = '';
			$l_uvjet_3 = '';
			$l_uvjet_4 = '';
		}

		$l_sql = 'update articles set amount = 0 ' . $l_uvjet_1;
		$this->sql_exe($l_sql);

		$x = $this->get_data('select receiving_items.article_id, sum(receiving_items.amount) as s1 ' .
			' from receivings, receiving_items ' .
			' where receivings.id = receiving_items.receiving_id ' .
			' and receivings.type in (0, 4, 6) ' .
			' and receivings.posted = 1 ' .
			$l_uvjet_2 .
			' group by receiving_items.article_id ' .
			' order by receiving_items.article_id ', 1);
		if (empty($x['article_id'])) {
			$x = array();
			$x['article_id'] = array();
			$x['s1'] = array();
		}

		$y = $this->get_data('select receiving_items.article_id, sum(abs(receiving_items.amount)) as s1 ' .
			' from receivings, receiving_items ' .
			' where receivings.id = receiving_items.receiving_id ' .
			' and receivings.type in (1, 2, 3) ' .
			' and receivings.posted = 1 ' .
			$l_uvjet_2 .
			' group by receiving_items.article_id ' .
			' order by receiving_items.article_id ', 1);

		for ($i = 0; isset($y['article_id']) && $i < sizeof($y['article_id']); $i++) {
			$l_pos = array_search($y['article_id'][$i], $x['article_id']);
			if ($l_pos === false) {
				$x['article_id'][] = $y['article_id'][$i];
				$x['s1'][] = -1 * abs($y['s1'][$i]);
			} else {
				$x['s1'][$l_pos] -= abs($y['s1'][$i]);
			}
		}





		if ($slozi_bez_racuna == 0) {

			$z = $this->get_data('select product_items.article_id, sum(sale_items.amount * product_items.amount) as s1 ' .
				' from sales, sale_items, product_items ' .
				' where sales.id = sale_items.sale_id ' .
				' and sale_items.product_id = product_items.product_id ' .
				$l_uvjet_3 .
				' group by product_items.article_id ' .
				' order by product_items.article_id ', 1);

			for ($i = 0; isset($z['article_id']) && $i < sizeof($z['article_id']); $i++) {

				if (isset($x['article_id'])) {
					$l_pos = array_search($z['article_id'][$i], $x['article_id']);
				} else {
					$l_pos = false;
				}

				if ($l_pos === false) {
					$x['article_id'][] = $z['article_id'][$i];
					$x['s1'][] = -1 * $z['s1'][$i];
				} else {
					$x['s1'][$l_pos] -= $z['s1'][$i];
				}
			}

		}





		$z = $this->get_data('select product_items.article_id, sum(abs(medju_items.kolicina) * product_items.amount) as s1 ' .
			' from medjus, medju_items, product_items ' .
			' where medjus.id = medju_items.medju_id ' .
			' and medju_items.product_id = product_items.product_id ' .
			$l_uvjet_4 .
			' and medjus.posted = 1 ' .
			' and medjus.povrat = 0 ' .
			' group by product_items.article_id ' .
			' order by product_items.article_id ', 1);

		for ($i = 0; isset($z['article_id']) && $i < sizeof($z['article_id']); $i++) {

			if (isset($x['article_id'])) {
				$l_pos = array_search($z['article_id'][$i], $x['article_id']);
			} else {
				$l_pos = false;
			}

			if ($l_pos === false) {
				$x['article_id'][] = $z['article_id'][$i];
				$x['s1'][] = -1 * $z['s1'][$i];
			} else {
				$x['s1'][$l_pos] -= $z['s1'][$i];
			}
		}



		for ($i = 0; isset($x['article_id']) && $i < sizeof($x['article_id']); $i++) {
			if ($rbr_artikl == 0 || ($rbr_artikl > 0 && $x['article_id'][$i] == $rbr_artikl)) {
				// usluge uvijek nek ostanu na nula (odnosno, nikad ih ovdje nemoj promijeniti)
				$l_sql = 'update articles set amount = ' . $x['s1'][$i] . ' where id = ' . $x['article_id'][$i] . ' and isService = 0 ';
				$this->sql_exe($l_sql);
			}
		}

	}




	function slozi_stanje_keub_ugo($rbr_artikl = 0)
	{

		// za $rbr_artikl = 0, preslaguju se svi... inace se preslaguje samo onaj ciji je rbr naveden

		if ($rbr_artikl > 0) {
			$l_uvjet_1 = ' where id = ' . $rbr_artikl;
			$l_uvjet_2 = ' and receiving_items.article_id = ' . $rbr_artikl;
			$l_uvjet_3 = ' and product_items.article_id = ' . $rbr_artikl;
			$l_uvjet_4 = ' and product_items.article_id = ' . $rbr_artikl;
		} else {
			$l_uvjet_1 = '';
			$l_uvjet_2 = '';
			$l_uvjet_3 = '';
			$l_uvjet_4 = '';
		}

		$l_sql = 'update articles set amount = 0 ' . $l_uvjet_1;
		$this->sql_exe($l_sql);

		$x = $this->get_data('select receiving_items.article_id, sum(receiving_items.amount) as s1 ' .
			' from receivings, receiving_items ' .
			' where receivings.id = receiving_items.receiving_id ' .
			' and receivings.type in (0, 4) ' .
			' and receivings.posted = 1 ' .
			$l_uvjet_2 .
			' group by receiving_items.article_id ' .
			' order by receiving_items.article_id ', 1);
		if (empty($x['article_id'])) {
			$x = array();
			$x['article_id'] = array();
			$x['s1'] = array();
		}

		$y = $this->get_data('select receiving_items.article_id, sum(abs(receiving_items.amount)) as s1 ' .
			' from receivings, receiving_items ' .
			' where receivings.id = receiving_items.receiving_id ' .
			' and receivings.type in (1, 2, 3) ' .
			' and receivings.posted = 1 ' .
			$l_uvjet_2 .
			' group by receiving_items.article_id ' .
			' order by receiving_items.article_id ', 1);

		for ($i = 0; isset($y['article_id']) && $i < sizeof($y['article_id']); $i++) {
			$l_pos = array_search($y['article_id'][$i], $x['article_id']);
			if ($l_pos === false) {
				$x['article_id'][] = $y['article_id'][$i];
				$x['s1'][] = -1 * abs($y['s1'][$i]);
			} else {
				$x['s1'][$l_pos] -= abs($y['s1'][$i]);
			}
		}




		$z = $this->get_data('select product_items.article_id, sum(abs(medju_items.kolicina) * product_items.amount) as s1 ' .
			' from medjus, medju_items, product_items ' .
			' where medjus.id = medju_items.medju_id ' .
			' and medju_items.product_id = product_items.product_id ' .
			$l_uvjet_4 .
			' and medjus.posted = 1 ' .
			' and medjus.povrat = 0 ' .
			' group by product_items.article_id ' .
			' order by product_items.article_id ', 1);

		for ($i = 0; isset($z['article_id']) && $i < sizeof($z['article_id']); $i++) {

			if (isset($x['article_id'])) {
				$l_pos = array_search($z['article_id'][$i], $x['article_id']);
			} else {
				$l_pos = false;
			}

			if ($l_pos === false) {
				$x['article_id'][] = $z['article_id'][$i];
				$x['s1'][] = -1 * $z['s1'][$i];
			} else {
				$x['s1'][$l_pos] -= $z['s1'][$i];
			}
		}



		for ($i = 0; isset($x['article_id']) && $i < sizeof($x['article_id']); $i++) {
			if ($rbr_artikl == 0 || ($rbr_artikl > 0 && $x['article_id'][$i] == $rbr_artikl)) {
				// usluge uvijek nek ostanu na nula (odnosno, nikad ih ovdje nemoj promijeniti)
				$l_sql = 'update articles set amount = ' . $x['s1'][$i] . ' where id = ' . $x['article_id'][$i] . ' and isService = 0 ';
				$this->sql_exe($l_sql);
			}
		}

	}




	function slozi_stanje_robe_malo($rbr_artikl = 0, $slozi_bez_racuna = 0)
	{

		// za $rbr_artikl = 0, preslaguju se svi... inace se preslaguje samo onaj ciji je rbr naveden

		if ($rbr_artikl > 0) {
			$l_uvjet_1 = ' where id = ' . $rbr_artikl;
			$l_uvjet_2 = ' and receiving_items.article_id = ' . $rbr_artikl;
			$l_uvjet_3 = ' and retail_items.article_id = ' . $rbr_artikl;
		} else {
			$l_uvjet_1 = '';
			$l_uvjet_2 = '';
			$l_uvjet_3 = '';
		}

		$l_sql = 'update articles set amount = 0 ' . $l_uvjet_1;
		$this->sql_exe($l_sql);

		$x = $this->get_data('select receiving_items.article_id, sum(receiving_items.amount) as s1 ' .
			' from receivings, receiving_items ' .
			' where receivings.id = receiving_items.receiving_id ' .
			' and receivings.type in (0, 4) ' .
			$l_uvjet_2 .
			' and receivings.posted = 1 ' .
			' group by receiving_items.article_id ' .
			' order by receiving_items.article_id ', 1);

		$y = $this->get_data('select receiving_items.article_id, sum(abs(receiving_items.amount)) as s1 ' .
			' from receivings, receiving_items ' .
			' where receivings.id = receiving_items.receiving_id ' .
			' and receivings.type in (1, 2, 3) ' .
			$l_uvjet_2 .
			' and receivings.posted = 1 ' .
			' group by receiving_items.article_id ' .
			' order by receiving_items.article_id ', 1);

		for ($i = 0; isset($y['article_id']) && $i < sizeof($y['article_id']); $i++) {
			$l_pos = array_search($y['article_id'][$i], $x['article_id']);
			if ($l_pos === false) {
				$x['article_id'][] = $y['article_id'][$i];
				$x['s1'][] = -1 * abs($y['s1'][$i]);
			} else {
				$x['s1'][$l_pos] -= abs($y['s1'][$i]);
			}
		}

		// DODANO 07.03.2026 - Type 6 Skladiste (moze biti + ili -, bez abs())
		$w = $this->get_data('select receiving_items.article_id, sum(receiving_items.amount) as s1 ' .
			' from receivings, receiving_items ' .
			' where receivings.id = receiving_items.receiving_id ' .
			' and receivings.type = 6 ' .
			$l_uvjet_2 .
			' and receivings.posted = 1 ' .
			' group by receiving_items.article_id ' .
			' order by receiving_items.article_id ', 1);

		for ($i = 0; isset($w['article_id']) && $i < sizeof($w['article_id']); $i++) {
			$l_pos = array_search($w['article_id'][$i], $x['article_id']);
			if ($l_pos === false) {
				$x['article_id'][] = $w['article_id'][$i];
				$x['s1'][] = $w['s1'][$i]; // direktno, bez abs() i bez -1
			} else {
				$x['s1'][$l_pos] += $w['s1'][$i]; // dodaje se direktno (+ ili -)
			}
		}
		// KRAJ DODANO 07.03.2026 - Type 6 Skladiste



		if ($slozi_bez_racuna == 0) {

			$z = $this->get_data('select retail_items.article_id, sum(retail_items.amount) as s1 ' .
				' from sales, retail_items ' .
				' where sales.id = retail_items.sale_id ' .
				$l_uvjet_3 .
				' group by retail_items.article_id ' .
				' order by retail_items.article_id ', 1);

			for ($i = 0; isset($z['article_id']) && $i < sizeof($z['article_id']); $i++) {

				if (isset($x['article_id'])) {
					$l_pos = array_search($z['article_id'][$i], $x['article_id']);
				} else {
					$l_pos = false;
				}
				if ($l_pos === false) {
					$x['article_id'][] = $z['article_id'][$i];
					$x['s1'][] = -1 * $z['s1'][$i];
				} else {
					$x['s1'][$l_pos] -= $z['s1'][$i];
				}
			}

		}





		for ($i = 0; isset($x['article_id']) && $i < sizeof($x['article_id']); $i++) {
			if ($rbr_artikl == 0 || ($rbr_artikl > 0 && $x['article_id'][$i] == $rbr_artikl)) {
				// usluge uvijek nek ostanu na nula (odnosno, nikad ih ovdje nemoj promijeniti)
				$l_sql = 'update articles set amount = ' . $x['s1'][$i] . ' where id = ' . $x['article_id'][$i] . ' and isService = 0 ';
				$this->sql_exe($l_sql);
			}
		}
	}


	function util_skladiste_to_primka()
	{

		$l_tip = $this->get_item('select value from settings where name = "tipprog" ');
		$l_tip == 'u' ?
			$l_baza_old = 'ugo'
			:
			$l_baza_old = 'malo';

		$l_baza_old .= '_' . (date('Y') - 1);


		$l_sale_date_new = $this->get_item('select date from sales order by id limit 1 ');
		if (!$l_sale_date_new) {
			$this->Session->setFlash(__('Za izvrsenje ove funkcije, obavezno je kreirati barem jedan racun u tekucoj godini.', true));
			return;
		}


		$databaseClassName = 'DATABASE_CONFIG';
		$db = new $databaseClassName;
		$temp = get_class_vars(get_class($db));


		$db_old = mysql_select_db($l_baza_old);
		if ($db_old === false) {
			$this->Session->setFlash(__('Nije moguce izvrsiti ovu funkciju. Nemate sve potrebne baze podataka. Molimo kontaktirajte administratora!', true));
			return;
		}
		$l_sale_date_old = $this->get_item('select date from sales order by id desc limit 1 ');
		mysql_select_db($temp['default']['database']) or die("unable to select database");


		$l_year_new = date('Y', strtotime($l_sale_date_new));
		$l_year_old = date('Y', strtotime($l_sale_date_old));

		if (($l_year_old + 1 == $l_year_new) && (date('Y') == $l_year_new)) {
		} else {
			$this->Session->setFlash(__('Nije moguce izvrsiti ovu funkciju. Nemate sve potrebne baze podataka. Molimo kontaktirajte administratora!', true));
			return;
		}


		$l_exist_inventura = $this->get_item('select id from suppliers where name = "Inventura" order by id limit 1 ');
		if (!$l_exist_inventura) {
			$l_sql = 'insert into suppliers values(NULL, "Inventura", "", "", "", "Inventura", now(), "vlasnik", now(), "vlasnik", "", "", "", "", "", "")';
			$l_exist_inventura = $this->sql_exe($l_sql, true);
		}

		$l_rec_1 = $this->get_item('select id from receivings where id = 1 ');
		if ($l_rec_1 == 1) {

			$l_sql = 'delete from receiving_items where receiving_id = 1 ';
			$this->sql_exe($l_sql);

			$l_sql = 'delete from receivings where id = 1 ';
			$this->sql_exe($l_sql);

		}

		$l_now = date('Y') . '-01-01 00:00:00';

		$l_sql = 'insert into receivings values(1, ' . intval($l_exist_inventura) . ', null, null, "' . $l_now . '", "' . $l_now . '", "vlasnik", "' . $l_now . '", "vlasnik", 0, NULL, "", "' . $l_now . '", "", 0, 1, "' . date('Y') . '/000001", "", "", "", null, 0, 0, 0, 0, 1, 1)';
		$this->sql_exe($l_sql);


		$db_old = mysql_select_db($l_baza_old) or die('unable to select old database - ' . $l_baza_old);
		$x = $this->get_data('SELECT articles.id , articles.amount , (articles.amount * articles.price_buy) as x0, articles.price_buy , articles.price_sell , ' .
			' ((articles.price_sell / ( 1 + tax_groups.tax_1 / 100) / articles.price_buy - 1 ) * 100) as x1, (articles.price_sell / ( 1 + tax_groups.tax_1 / 100) - articles.price_buy) as x2,  ' .
			' ((articles.price_sell / ( 1 + tax_groups.tax_1 / 100) - articles.price_buy) * articles.amount) as x3, (articles.amount * articles.price_sell) as x4, ' .
			' tax_groups.tax_1 as x5, tax_groups.tax_2 as x6, feedback_compensation as x7 ' .
			' FROM articles, tax_groups ' .
			' WHERE tax_groups.id = articles.tax_group_id ' .
			' and amount > 0', $db_old);
		mysql_select_db($temp['default']['database']) or die("unable to select database");

		$l_id_ri = '0';
		for ($i = 0; isset($x['id']) && $i < sizeof($x['id']); $i++) {
			$l_sql = 'insert into receiving_items values(NULL, 1, ' . $x['id'][$i] . ', ' . $x['amount'][$i] . ', ' . $x['x0'][$i] . ', ' . $x['price_buy'][$i] . ', ' . $x['price_sell'][$i] .
				', 0, ' . $x['x1'][$i] . ', ' . $x['x2'][$i] . ', ' . $x['x3'][$i] . ', null, ' . $x['x4'][$i] . ', ' . $x['x5'][$i] . ', ' . $x['x6'][$i] . ', null, null, ' . $x['x7'][$i] . ', 1)';
			$l_id_ri = ', ' . $this->sql_exe($l_sql, true);
		}


		// samo za prijelaz KN u EUR... kad prodje godina dana, vise nema potrebe da se euri prebacuju u kune... kuna, euro, KUNA, EURO, kn, Kn, KN, HRK, EUR
		if (date('Y-m-d') <= '2023-12-30 23:59:59') {
			$l_sql = 'update receiving_items set price = price / 7.5345, price_buy = price_buy / 7.5345, price_sell = price_sell / 7.5345, price_sell_ukup = price_sell_ukup / 7.5345, marza_per_unit = marza_per_unit / 7.5345 where id in (' . $l_id_ri . ') ';
			$this->sql_exe($l_sql);
		}





		$a_pb_ps = $this->get_data('select sum(amount * price_buy) as pbu, sum(amount * price_sell) as psu from receiving_items where receiving_id = 1', 0);

		$l_sql = 'update receivings set price_buy = ' . $a_pb_ps['pbu'] . ', price_sell = ' . $a_pb_ps['psu'] . ' where id = 1 ';
		$this->sql_exe($l_sql);
	}


	function slozi_izracunaj_nc_normativa()
	{

		$x = $this->get_data('select products.id, sum(product_items.amount * articles.price_buy) as cijena ' .
			' from products, product_items, articles ' .
			' where products.id = product_items.product_id ' .
			' and product_items.article_id = articles.id ' .
			' group by products.id ' .
			' order by products.id ', 1);
		for ($i = 0; isset($x['id']) && $i < sizeof($x['id']); $i++) {
			$l_sql = 'update products set ncp = ' . $x['cijena'][$i] . ' where id = ' . $x['id'][$i];
			$this->sql_exe($l_sql);
		}
	}



	function mnozi_dijeli_pdv($type, $upValue)
	{

		// $upValue se vise ne dohvaca iz forme, vec preko tablice tax_groups... pogledati malo ispod gdje se ta vrijednost pridjeli varijabli


		$l_max_primka = $this->get_item('select max(substring(broj_primka, 6, 6)) as zbr from receivings where substring(broj_primka, 1, 4) = ' . date('Y'));
		$l_max_primka = intval($l_max_primka);
		$l_max_primka++;
		$l_max_primka = sprintf('%06d', $l_max_primka);


		$l_user_id = $this->Session->read('Auth.User.id');

		$l_user_name = $this->get_item('select full_name from users where id = ' . intval($l_user_id));

		$l_has_supplier = $this->get_item('select id from suppliers where name = "DONOS ' . date('d.m.Y.') . '" ');
		if (!$l_has_supplier) {
			$l_sql = 'insert into suppliers values(null, "DONOS ' . date('d.m.Y.') . '", "", "", "", "", now(), "' . $l_user_name . '", now(), "' . $l_user_name . '", "", "", "", "", "", "")';
			$l_has_supplier = $this->sql_exe($l_sql, true);
		}


		$l_sql = 'insert into receivings values(null, ' . $l_has_supplier . ', 0, 0, now(), now(), "' . $l_user_name . '", now(), "' . $l_user_name . '", 0, NULL, "", now(), ' .
			' "", 0, 0, "' . date('Y') . '/' . $l_max_primka . '", "", "", "", "")';
		$l_rec_id = $this->sql_exe($l_sql, true);



		$x = $this->get_data('select id, amount, price_buy, price_sell, tax_group_id, feedback_compensation ' .
			' from articles ' .
			' where amount > 0 ' .
			' order by articles.id ', 1);

		for ($i = 0; $i < sizeof($x['id']); $i++) {

			$la_tax = $this->get_data('select tax_1, tax_2 from tax_groups where id = ' . $x['tax_group_id'][$i], 0);


			// pridijeli vrijednost varijable iz tablice, a ne da dolazi iz html forme kako je bilo ranije
			$upValue = $la_tax['tax_1'];

			if ($type == 1) {
				$l_konst_pdv = 1 + $upValue / 100;
			}
			if ($type == 2) {
				$l_konst_pdv = 1 + $upValue / 100;
				$l_konst_pdv = 1 / $l_konst_pdv;
			}

			$l_sql = 'insert into receiving_items values(null, ' . intval($l_rec_id) . ', ' . $x['id'][$i] . ', ' . $x['amount'][$i] . ', ' . ($x['amount'][$i] * $x['price_sell'][$i]) . ', ' .
				($x['price_buy'][$i] * $l_konst_pdv) . ', ' . $x['price_sell'][$i] . ', 0, ' .
				round(($x['price_sell'][$i] / ($l_konst_pdv * $x['price_buy'][$i])) - 1, 2) . ', ' .
				round($x['price_sell'][$i] - ($l_konst_pdv * $x['price_buy'][$i]), 2) . ', ' .
				round(($x['price_sell'][$i] - ($l_konst_pdv * $x['price_buy'][$i])) * $x['amount'][$i], 2) . ', ' .
				' null, null, ' . $la_tax['tax_1'] . ', ' . $la_tax['tax_2'] . ', 0, 0, ' . $x['feedback_compensation'][$i] . ')';
			$this->sql_exe($l_sql);

		}

	}

	public function insertPrimka()
	{
		$this->autoRender = false; // Isključujemo renderovanje HTML-a

		//echo "✅ 1. Pokrenuta insertPrimka()<br>";

		// 1️⃣ Generisanje broja primke
		$l_max_primka = $this->get_item('SELECT MAX(SUBSTRING(broj_primka, 6, 6)) AS zbr FROM receivings WHERE SUBSTRING(broj_primka, 1, 4) = ' . date('Y'));
		$l_max_primka = intval($l_max_primka) + 1;
		$l_max_primka = sprintf('%06d', $l_max_primka);

		//echo "✅ 2. Generisan broj primke: $l_max_primka<br>";

		// 2️⃣ Dohvaćanje podataka o korisniku
		$l_user_id = $this->Session->read('Auth.User.id');
		$l_user_name = $this->get_item('SELECT full_name FROM users WHERE id = ' . intval($l_user_id));

		//echo "✅ 3. Korisnik: $l_user_name (ID: $l_user_id)<br>";

		// 3️⃣ Hardkodirani Supplier ID = 1
		$l_has_supplier = 1;
		//echo "✅ 4. Dobavljač ID: $l_has_supplier (hardkodiran)<br>";

		// 4️⃣ Kreiranje nove primke u `receivings` s ispravnim kolonama
		$l_sql = 'INSERT INTO receivings (supplier_id, price_buy, price_sell, date, created, created_by, modified, modified_by, canceled, canceled_by, note, document_date, number, type, posted, broj_primka, broj_otpis, broj_povratnica, broj_medjuskladisnica, broj_inventura)
				  VALUES (' . $l_has_supplier . ', 0, 0, NOW(), NOW(), "' . $l_user_name . '", NOW(), "' . $l_user_name . '", 0, NULL, "", NOW(), "", 0, 0, "' . date('Y') . '/' . $l_max_primka . '", "", "", "", "")';

		//echo "📌 SQL Primka: $l_sql <br>";

		$l_rec_id = $this->sql_exe($l_sql, true);

		if (!$l_rec_id) {
			echo "❌ Greška: Primka nije kreirana!<br>";
			exit();
		}

		//echo "✅ 6. Kreirana primka s ID: $l_rec_id<br>";

		// 5️⃣ Očisti tablicu receiving_items za receiving_id = 1
		$sql_delete = 'DELETE FROM receiving_items WHERE receiving_id = 1';
		//echo "📌 SQL DELETE receiving_items: $sql_delete <br>";
		$this->sql_exe($sql_delete);
		//echo "✅ 7. Obrisani podaci iz receiving_items<br>";

		// 6️⃣ Ubaci artikle iz `articles` u `receiving_items`
		$sql_insert = 'INSERT INTO receiving_items (receiving_id, article_id, amount, price_buy, price_sell)
						SELECT ' . $l_rec_id . ', id, amount, price_buy, price_sell FROM articles';

		//echo "📌 SQL Insert Receiving Items: $sql_insert <br>";
		$this->sql_exe($sql_insert);
		//echo "✅ 8. Artikli dodani u receiving_items<br>";

		// 7️⃣ Izračunaj iznose u receiving_items
		$this->sql_exe('UPDATE receiving_items SET price = price_buy * amount');
		//echo "✅ 9. Ažuriran price<br>";

		$this->sql_exe('UPDATE receiving_items SET marza_percent = (price_sell / price_buy - 1) * 100');
		//echo "✅ 10. Ažurirana marza_percent<br>";

		$this->sql_exe('UPDATE receiving_items SET marza_per_unit = (price_sell - price_buy)');
		//echo "✅ 11. Ažurirana marza_per_unit<br>";

		$this->sql_exe('UPDATE receiving_items SET marza_per_receiving = (price_sell - price_buy) * amount');
		//echo "✅ 12. Ažurirana marza_per_receiving<br>";

		// 8️⃣ Ažuriraj `price_sell_curency` u `articles`
		$this->sql_exe('UPDATE articles SET price_sell_curency = price_sell * 7.54');
		//echo "✅ 13. Ažuriran price_sell_curency u articles<br>";

		//echo json_encode(["status" => "success", "primka_id" => $l_rec_id]);
		//exit(); // Zaustavi izvršavanje da vidiš poruke

	}




	function preslozi_stanje($upValue)
	{

		$l_sql = 'delete from receiving_items where receiving_id in (select id from receivings where canceled = 1) ';
		$this->sql_exe($l_sql);

		$l_sql = 'delete from receivings where canceled = 1 ';
		$this->sql_exe($l_sql);


		if ($this->get_item('select value from settings where name = "tipprog" limit 1 ') == 'm') {
			$this->slozi_stanje_robe_malo($upValue, 0);
		}
		if ($this->get_item('select value from settings where name = "tipprog" limit 1 ') == 'u') {
			$this->slozi_stanje_robe_ugo($upValue, 0);
		}
	}

	function update($upId, $upValue = '')
	{

		if ($upId == -166) {  // 🔥 Novi case za "IZRADI PRIMKU"
			$this->insertPrimka();
			$this->Session->setFlash(__('Primka je uspješno kreirana.', true));
			$this->redirect(array('action' => '../alati/'));
			return;
		}

		if ($upId == -165) {
			$this->mnozi_dijeli_pdv(2, $upValue);

			$this->Session->setFlash(__('Izrađena je primka 1 / PDV', true));

			$this->redirect(array('action' => '../alati/'));
			return;
		}


		if ($upId == -164) {
			$this->mnozi_dijeli_pdv(1, $upValue);

			$this->Session->setFlash(__('Izrađena je primka 1 x PDV', true));

			$this->redirect(array('action' => '../alati/'));
			return;
		}



		if ($upId == -163) {

			$x = $this->get_data('select id ' .
				' from articles ' .
				' order by articles.id ', 1);

			for ($i = 0; $i < sizeof($x['id']); $i++) {

				$y = $this->get_data('select receiving_items.price_buy, receiving_items.discount ' .
					' from receivings, receiving_items ' .
					' where receivings.id = receiving_items.receiving_id ' .
					' and receivings.type in (0) ' .
					' and receivings.posted = 1 ' .
					' and receiving_items.article_id = ' . $x['id'][$i] .
					' order by receivings.document_date desc, receivings.id desc, receiving_items.receiving_id desc, receiving_items.id desc ' .
					' limit 1 ', 0);

				if (isset($y['price_buy'])) {
					$l_sql = 'update articles set price_buy = ' . ($y['price_buy'] * (100 - $y['discount']) / 100) . ' where id = ' . $x['id'][$i];
					$this->sql_exe($l_sql);
				}

			}

			$this->Session->setFlash(__('Nabavne cijene preuzete su iz zadnjih primki', true));

			$this->redirect(array('action' => '../alati/'));
			return;
		}


		if ($upId == -162) {
			// slozi bez racuna


			if ($upValue == -1) {
				$this->Session->setFlash(__('Niste odabrali niti jedan artikl!', true));
				$this->redirect(array('action' => 'index'));
				return;
			}

			$this->Session->setFlash(__('Artikli preslozeni ', true));

			//$this->Setting->query("call StimujStanjaArtikala();");

			$l_sql = 'delete from receiving_items where receiving_id in (select id from receivings where canceled = 1) ';
			$this->sql_exe($l_sql);

			$l_sql = 'delete from receivings where canceled = 1 ';
			$this->sql_exe($l_sql);


			if ($this->get_item('select value from settings where name = "tipprog" limit 1 ') == 'm') {
				$this->slozi_stanje_robe_malo($upValue, 1);
			}
			if ($this->get_item('select value from settings where name = "tipprog" limit 1 ') == 'u') {
				$this->slozi_stanje_robe_ugo($upValue, 1);
			}

			$this->Session->setFlash('Stanje robe je uspješno složeno.');
			$this->redirect(array('controller' => 'alati', 'action' => 'index'));
			return;

		}



		// slozi stanje KEUB
		if ($upId == -161) {
			if ($upValue == -1) {
				$this->Session->setFlash(__('Niste odabrali niti jedan artikl!', true));
				$this->redirect(array('action' => 'index'));
				return;
			}

			$this->Session->setFlash(__('Artikli preslozeni ', true));


			$l_sql = 'delete from receiving_items where receiving_id in (select id from receivings where canceled = 1) ';
			$this->sql_exe($l_sql);

			$l_sql = 'delete from receivings where canceled = 1 ';
			$this->sql_exe($l_sql);


			if ($this->get_item('select value from settings where name = "tipprog" limit 1 ') == 'm') {
				// ovdje nikad nece doci jer KEUB-a nema na stranici za MALO
			}
			if ($this->get_item('select value from settings where name = "tipprog" limit 1 ') == 'u') {
				$this->slozi_stanje_keub_ugo($upValue);
			}

			$this->redirect(array('action' => '../alati/'));
			return;
		}



		if ($upId == -160) {
			//$this->Session->setFlash(__('Stanje skladista prethodne godine prebaceno je u prvu primku tekuce godine.', true));
			$this->Session->setFlash(__('Artikli preneseni i stanje preslozeno ', true));

			$this->util_skladiste_to_primka();
			$this->preslozi_stanje($upValue);
		}

		if ($upId == -159) {
			$this->Session->setFlash(__('Nabavne cijene normativa su izracunate ', true));

			$this->slozi_izracunaj_nc_normativa();
		}

		if ($upId == -158) {
			$this->Session->setFlash(__('Knjiga popisa je osvjezena', true));

			$this->Setting->query("call Knjizenje(NULL);");

			$this->redirect(array('action' => 'index'));
			return;
		}


		if ($upId == -157) {

			if ($upValue == -1) {
				$this->Session->setFlash(__('Niste odabrali niti jedan artikl!', true));
				$this->redirect(array('action' => 'index'));
				return;
			}

			//$this->Setting->query("call StimujStanjaArtikala();");


			$this->preslozi_stanje($upValue);

			/*
																																																				  $l_sql = 'delete from receiving_items where receiving_id in (select id from receivings where canceled = 1) ';
																																																				  $this->sql_exe($l_sql);
																																																				  
																																																				  $l_sql = 'delete from receivings where canceled = 1 ';
																																																				  $this->sql_exe($l_sql);
																																																				  
																																																				  
																																																				  if($this->get_item('select value from settings where name = "tipprog" limit 1 ') == 'm'){
																																																					  $this->slozi_stanje_robe_malo($upValue, 0);
																																																				  }
																																																				  if($this->get_item('select value from settings where name = "tipprog" limit 1 ') == 'u'){
																																																					  $this->slozi_stanje_robe_ugo($upValue, 0);
																																																				  }
																																																				  */

			$this->redirect('/alati/?msg=ok');
			return;
		}

		if ($upId == -156) {
			$this->Session->setFlash(__('Prebacili ste cijene svih normativa na ', true) . __('Price ' . $upValue, true), 'default', array('class' => 'success'));

			$this->Setting->query("update products set price=price_" . $upValue);

			$this->redirect(array('action' => 'index'));
			return;
		}


		$upValue = (base64_decode(str_replace("*", "+", str_replace("{", "/", str_replace("}", "=", $upValue)))));
		//die($upValue);
		//$upValue=urldecode ($upValue);
		$record = $this->Setting->find('first', array('conditions' => array('Setting.id' => $upId)));

		$record['Setting']['value'] = $upValue;


		$this->Setting->create();
		$this->Setting->saveAll($record['Setting']);


		//$this->redirect(array('action' => 'index'));
		$this->redirect(array('action' => '../alati/'));
	}

	function updateImg($upId)
	{


		$record = $this->Setting->find('first', array('conditions' => array('Setting.id' => $upId)));

		$record['Setting']['value'] = $upValue;


		$this->Setting->create();
		$this->Setting->saveAll($record['Setting']);


		$this->redirect(array('action' => 'index'));
	}

	function edit($id = null)
	{
		print_r($_GET);
		die();
	}

	function delete($id = null)
	{

	}

}
