<?php
	/*-------------------------
	Autor: Obed Alvarado
	Web: obedalvarado.pw
	Mail: info@obedalvarado.pw
	---------------------------*/
session_start();
// $user_id=$_SESSION['user_id'];
$sale_id= $_SESSION['sale_id'];
if (isset($_POST['id'])){$id=$_POST['id'];}
if (isset($_POST['cantidad'])){$qty=intval($_POST['cantidad']);}
if (isset($_POST['precio_venta'])){floatval($unit_price=$_POST['precio_venta']);}

	/* Connect To Database*/
	require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
	require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos
	require_once ("../libraries/inventory.php");//Contiene funcion que controla stock en el inventario
	
if (!empty($id) and !empty($qty) and !empty($unit_price))
{
	$stock=get_stock($id);
	if ($stock<$qty){
		?>
		<script>alert('No cuenta con suficiente stock para realizar la venta');</script>
		<?php	
	} else{

		if(validarTablaVentas($id, $sale_id)){  //validar con id de sale
			global $con;
			 $sql=mysqli_query($con, "UPDATE  sale_product  set qty =qty+'".$qty."'  WHERE product_id='".$id."' and sale_id='".$sale_id."'");
		}else{
			$insert=mysqli_query($con, "INSERT INTO sale_product (sale_id,product_id,qty,unit_price) VALUES ('$sale_id','$id','$qty','$unit_price')");				
		}

		remove_inventory($id,$qty );//Disminuye la cantidad en el inventario;
		
	}
}


if (isset($_GET['id']))//codigo elimina un elemento de la DB
{
	$sale_product_id=intval($_GET['id']);	
	$sql_sale=mysqli_query($con,"select product_id, qty from  sale_product where sale_product_id='".$sale_product_id."'");
	$rw_sale=mysqli_fetch_array($sql_sale);
	$product_id_remove=$rw_sale['product_id'];
	$qty_remove=$rw_sale['qty'];
	$delete=mysqli_query($con, "DELETE FROM sale_product WHERE sale_product_id='".$sale_product_id."'");	
	
	add_inventory($product_id_remove, $qty_remove);//Agrego producto al inventario
}


if (isset($_POST['key'])){
	$key=intval($_POST['key']);
	if ($key==1){
		$customer_id=intval($_POST['value']);
		$str="customer_id='$customer_id'";
	} else if ($key==2){
		$tax_value=floatval($_POST['value']);
		$str="tax_value='$tax_value'";
	}
	$update_sale=mysqli_query($con,"update sales set $str where sale_id='$sale_id'");
}



if (isset($_GET['payment'])){
	$payment=intval($_GET['payment']);
	
	$update_sale=mysqli_query($con,"update sales set payment_method='$payment' where sale_id='$sale_id'");
}
	/*Datos de la empresa*/
		$sql_empresa=mysqli_query($con,"SELECT * FROM  business_profile, currencies where business_profile.currency_id=currencies.id and business_profile.id=1");
		$rw_empresa=mysqli_fetch_array($sql_empresa);
		$moneda=$rw_empresa["symbol"];
		
	/*Fin datos empresa*/
	$tax=get_id("sales","tax_value","sale_id",$sale_id);
	$descuento=floatval($_REQUEST['descuento']);

if (isset($_GET['cantidad'])){
	$cantidad = intval($_GET['cantidad']);
	$product_id = intval($_GET['idproducto']);
	$sale_number = intval($_GET['sale_number']);
 	$stock=get_stock($product_id);	
	if ($cantidad==0) {
 			?>
 			<script>alert('Cantidad debe ser mayor a 0');</script>
 			<?php
 			$cantidad=1;
 	}

	if ($stock<$cantidad){
		?>
		<script>alert('No cuenta con suficiente stock para realizar la venta');</script>
		<?php	
	} else{
	
		if(validarTablaVentas($product_id, $sale_id )){ //validar con el id de ventas
			global $con;			
			 
			 $sql2=mysqli_query($con,"select * from sale_product where product_id='".$product_id."'");
			$rw=mysqli_fetch_array($sql2);
			$product_id_sale=$rw['product_id'];
			$qty=$rw['qty'];//Cantidad encontrada en el inventar

			

				$sql=mysqli_query($con, "UPDATE  sale_product  set qty ='".$cantidad."'  WHERE product_id='".$product_id."' and sale_id='".$sale_id."'");

				remove_inventory($product_id,$cantidad );

				add_inventory($product_id_sale, $qty);
				
				 
			 
	 	}
	}
}

if (isset($_POST['barcode'])){
	$barcode=mysqli_real_escape_string($con,$_POST['barcode']);
	$barcode_qty=intval($_POST['barcode_qty']);
	$product_id=get_id('products','product_id','product_code',$barcode);
	$unit_price=get_id('products','selling_price','product_id',$product_id);

	if ($product_id>0){
		$stock=get_stock($product_id);

		
		if ($stock<$barcode_qty){
			?>
			<script>alert('No cuenta con suficiente stock para realizar la venta');</script>
			<?php	
		} else{
		
			if(validarTablaVentas($product_id, $sale_id)){  //validar con id de sale
				global $con;
			 	$sql=mysqli_query($con, "UPDATE  sale_product  set qty =qty+'".$barcode_qty."'  WHERE product_id='".$product_id."' and sale_id='".$sale_id."'");
			}else{
				$insert=mysqli_query($con, "INSERT INTO sale_product (sale_id,product_id,qty,unit_price) VALUES ('$sale_id','$product_id','$barcode_qty','$unit_price')");				
			}
				remove_inventory($product_id, $barcode_qty );//Disminuye la cantidad en el inventario;

					
		}
	} else {
		echo "<script>alert('Producto no encontrado.')</script>";
	}
}
	
	
?>

<table class=" table" id="cartTable">
    <thead>
        <tr>
            <th width=""><h5><b>#</b></h5></th>
            <th width="" ><h5>PRODUCTO </h5></th>
            <th width=""><h5> CANT.</th>
            <th width="" ><h5> P. UNIT. </h5></th> 
            <th width="" ><h5> P.TOTAl</h5></th> 
            <th width="" ></th>           
            
        </tr>
    </thead>
    <tbody class="">
<?php	
	$sql_taxes=mysqli_query($con,"select * from taxes where status=1");
	$sumador_total=0;
	$sql=mysqli_query($con, "select * from products, sale_product where products.product_id=sale_product.product_id and sale_product.sale_id='$sale_id'");
	$numsItems =0;
	$numsProductos=1;
	while ($row=mysqli_fetch_array($sql))
	{
	$product_id=$row['product_id'];
	$sale_product_id=$row["sale_product_id"];
	$product_code=$row['product_code'];
	$qty=$row['qty'];
	$product_name=$row['product_name'];
	$unit_price=number_format($row['unit_price'],$currency_format['precision_currency'],'.','');

	$precio_total=$unit_price*$qty;
	$precio_total=number_format($precio_total,$currency_format['precision_currency'],'.','');//Precio total formateado
	$sumador_total+=$precio_total;//Sumador
	
?>                          
                        
            <tr>
                <td width=""><?php echo $numsProductos;?></td>
                <td width=""><?php echo $product_name;?></td>
                <td  width=""class="">                	
                   		 <input style="width: 65px" class="form-control input-sm" oninput="updateCant(this.value, <?php echo $product_id;?>);"  id="cant" type="number" value="<?php echo $qty;?>">
                    
                	<!-- </div> -->
                </td>
                <td><span class="pull-right"> <?php echo number_format($unit_price,$currency_format['precision_currency'],$currency_format['decimal_separator'],$currency_format['thousand_separator']);?> </span></td>
                <td><span class="pull-right"> <?php echo number_format($precio_total,$currency_format['precision_currency'],$currency_format['decimal_separator'],$currency_format['thousand_separator']);?> </span></td>
                
                <td><button class="btn btn-danger btn-xs" onclick="eliminar('<?php echo $sale_product_id; ?>')"><i class="fa fa-times"></i></button></td>
            </tr>
                
			
		<?php
		$numsProductos++;
		$numsItems++;
	}

	$total_parcial=number_format($sumador_total,$currency_format['precision_currency'],'.','');
	$total_neto=$total_parcial;
	$total_neto=number_format($total_neto,$currency_format['precision_currency'],'.','');
	$precio_descuento =($total_neto*$descuento)/100;


	if($precio_descuento<=0 && $total_neto<=0){
		
	}else{

		if ($precio_descuento >= $total_neto) {
		echo "<script>alert('El descuento no puede ser mayor al precio ');</script>";
		$descuento =0;
		$precio_descuento =0;
		}

	}
	
	
	if($descuento >0) {
			$precio_descuento =($total_neto*$descuento)/100;
			$total_descuento = ($total_neto-$precio_descuento);
			$total_iva = ($total_descuento*$tax)/100;
			$total_compra =($total_descuento+$total_iva);
	}else{

			$total_iva=($total_neto*$tax) / 100;
			$total_iva=number_format($total_iva,$currency_format['precision_currency'],'.','');
			$total_compra=$total_neto+$total_iva;
			$total_compra=number_format($total_compra,$currency_format['precision_currency'],'.','');
	}
	$netos=$total_neto-$precio_descuento;
	$update=mysqli_query($con,"update sales set subtotal='$netos', tax='$total_iva', discount_value='$descuento', total='$total_compra' where sale_id='$sale_id'");
	

?>
</tbody>
   </table>           
 

    <hr>
   <div class="m-t-10" >
       <div class="row" >
           <div class="col-md-4"><label class="control-label">Total Item(s) </label></div>
           <div class="col-md-2">: <sapn id="total"><label class="control-label"><?php echo $numsItems;?></label></sapn></div>
           <?php
           	$validarDescuento =$total_neto;
           	$label="NETO:";           
           		           	
           
           ?>
           <div class="col-md-3"> <label class="control-label"><?php echo $label;?></label> </div>
           <div class="col-md-3">: <span id="price"><label class="control-label"><?php echo number_format($validarDescuento,$currency_format['precision_currency'],$currency_format['decimal_separator'],$currency_format['thousand_separator']);?></label></span></div>
           
		</div>	
	</div>

	<div class="m-t-10">
       <div class="row">
       	<div class="form-group">
           <div class="col-md-4"> <label class="control-label">Descuento(%) </label></div>
           <!-- <div class="col-md-2"></div> -->
            <div class="col-md-4"><input class="form-control input-sm" required pattern="\d+(\.\d{2})?"  type="number" id="descuento" value="<?php echo $descuento ?>" oninput="descuento(this.value)" ></div> 
            <div class="col-md-3 col-md-offset-1">: <span id="price"> <label class="control-label"><?php echo number_format($precio_descuento,$currency_format['precision_currency'],$currency_format['decimal_separator'],$currency_format['thousand_separator']);?></label></span></div>
        </div>               

		</div>	
	</div>			


	<div class="m-t-10">
       <div class="row">            
           <div class="col-md-4"><label class="control-label">IVA(%)</label> </div>
           <div class="col-md-4">
            	<select name="taxes" class="form-control input-sm" id="taxes" onchange="update_sale(2,this.value);">
					<?php
						foreach ($sql_taxes as $valor){
							if ($tax==$valor['value']){
								$selected="selected";
							} else{
								$selected="";
							} 
							echo '<option value="'.$valor['value'].'" '.$selected.'>'.$valor['name']." ".$valor['value'].' %</option>';
						}
					?>
			
				</select> 
			</div>
			<!-- <div class="col-md-2"></div> -->
           <div class="col-md-3 col-md-offset-1">: <span id="price"><label class="control-label"><?php echo number_format($total_iva,$currency_format['precision_currency'],$currency_format['decimal_separator'],$currency_format['thousand_separator']);?></label></span></div>
		</div>	
	</div>		

	 <div class="m-t-10">
       <div class="row">           
           <div class="col-md-3 col-md-offset-6">
           		<h3> <label class="control-label">TOTAL</label> </h3>
           	</div>
           <div class="col-md-3">
           		<h3>
           		 	<label class="control-label">
           		 		<?php echo number_format($total_compra,$currency_format['precision_currency'],$currency_format['decimal_separator'],$currency_format['thousand_separator']);?>
           		 			
           		 	</label>
           		 </h3>           		 
           	</div>

		</div>	
	</div>	
   <div class="button-list pull-right">
        

                        
        <button  data-toggle="modal" data-target="#paymentModel"
         	value="<?php echo $total_compra;?>" 
          	onclick="modalPago(this.value);"
          	id="payButton"
          	 class="btn btn-success waves-effect waves-light">
                        <span class="btn-label"><i class="fa fa-money"></i></span>Pagar
        </button>
    </div>
	 <hr>