<?php
class kosikController extends baseController {

	function __construct() {

    $this->controller_name = 'Košík';
    $this->controller_fname = 'kosik';
    $this->controller_info = 'Košík';
    $this->entita_classname = 'Kosik';
    parent::__construct();

  }

  public function pridat($args) {

  	$kosik = $this->registry->kosik;

  	if (is_numeric($_POST['id_prod']) AND is_numeric($_POST['mnozstvi'])) {
  		$html = $kosik->pridat($_POST['id_prod'],$_POST['mnozstvi']);
  	}
  	else {
  		$html = 'Špatné parametry produktu';
  	}
  	
  	if (isset($_POST['pridat'])) {
  		Tools::setMessage($html, '',1);
  		Tools::redirect(Tools::productLinkId($_POST['id_prod']));
  	}
  	else {
  		$html .= $kosik->souhrn();
  		die($html);
  	}

  }

  public function zobrazit($args) {
  	
  	$rows = $this->registry->kosik->getArray();
  	
  	if (count($rows) > 0) {
 		
  		foreach($rows as $key=>$value) {
  			$rows[$key]['link'] = Tools::productLinkId($value['id']);
  			$rows[$key]['nazev'] = dibi::query('SELECT NAZEV FROM PRODUKT WHERE ID = %i', $value['id'])->fetchSingle();
  			$rows[$key]['cena'] = number_format($value['celkova_cena'],2,',',' ');
  			$rows[$key]['celkova_cena'] = number_format($value['mnozstvi'] * $value['celkova_cena'],2,',',' ');

  		}
  		
  		$this->registry->template->set('kosik',$rows);
  		$this->registry->template->set('celkovy_pocet',number_format($this->registry->kosik->celkovy_pocet,0,',', ' '));
  		$this->registry->template->set('celkova_cena',number_format($this->registry->kosik->celkova_cena,2,',', ' '));
  		$this->registry->template->set('kosik_prazdny',false,true);
  	}
  	else {
  		$this->registry->template->set('kosik_prazdny',true,true);
  	}
//$this->html = print_r($rows,true);
  	$this->setView('objednavka.tpl');

  }

  public function upravit($args) {

  	if ( $this->registry->form_send) {

			if (isset($_POST['smazat'])) {
				foreach($_POST['smazat'] as $key=>$vylue) {
					$_POST['mnozstvi'][$key] = 0;
					$_POST['prepocitej'] = true;
				}
			}

  		if (isset($_POST['prepocitej']) or isset($_POST['pokracuj'])) {

  			$this->registry->kosik->upravit($_POST['mnozstvi']);

				if (isset($_POST['pokracuj'])) {
					$redirect = Tools::controllerlink('objednavka','adresy');
				}
				else {
					$redirect = Tools::controllerlink($this->controller_fname,'zobrazit');
				}
				Tools::redirect($redirect);
  		}
  		elseif (isset($_POST['smazat_vse'])){
				
  			$this->registry->kosik->smazat();
				$this->setMessage('Nákupní košík byl vymazán', '', 1);
				$redirect = Tools::controllerlink($this->controller_fname,'zobrazit');
				Tools::redirect($redirect);
  		}

  	}
  	die;

  }

  public function treeNav() {

    $this->registry->template->set('is_tree_nav', true, true);
    $this->registry->template->set('akt_nazev', 'Košík');
//Debug::getVar($this->registry->template);
  }

}
?>