<?php
	session_start();
	require ("./Funciones/funciones.php");
	date_default_timezone_set('America/Mazatlan');
	$conexion = conecta();
	$nombre = $_POST['nombre'];
	$cat = $_POST['cat']; //PROVEEDOR
	$codigo = $_POST['cod'];
	$precio = $_POST['precio']; //PRECIO COMPRA
	$unid = $_POST['unid']; // unidad de  medid
	$moneda = $_POST['moneda']; //1 peso 2 dlls
	$unim = $_POST['unidm'];
	$varios = $_POST['varios'];
	$id = $_POST['id'];
	$desp = $_POST['desper'];
	$totalpaq = $_POST['totalpaq'];
    $costounit = $_POST['costounit'];
    $porcdesp = $_POST['porcdesp'];
    $costunit = $_POST['costunit'];
	$activado = 1;
	$eliminado = 0;
	$destacado= 0;
	$sql= "SELECT * FROM Insumos where IdInsumo ='$id'";
	$res = mysqli_query($conexion,$sql);
	$row = mysqli_num_rows($res);
	if($id==''){
		$sql = mysqli_query($conexion,"INSERT INTO Insumos VALUES (0, '$nombre','$codigo','$cat','$precio','$varios','$moneda','$unid',$unim,NULL,$totalpaq,$costounit,$costunit,$porcdesp,$activado,$eliminado,0 )");
		$res = mysqli_query($conexion,$sql);
		echo "1";
	}else{
		
		$sql= mysqli_query($conexion,"UPDATE Insumos SET Descripcion='$nombre',Codigo='$codigo',IdProveedor='$cat',PrecioCompra='$precio',Moneda='$moneda',UnidPaq='$unid',IdUnidadMed='$unim',TotalPaq = '$totalpaq',CostoUnit ='$costounit',TotalUnit='$costunit',PorcDesp='$porcdesp' WHERE IdInsumo='$id'");
		
		$c = mysqli_query($conexion,"SELECT DISTINCT(IdProducto) FROM ProductoDetalle WHERE IdInsumo = '$id'");
		while($p = mysqli_fetch_array($c)){
			$ctact = 0;
			$subarea = 0;
			$porcmf = 0;
			$porcff = 0;
			$preciofm = 0;
			$precioff = 0;

			$idprod = $p['IdProducto'];
			$s = mysqli_query($conexion,"SELECT * FROM Productos WHERE IdProducto = $idprod");
			$i = mysqli_query($conexion,"SELECT * FROM ProductoDetalle WHERE IdProducto = $idprod ");
			while($fi = mysqli_fetch_array($i)){
				$id = $fi['IdInsumo'];
				$areauni = $fi['Cantidad'];
				$pq = mysqli_query($conexion,"SELECT * FROM Insumos WHERE IdInsumo = $id");
				$fq = mysqli_fetch_array($pq);
				$total = $fq['TotalUnit'];
				$subarea = $total * $areauni;
				$ctact += $subarea;
			}
			$pr = mysqli_fetch_array($s);
			$porcm = $pr['porcm'];
			$porcf = $pr['porc'];
			$costov = $pr['costov'];
			$ctactf = $ctact + $costov;
			$porcmf = $porcm + 100;
			$porcff = $porcf + 100;

			$preciofm = (($ctactf * $porcmf)/100) ;
			$precioff = (($ctactf * $porcff)/100) ;
			$u = mysqli_query($conexion,"UPDATE Productos SET PrecioCompra = '$ctactf', Costtot = '$ctactf',PrecioVenta = '$precioff',preciovm = '$preciofm' WHERE IdProducto = '$idprod'");
		}
		
		echo "1";


		}
	
	
?>
