<?php
require 'acesso.php';
	$res = array();

	$query = "SELECT a.arcodigo, COALESCE( a.ardesnot, a.ardescri ) AS descricao, a.ardescri, a.arunidad, a.arrefere, a.arrefori,
			a.arcodbar, a.arstqloj, a.arqtmedi, a.arlcacao, a.arlocal_depo, a.ardesativa_produ, a.arstqmin, a.artipdep, a.arfracio,
			CAST( MID( arvrcomp, ( artabatu - 1) * 16 + 1, 16 ) * 1 AS DECIMAL( 16,2 ) ) AS vr_bruto,
			CAST( MID( arvrvend, ( artabatu - 1) * 16 + 1, 16 ) * 1 AS DECIMAL( 16,2 ) ) AS vr_vista,
			CAST( MID( arvratad, ( artabatu - 1) * 16 + 1, 16 ) * 1 AS DECIMAL( 16,2 ) ) AS vr_cartao,
			CAST( MID( arqtdest, ( artabatu - 1) * 9 + 1 , 9 ) * 1 AS DECIMAL( 9,3 ) ) AS qtd_loja,
			CAST( MID( arqtdepo, ( artabatu - 1) * 9 + 1 , 9 ) * 1 AS DECIMAL( 9,3 ) ) AS qtd_deposito,
			b.arnommar, c.arnomgru FROM estoque a LEFT JOIN marcas b ON a.arcodmar = b.arcodmar
			LEFT JOIN grupos c ON a.arcodgru = c.arcodgru ";

	$con = new PDO("mysql:dbname=$database; charset=utf8", $usuario , $senha);
	if (isset($_POST['pesquisar'])) {
		$campo = $_POST['campo'];
		$termo = $_POST['termo'];
		$contido = $_POST['contido'];
		switch ($campo) {
		case 0: // descrição
			if ($contido == "1") {
				$like_termos = "";
				$like_array = explode(' ', $termo);
				foreach($like_array as $palavra) {
					$like_termos = $like_termos . "COALESCE( ardesnot, ardescri ) LIKE '%$palavra%' AND ";
				}
				$like_termos = substr($like_termos, 0, -4);
				$ret = $con->prepare($query . "WHERE $like_termos AND a.sr_deleted != 'T' HAVING descricao IS NOT NULL ORDER BY arrefere");
			} else {
				$ret = $con->prepare($query . "WHERE COALESCE( ardesnot, ardescri ) LIKE '$termo%' AND a.sr_deleted != 'T' HAVING descricao IS NOT NULL ORDER BY arrefere");
			} 
			break;
		case 1: // referencia
			if ($contido == "1") {
				$ret = $con->prepare($query . "WHERE arrefere LIKE '%$termo%' AND a.sr_deleted != 'T' HAVING descricao IS NOT NULL ORDER BY arrefere");
			} else {
				$ret = $con->prepare($query . "WHERE arrefere LIKE '$termo%' AND a.sr_deleted != 'T' HAVING descricao IS NOT NULL ORDER BY arrefere");
			}
			break;
		case 2: // codigo de barras
			if ($contido == "1") {
				$ret = $con->prepare($query . "WHERE COALESCE( arcodbar, arcdbar2 ) LIKE '%$termo%' AND a.sr_deleted != 'T' HAVING descricao
						IS NOT NULL ORDER BY arrefere");
			} else {
				$ret = $con->prepare($query . "WHERE COALESCE( arcodbar, arcdbar2 ) LIKE '$termo%' AND a.sr_deleted != 'T' HAVING descricao
						IS NOT NULL ORDER BY arrefere");
			}
			break;
		case 3: // código
			if ($contido == "1") {
				$ret = $con->prepare($query . "WHERE arcodigo LIKE '%$termo%' AND a.sr_deleted != 'T' HAVING descricao IS NOT NULL ORDER BY arrefere");
			} else {
				$codigo = str_pad($termo, 7, "0", STR_PAD_LEFT);
				$ret = $con->prepare($query . "WHERE arcodigo LIKE '$termo' AND a.sr_deleted != 'T' HAVING descricao IS NOT NULL ORDER BY arrefere");
			}
			break;
		case 4: // marca
			$ret = $con->prepare($query . "WHERE a.arcodmar = '$termo' AND a.sr_deleted != 'T' HAVING descricao IS NOT NULL ORDER BY arrefere");
		}
	} else if (isset($_POST['atualizar'])) {
		$codigo = $_POST['codigo'];
		$quantidade = $_POST['quantidade'];
		$minimo = $_POST['minimo'];
		$locacao = $_POST['locacao'];
		$desativado = $_POST['desativado'];
		$local = $_POST['local'];
		$codbarra = $_POST['codbarra'];
		if ($local == 1) { // loja
			$ret = $con->prepare("UPDATE estoque SET arcodbar = '$codbarra', arqtmedi = $minimo, arlcacao = '$locacao', ardesativa_produ = $desativado WHERE arcodigo = '$codigo'");
			$ret->execute();

			$ret = $con->prepare("UPDATE estoque SET arqtdest = IF(arqtdest IS NULL, CONCAT(LEFT(RPAD('', 108, '0'), (artabatu - 1) * 9), LPAD(CAST($quantidade AS DECIMAL(9, 3)), 9, '0'), MID(RPAD('', 108, '0'), (artabatu * 9) + 1)), CONCAT(LEFT(RPAD(REPLACE(arqtdest, ' ', '0'), 108, '0'), (artabatu - 1) * 9), LPAD(CAST($quantidade AS DECIMAL(9, 3)), 9, '0'), MID(RPAD(REPLACE(arqtdest, ' ', '0'), 108, '0'), (artabatu * 9) + 1))) WHERE arcodigo = '$codigo'");
		} else { // depósito
			$embalagem = $_POST['embalagem'];
			$ret = $con->prepare("UPDATE estoque SET arcodbar = '$codbarra', arstqloj = $minimo, arlocal_depo = '$locacao', ardesativa_produ = $desativado, arstqmin = $embalagem WHERE arcodigo = '$codigo'");
			$ret->execute();

			$ret = $con->prepare("UPDATE estoque SET arqtdepo = IF(arqtdepo IS NULL, CONCAT(LEFT(RPAD('', 108, '0'), (artabatu - 1) * 9), LPAD(CAST($quantidade AS DECIMAL(9, 3)), 9, '0'), MID(RPAD('', 108, '0'), (artabatu * 9) + 1)), CONCAT(LEFT(RPAD(REPLACE(arqtdepo, ' ', '0'), 108, '0'), (artabatu - 1) * 9), LPAD(CAST($quantidade AS DECIMAL(9, 3)), 9, '0'), MID(RPAD(REPLACE(arqtdepo, ' ', '0'), 108, '0'), (artabatu * 9) + 1))) WHERE arcodigo = '$codigo'");
		}
		$ret->execute();
		if ($ret->rowCount() > 0) {
			$ret = $con->prepare("INSERT INTO esto_56 (arcodigo, ardtalte, arvratua, sr_deleted) VALUES ('$codigo', date(now()), $quantidade, ' ')");
		}
	} else if (isset($_POST['alteracao'])) {
		$codigo = $_POST['codigo'];
		$data = $_POST['data'];
		$hora = $_POST['hora'];
		$mac = $_POST['mac'];
		$quantidade_anterior = $_POST['quantidade_anterior'];
		$quantidade_atual = $_POST['quantidade_atual'];
		$mudanca = $_POST['mudanca'];
		$operador = $_POST['operador'];
		
		$ret = $con->prepare("UPDATE esto_56 SET arvrante = $quantidade_anterior, arhoratu = '$hora', armaquin = '$mac', arusuari = '$operador', arnommaq = 'TABLET/SMARTPHONE', armudanc = '$mudanca' 
					WHERE arcodigo = '$codigo' AND arvratua = $quantidade_atual AND ardtalte = '$data'");
	} else if (isset($_POST['marcas'])) {
		$termo = $_POST['termo'];
		$contido = $_POST['contido'];
		if ($contido == "1") {
			$ret = $con->prepare("SELECT arcodmar, arnommar FROM marcas WHERE arnommar LIKE '%$termo%' ORDER BY arnommar");
		} else {
			$ret = $con->prepare("SELECT arcodmar, arnommar FROM marcas WHERE arnommar LIKE '$termo%' ORDER BY arnommar");
		}
	} else if (isset($_POST['usuarios'])) {
		$ret = $con->prepare("SELECT arcoduse, arnomuse, arsenuse FROM user_admin WHERE sr_deleted != 'T' ORDER BY arnomuse");
	} else if (isset($_POST['levantamentos'])) {
	    $query = "select l.arcodigo, coalesce(e.ardesnot, e.ardescri) as ardesnot, m.arnommar, e.arrefere, e.arcodbar, l.ardtalte, l.arvrante, l.arvratua, l.arusuari, l.armaquin, l.arnommaq, l.armudanc from esto_56 l left join estoque e on l.arcodigo = e.arcodigo left join marcas m on e.arcodmar = m.arcodmar ";
	    /* if (isset($_POST['data_inicial']) && isset($_POST['data_final'])) {
	        echo "data_inicial: " . $_POST['data_inicial'];
	        echo "data_final: " . $_POST['data_final'];
	        
	        $data_inicial = $_POST['data_inicial'];
	        $data_final = $_POST['data_final'];
	        if ($data_inicial = '') {
	            echo 'passo1';
	            $ret = $con->prepare($query . "where l.sr_deleted = ' ' and l.ardtalte <= '$data_final' order by ardtalte desc");
	        } else if ($data_final = '') {
	            echo 'passo2';
	            $ret = $con->prepare($query . "where l.sr_deleted = ' ' and l.ardtalte >= '$data_inicial' order by ardtalte desc");
	        } else {
	            echo 'passo3';
	            echo $data_inicial;
	            $ret = $con->prepare($query . "where l.sr_deleted = ' ' and l.ardtalte between '" . $data_inicial . "' and '$data_final' order by ardtalte desc");
	            //$ret = $con->prepare($query . "where l.sr_deleted = ' ' and l.ardtalte between '2019-04-01' and '2019-09-01' order by ardtalte desc");
	            
	        }
	    } else {
	        echo 'passo4';
	        $ret = $con->prepare($query . "where v.sr_deleted = ' ' order by ardtalte desc");
	    } */
	    $ret = $con->prepare($query . " where l.sr_deleted = ' ' order by l.ardtalte desc limit 100");
	    //echo $ret->queryString;
	}

	$ret->execute();
	$mensagem = $ret->errorInfo();
	if($ret->rowCount() > 0) {
		$res["levantamento"] = array();
		while ($row = $ret->fetch(PDO::FETCH_ASSOC)) {
			array_push($res["levantamento"], $row);
		}
	}

	if($mensagem[0] == "00000") {
		$res["sucesso"] = 1;
		echo json_encode($res);
	} else {
		$res["sucesso"] = 0;
		$res["mensagem"] = $mensagem[2];
		echo json_encode($res);
	}

	$con = null;
?>

