<?php 
require_once 'db.php';
require_once 'Producto.php';
require_once 'Cliente.php';
class ventas extends conn { 

public function ultimonfactura(){
    $conn = parent::crearconn();
    $sql = "select max(N_Factura) from factura";
 $resulta = $conn->query($sql);
  $re=mysqli_fetch_row($resulta)[0];
 return $re;
}


public function getAllVenta()
{
$conn = parent::crearconn();
$sql = " SELECT f.N_Factura, f.Fecha, f.Total, f.ID_Cliente, us.Username as User_Vendedor, d.Nombre as Nombre_cliente, d.Cedula as Cedula_cliente  from factura f
INNER join cliente cl  on f.ID_Cliente = cl.ID 
INNER join usuario us  on f.ID_Usuario = us.ID 
INNER JOIN datos_personales d on cl.CI_Datos = d.Cedula"; 

$result = $conn->query($sql);
$ventas = array();
if ($result->num_rows > 0) {
     while ($row = $result->fetch_assoc()) {
         $ventas[] = $row;
       }   
    }   
    return $ventas;
} 

public function getAllDetalles($idventa)
{
$conn = parent::crearconn();
$sql = " SELECT d.Cantidad, d.Precio_Unt, d.subtotal, d.ID_Factura, d.Cod_Productos, p.Nombre as Nombre_Producto from detalles_factura d inner join productos p on d.Cod_Productos = p.Cod where ID_Factura = '$idventa' "; 

$result = $conn->query($sql);

$detalles = array();
if ($result->num_rows > 0) {
     while ($row = $result->fetch_assoc()) {
         $detalles[] = $row;
       }   
    }   
    return $detalles;
}

public function getVentasConDetalles($f1,$f2,$vereliminados)
{
$conn = parent::crearconn();
$sql = "SELECT f.N_Factura, f.Fecha, f.Total, f.delet_venta,f.ID_Cliente, us.Username as User_Vendedor, d.Nombre as Nombre_cliente, d.Cedula as Cedula_cliente  
FROM factura f
INNER JOIN cliente cl ON f.ID_Cliente = cl.ID 
INNER JOIN usuario us ON f.ID_Usuario = us.ID 
INNER JOIN datos_personales d ON cl.CI_Datos = d.Cedula 
WHERE f.Fecha >= '$f1 00:00:00' AND f.Fecha <= '$f2 23:59:59' "; 

 if ($vereliminados) {
        $sql .= " AND f.delet_venta IS NOT NULL";
    } else {
        $sql .= " AND f.delet_venta IS NULL";
    }

    $result = $conn->query($sql);
    $ventas = array();

  if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $idVenta = $row['N_Factura'];
            $row['detalles'] = $this->getAllDetalles($idVenta);
            $ventas[] = $row;
        }
    }
    
    return $ventas;


  }

  public function crearVenta($carrito, $totaldolar, $cliente,$vendedor){
 	  $conn = parent::crearconn();
         foreach ($cliente as $c) {
             
         
        $query = "insert into factura values (null, now(), $totaldolar,'".$c->id."',$vendedor,null)";
       $result = $conn->query($query);
  }
$sql = "select max(N_Factura) from factura";
 $resulta = $conn->query($sql);

$idultimaventa= 0;
if($reg= mysqli_fetch_array($resulta)) {
	$idultimaventa = $reg[0];
}

        foreach ($carrito as $p) {
            
            $query2 = "insert into detalles_factura values (null,
             '".$p->cantidad."',
             '".$p->precio."',
            '".$idultimaventa."',
             '".$p->id."',
            '".$p->subTotal."',null)";
$result2 = $conn->query($query2);
$this->actualizarStock($p->id,$p->cantidad);
        }
      
    }   


    public function actualizarStock($id, $stockADescontar) {
   $conn = parent::crearconn();
    $query = "select  Stock_Actual from productos WHERE Cod = '$id'";
    $r = $conn->query($query);

    $stockActual= 0; 

  if ($reg=mysqli_fetch_array($r)){
      $stockActual = $reg[0];
       }
 $stockActual -= $stockADescontar ; 


  $query = " UPDATE productos set Stock_Actual = $stockActual where Cod = '$id' "; 
  $r = $conn->query($query);
    }

public function deleteventa($ventaId,$producto,$cantidad)
{
$conn = parent::crearconn();
 $query = "UPDATE `detalles_factura` SET `delet_venta` = now() WHERE ID_Factura = '$ventaId'";
    $r = $conn->query($query);
$sql = "UPDATE `factura` SET `delet_venta` = now() WHERE N_Factura = '$ventaId'";
$resultado = $conn->query($sql);


 foreach ($producto as $key => $value) {
        $this->actualizarStockeliminado($value, $cantidad[$key]);
    }
  
 
  
     


}

    public function actualizarStockeliminado($id, $stockAgregar) {
 $conn = parent::crearconn();
      $query2 = "select Stock_Actual from productos WHERE Cod = '$id'";
 $r = $conn->query($query2);
 $stockActual= 0; 

 if ($reg=mysqli_fetch_array($r)){
      $stockActual = $reg[0];
       }
 $stockActual +=  $stockAgregar ; 


$query3 = " UPDATE productos set Stock_Actual = $stockActual where Cod = '$id' "; 
  $r = $conn->query($query3);
}


public function consultar_venta($f1,$f2,$vereliminados)
    {
            $conn = parent::crearconn();
      
            $sql = "SELECT f.N_Factura, f.Fecha, f.Total, f.delet_venta,f.ID_Cliente, us.Username as User_Vendedor, d.Nombre as Nombre_cliente, d.Cedula as Cedula_cliente  
FROM factura f
INNER JOIN cliente cl ON f.ID_Cliente = cl.ID 
INNER JOIN usuario us ON f.ID_Usuario = us.ID 
INNER JOIN datos_personales d ON cl.CI_Datos = d.Cedula 
WHERE f.Fecha >= '$f1 00:00:00' AND f.Fecha <= '$f2 23:59:59' "; 
if ($vereliminados == 'true') {
        $sql .= " AND f.delet_venta IS NOT NULL";
    } else {
        $sql .= " AND f.delet_venta IS NULL";
    }

            $result= mysqli_query($conn,$sql);

              return $result ;
    }


}


?>