<?php 
	if(empty($_SESSION['user_vcrx_id']) || !isset($_SESSION['user_vcrx_id'])){
		echo '{"error":"1","msg":"No ha iniciado session"}';	
	}
	else{
		$item=$_POST['itemx'];
		$car_sql='select max(idnum1) as idnum1t from car1 
		where 
		enti="'.$_SESSION['user_vcrx_id'].'" and
		status="-"
		';
		$car_res=$lynk_demo->query($car_sql);
		//echo $car_sql;
		$car_idnum1t=mysqli_result($car_res,0,'idnum1t');
		if($car_idnum1t==0){
			$car_sql='insert into car1(enti,status,iuser,idate)values("'.$_SESSION['user_vcrx_id'].'","-","'.$_SESSION['user_vcrx_id'].'",now())';
			$car_res=$lynk_demo->query($car_sql);
			$car_sql='select max(idnum1) as idnumt from car1 
					where 
					enti="'.$_SESSION['user_vcrx_id'].'" and
					status="-"
					';
			$car_res=$lynk_demo->query($car_sql);
			$car_idnum1t=mysqli_result($car_res,0,'idnumt');
		}
		$car_sql='select max(iddet) as iddet2 from car2
		where 
		idnum2="'.$car_idnum1t.'"
		';
		$car_res=$lynk_demo->query($car_sql);
		$car_iddet2=mysqli_result($car_res,0,'iddet2');
		$car_iddet2++;
		
		$car_sql='select max(cant)as total from car2 where item="'.$item.'" and idnum2="'.$car_idnum1t.'"';
		$car_res=$lynk_demo->query($car_sql);
		$car_total=mysqli_result($car_res,0,'total');
		if($car_total==0){
			$car_sql='insert into car2 (idnum2,iddet,cant,item)values(
			"'.$car_idnum1t.'",
			"'.$car_iddet2.'",
			"1",
			"'.$item.'"
			)';
		}
		
		if($car_total!=0){
			$car_sql='update car2 set cant=cant+1 where idnum2="'.$car_idnum1t.'" and item="'.$item.'"';
		}
		
		if($lynk_demo->query($car_sql)){
			$car_sql='select FORMAT(sum(cant),0) as total from car2 where idnum2="'.$car_idnum1t.'"';
			$car_res=$lynk_demo->query($car_sql);
			$car_total=mysqli_result($car_res,0,'total');
			echo '{"error":"0","msg":"'.$car_total.'"}';
			$car_sql='
			UPDATE car2 
				INNER JOIN item0
				  on  item0.item_codigo=car2.item
				SET 
				car2.puni=item0.item_puni,
				car2.dcto=item0.item_dcto,
				car2.ice=item0.item_iva,
				car2.irbp=item0.item_irbp,
				car2.pvp1=item0.item_pvp
				where car2.idnum2="'.$car_idnum1t.'"
				and car2.item="'.$item.'"';
			//echo $car_sql;
			$lynk_demo->query($car_sql);
		}
		else{echo '{"error":"1","msg":"error de registro"}';}
	
	}
?>