<?php

App::import('Lib', 'Ugotcp');

class AndroidController extends AppController {

	var $name = 'Android';
	var $uses = array('Sale','Receiving');

    var $components = array(
	    'Filter' => array(
        ),
	);

	function  beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('gettables');
		$this->Auth->allow('login');
		$this->Auth->allow('normativs');
		$this->Auth->allow('order');
		$this->Auth->allow('ns');
		$this->Auth->allow('nn');
		$this->Auth->allow('tablefull');
		$this->Auth->allow('ir');
		$this->Auth->allow('table');
		/*$this->Auth->mapActions(array(
			'payment_types' => 'read',
			'tax_groups' => 'read',
			'articles' => 'read',
			
		));*/
	}

function login() {
  @$r=$this->Sale->query("SELECT id,full_name FROM users WHERE user_level_id is not null and passkey='".$_POST["password"]."'");

  if (empty($r)) $ret["success"]="false"; else {
    $ret["success"]="true";
    $ret["waiterid"]=$r[0]["users"]["id"];
    $ret["name"]=$r[0]["users"]["full_name"];
  }

  die(json_encode($ret,JSON_FORCE_OBJECT));	

}

function tablefull() {
  @$tid=(int)$_POST["tableid"];
  $ts=$this->Sale->query("select coalesce(count(s.id),0) as pun from orders o inner join sale_items s on (s.order_id=o.id and s.sale_id is null and s.canceled_by is null) where o.table_id=".$tid." group by o.id order by o.id desc limit 1;");
  @$pun=(int)$ts[0][0]["pun"];
  $ret["success"]= $pun ? "true":"false";
  die(json_encode($ret,JSON_FORCE_OBJECT));	
}

function gettables() {
  $r="";
  $ts=$this->Sale->query("SELECT id,name from table_groups t");
  foreach($ts as $t) {
    $r.="SALA,".$t["t"]["name"].",255,255,255,".$t["t"]["id"]."\n";
    $ss=$this->Sale->query("select * from (SELECT id,name,color&0xff as r, (color>>8)&0xff as g,(color>>16)&0xff as b,position_x as x, position_y as y, angle as alpha, width as w, height as h, if(type,'KRUZNI','KVADRATNI') as type, IF((SELECT COUNT(*) FROM sale_items s inner join orders o on s.order_id=o.id where s.sale_id is null and o.table_id=t.id and s.canceled_by is null),'PUN','PRAZAN') as full FROM tables t WHERE table_group_id=".$t["t"]["id"].") q;");
    foreach($ss as $s) {
      $r.="STO,".$s["q"]["name"].",".$s["q"]["r"].",".$s["q"]["g"].",".$s["q"]["b"].",".$s["q"]["x"].",".$s["q"]["y"].",".$s["q"]["alpha"].",".$s["q"]["w"].",".$s["q"]["h"].",".$s["q"]["type"].",".$s["q"]["id"].",".$s["q"]["full"]."\n";
    }

  }

  die($r);
}


function normativs() {
  $r="";
  $ts=$this->Sale->query("SELECT id,name from product_groups t");
  foreach($ts as $t) {
    $r.="GROUPNORMATIVE,".$t["t"]["id"].",".$t["t"]["name"]."\n";

    //$ss=$this->Sale->query("SELECT id,name from products p where product_group_id=".$t["t"]["id"]);

    $ss=$this->Sale->query("select id,name,kom from (SELECT id,BASE64_ENCODE(name) as name,(select GROUP_CONCAT(BASE64_ENCODE(name) separator \",\") from notes where note_group_id=t.note_group_id) kom from products t where product_group_id=".$t["t"]["id"]." ) p;");

    foreach($ss as $p) {
      @$r.="NORMATIV,".$p["p"]["id"].",".$p["p"]["name"].($p["p"]["kom"] ? (",".$p["p"]["kom"]):"")."\n";
    }
  }

  die($r);

}

function table() {
  @$tid=$_POST["tableid"];
  $r="";
   
  if (isset($tid)) {

    $this->Sale->query("START TRANSACTION;");

    $ss = $this->Sale->query("select o.id from orders o left join sale_items s on (s.order_id=o.id and s.sale_id is null) where o.table_id=".$tid." limit 1;");
    if (!empty($ss)) {
      $oid=$ss[0]["o"]["id"];
      $rss = $this->Sale->query("select s.product_id, s.amount, s.base_price, s.price, s.discount_percent, BASE64_ENCODE(s.comment) ccc, p.name from sale_items s inner join products p on (s.product_id=p.id) where s.order_id = ".$oid." and s.sale_id is null and s.canceled_by is null");
      foreach($rss as $p) {
        @$r.=$p["p"]["name"].",".$p["s"]["product_id"].",".$p["s"]["amount"].",".$p["s"]["base_price"].",".$p["s"]["price"].",".$p["s"]["discount_percent"].($p["0"]["ccc"] ? (",".$p["0"]["ccc"]):"")."\n";
      }
    }
    $this->Sale->query("COMMIT;");
  }
  die($r);
}

function place($oid, $wid, $i) {
  @$pid=$i[0];
  if(!$pid) return;
  //if (isset($i[2])) $kom="\n".str_replace("'","`",$i[2]); else $kom="";

  @$kom=$i[2];

  if($kom) $kom="\n".str_replace("'","`",base64_decode($kom));
  
  @$ss=$this->Sale->query("select s.id from sale_items s where order_id=".$oid." and product_id=".$i[0]." and canceled_by is null and sale_id is null;");
  if (empty($ss)) {
    $ss=$this->Sale->query("select p.price from products p where p.id=".$i[0].";");
    $this->Sale->query("insert into sale_items (order_id,product_id,amount,base_price,comment,price) values(".$oid.",".$i[0].",".$i[1].",".$ss[0]["p"]["price"].",'".$kom."',".($i[1]*$ss[0]["p"]["price"]).");");
  } else {
    $this->Sale->query("update sale_items set amount=amount+".$i[1].", comment=CONCAT(comment,'".$kom."') where id=".$ss[0]["s"]["id"].";");
	$this->Sale->query("update sale_items set price=amount*base_price*(100-discount_percent)/100.0 where id=".$ss[0]["s"]["id"].";");
  }


}


function order() {

  @$wid=$_POST["waiterid"];
  @$tid=$_POST["tableid"];
  @$items=$_POST["items"];
  $today = date("d-m-Y H:i:s");

  $ret["success"]="false";

  if (isset($wid)&&isset($tid)&&isset($items)) {

    $this->Sale->query("START TRANSACTION;");

    $ss=$this->Sale->query("select o.id from orders o left join sale_items s on (s.order_id=o.id and s.sale_id is null) where o.table_id=".$tid." limit 1;");
	
    if(empty($ss)) {
      $this->Sale->query("insert into orders (table_id, created) values (".$tid.",'".$today."');");
      $ss=$this->Sale->query("select o.id from orders o left join sale_items s on (s.order_id=o.id and s.sale_id is null) where o.table_id=".$tid." limit 1;");
    }
    
    if(!empty($ss)) {
      $oid=$ss[0]["o"]["id"];

      $ia=explode("\n",$items);
      foreach($ia as $it) {
        $i=explode(",",$it);
		$this->place($oid,$wid,$i);
      }

      $ret["success"]="true";
      $this->Sale->query("COMMIT;");
    }
  }

  die(json_encode($ret,JSON_FORCE_OBJECT));

}

function ns() {
  @$wid=$_POST["waiterid"];
  @$tid=$_POST["tableid"]; 
  $ss=$this->Sale->query("select ip,port from printers where is_default=1");
  $ret["success"] = ugo_send_to_ip($ss[0]["printers"]["ip"],$ss[0]["printers"]["port"],"@@@SNS".$tid.",".$wid."\n") ?  "true":"false";
  die(json_encode($ret,JSON_FORCE_OBJECT));
}

function nn() {
  @$wid=$_POST["waiterid"];
  @$tid=$_POST["tableid"]; 
  @$items=$_POST["items"];
  $ss=$this->Sale->query("select ip,port from printers where is_default=1");
  $ret["success"] = ugo_send_to_ip($ss[0]["printers"]["ip"],$ss[0]["printers"]["port"],"@@@SNN~".$tid."~".$wid."~".$items."\n") ?  "true":"false";
  die(json_encode($ret,JSON_FORCE_OBJECT));
}

function ir() {
  @$wid=$_POST["waiterid"];
  @$tid=$_POST["tableid"]; 
  $ss=$this->Sale->query("select ip,port from printers where is_default=1");
  $ret["success"] = ugo_send_to_ip($ss[0]["printers"]["ip"],$ss[0]["printers"]["port"],"@@@SIR".$tid.",".$wid."\n") ?  "true":"false";
  die(json_encode($ret,JSON_FORCE_OBJECT));
}

}
