<?php
require 'acesso.php';
	$res = array();
	//$con = new PDO("mysql:dbname=$database; charset=utf8", $usuario , $senha);
	//IF(b.artpvend IN('10', '11'), ROUND(0 - SUM((a.arqtdsai * a.arvrvend) - (COALESCE(a.ardesconto_adcional, 0) + COALESCE(a.arvrdesc, 0) + COALESCE(a.ardesicm, 0))), 2), ROUND(SUM((a.arqtdsai * a.arvrvend) - (COALESCE(a.ardesconto_adcional, 0) + COALESCE(a.ardesicm, 0))), 2)) AS arvliqui
			
	$query = "SELECT a.arcodven, a.ardtsaid, COUNT(b.artpvend) AS arqtdven, b.artpvend, c.ardesfor,
			IF(b.artpvend IN('10', '11'), 0, ROUND(SUM(a.arvtotal), 2)) AS arvbruto, 
			IF(b.artpvend IN('10', '11'), 0, ROUND(SUM(COALESCE(a.ardesconto_adcional, 0) + COALESCE(a.arvrdesc, 0)), 2)) AS arvrdesc, 
			IF(b.artpvend IN('10', '11'), 0, ROUND((1 - SUM((a.arvtotal) - (COALESCE(a.ardesconto_adcional, 0) + COALESCE(a.arvrdesc, 0) + COALESCE(a.ardesicm, 0))) / SUM(a.arvtotal)) * 100, 2)) AS arperdes, 
			IF(b.artpvend IN('10', '11'), 0, ROUND(SUM(a.arvtotal - (COALESCE(a.ardesconto_adcional, 0) + COALESCE(a.arvrdesc, 0))), 2)) AS arvliqui
			FROM saidas a LEFT JOIN boletos b ON b.arnrdoct = a.arnrdoct LEFT JOIN forma_pg c ON c.artpvend = b.artpvend LEFT JOIN estoque d ON d.arcodigo = a.arcodigo ";
	
	if (isset($_POST['arcodvde'])) {
		$arcodvde = $_POST['arcodvde'];
		$ret = $con->prepare($query . "WHERE a.arcodven = '$arcodvde' AND b.artpbaix = 'B' AND d.arprod_sem_comiss != '1' AND b.artpvend NOT IN( '28','34','22' ) AND a.sr_deleted != 'T' AND a.arexcuid = '0' AND a.ardtsaid BETWEEN (curdate() - interval 3 MONTH) AND curdate()  
			GROUP BY a.ardtsaid, b.artpvend ORDER BY a.ardtsaid, c.ardesfor");
	} else {
		$ret = $con->prepare($query . "WHERE a.arcodven IS NOT NULL AND b.artpbaix = 'B' AND d.arprod_sem_comiss != '1' AND b.artpvend NOT IN( '28','34','22' ) AND a.sr_deleted != 'T' AND a.arexcuid = '0' AND a.ardtsaid BETWEEN (curdate() - interval 3 MONTH) AND curdate()
				GROUP BY a.ardtsaid, b.artpvend ORDER BY a.ardtsaid, c.ardesfor");	
	}
					
	$ret->execute();
	$mensagem = $ret->errorInfo();
	if($ret->rowCount() > 0) {
		$res['vendas'] = array();
		while ($row = $ret->fetch(PDO::FETCH_ASSOC)) {
			array_push($res["vendas"], $row);
		}
		$res["sucesso"] = 1;
		echo json_encode($res);
	} else {
		$res["sucesso"] = 0;
		$res["mensagem"] = $mensagem[2];
		echo json_encode($res);
	}