<?php
//
// Gravar o codigo de barras
Function GravarCodBar($nCodCad, $a_ListaBar) {
   $nBar_CodigoN=0;
   $RowT = MYSQL_QUERY("SELECT BAR_SEQUEN FROM cad_codigo_barras ORDER BY BAR_SEQUEN DESC LIMIT 1;") or die(MYSQL_ERROR());
   If ($RowT = MYSQL_FETCH_ARRAY($RowT)) {
      $nBar_CodigoN = $RowT[0];
   }
   $a_ListaBarN = ARRAY();
   ForEach ( $a_ListaBar As $aBar ) {
      $a_ListaBarN[ $aBar['BAR_CODBAR'] ] = $aBar;
      
		$RowT = MYSQL_QUERY("SELECT BAR_SEQUEN FROM cad_codigo_barras WHERE BAR_CODBAR='".$aBar['BAR_CODBAR']."' ;") or die(MYSQL_ERROR());
      If ( $RowT = MYSQL_FETCH_ARRAY($RowT) ) {
	     $nBar_Codigo = $RowT[0]+0;
	  } Else {
	    $nBar_CodigoN++;
		 $nBar_Codigo = $nBar_CodigoN;
		 // Cria um novo registro
         MYSQL_QUERY("INSERT INTO cad_codigo_barras(BAR_SEQUEN) VALUES (".$nBar_Codigo."); ") or die(MYSQL_ERROR());
      }
	  MYSQL_QUERY(
         "UPDATE cad_codigo_barras SET ".
		      "BAR_CODITE=".$nCodCad.",".
		      "BAR_CODBAR='".$aBar['BAR_CODBAR']."'".
			 "WHERE BAR_SEQUEN=".$nBar_Codigo.";"
	  ) Or Die(MYSQL_ERROR());
   }
   $RowsT = MYSQL_QUERY("SELECT BAR_CODBAR, BAR_SEQUEN FROM cad_codigo_barras WHERE BAR_CODITE=".$nCodCad." ;") Or Die(MYSQL_ERROR());
   While ( $RowT = MYSQL_FETCH_OBJECT($RowsT) ) {
      If ( ! ISSET($a_ListaBarN[ $RowT->BAR_CODBAR ]) ) {
         MYSQL_QUERY("DELETE FROM cad_codigo_barras WHERE BAR_SEQUEN=".$RowT->BAR_SEQUEN."; ") or die(MYSQL_ERROR());
	  }
   }
}
//
?>