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

	$arcodcli = $_POST['arcodcli'];
	try {
	    //$con = new PDO("mysql:dbname=$database", $username , $password);
	    $res["sucesso"] = 1;
	} catch (PDOException $e) {
	    $res["sucesso"] = 0;
	    $res["messagem"] = "$e->getCode() - $e->getMessage()";
	}
	
	if (isset($_POST['novo'])) {
		$ret = $con->prepare("SELECT IF(COUNT(arcod_entrega) > 0, LPAD(MAX(arcod_entrega) + 1, 3, '0'), '001') AS arcod_entrega FROM re17 
				WHERE arcodcli = '$arcodcli'");
		$ret->execute();
		$mensagem = $ret->errorInfo();
		$row = $ret->fetch(PDO::FETCH_OBJ);
		$arcod_entrega = $row->arcod_entrega;
		$res["arcod_entrega"] = $arcod_entrega;
		
		$arendcli = $_POST['arendcli'];
		$arnumend = $_POST['arnumend'];
		$arbaicli = $_POST['arbaicli'];
		$arcidcli = $_POST['arcidcli'];
		$ar_ufcli = $_POST['ar_ufcli'];
		$arcepcli = $_POST['arcepcli'];
		$artelcli = $_POST['artelcli'];
		if (strlen($_POST['arobserv']) == 0) {
			$arobserv = null;
		} else {
			$arobserv = $_POST['arobserv'];
		}
		//$arlatitude = $_POST['arlatitude'];
		//$arlongetude = $_POST['arlongetude'];
		
		$ret = $con->prepare("INSERT INTO re17 (arcod_entrega, arcodcli, arendcli, arbaicli, arcidcli, ar_ufcli, arcepcli, artelcli, 
				arnumend, arobserv) VALUES ('$arcod_entrega', '$arcodcli', '$arendcli', '$arbaicli', '$arcidcli', '$ar_ufcli', '$arcepcli', 
				'$artelcli', '$arnumend', '$arobserv')");
	} elseif (isset($_POST['atualizar'])) {
		$arcod_entrega = $_POST['arcod_entrega'];
		$arcodcli = $_POST['arcodcli'];
		$arendcli = $_POST['arendcli'];
		$arnumend = $_POST['arnumend'];
		$arbaicli = $_POST['arbaicli'];
		$arcidcli = $_POST['arcidcli'];
		$ar_ufcli = $_POST['ar_ufcli'];
		$arcepcli = $_POST['arcepcli'];
		$artelcli = $_POST['artelcli'];
		$arobserv = $_POST['arobserv'];
		//$arlatitude = $_POST['arlatitude'];
		//$arlongetude = $_POST['arlongetude'];
		
		$ret = $con->prepare("UPDATE re17 SET arendcli = '$arendcli', arnumend = '$arnumend', arbaicli = '$arbaicli', arcidcli = '$arcidcli', 
				ar_ufcli = '$ar_ufcli', arcepcli = '$arcepcli', artelcli = '$artelcli' WHERE arcod_entrega = '$arcod_entrega' AND arcodcli = '$arcodcli'");
	} else {		
		$ret = $con->prepare("SELECT * FROM re17 WHERE arcodcli = '$arcodcli' AND sr_deleted != 'T' ORDER BY arcod_entrega");
	}
	$ret->execute();
	$mensagem = $ret->errorInfo();
	if($ret->rowCount() > 0) {
		$res["enderecos_entrega"] = array();
		while ($row = $ret->fetch(PDO::FETCH_ASSOC)) {
			array_push($res["enderecos_entrega"], $row);
		}
	    $res["sucesso"] = 1;
	} else {
	    $res["sucesso"] = 0;
	    $res["mensagem"] = $mensagem[2];
	}
	echo json_encode($res);
	$con = null;
?>

