<?php
require('conexion.php');

$res='';
if(isset($_POST['prod']) && isset($_POST['dateIni']) && isset($_POST['dateFin'])){
    
    $id_prod=$_POST['prod'];
    $from_date=$_POST['dateIni'];
    $to_date=$_POST['dateFin'];
    $unions="";
    $timestamp = strtotime($to_date);
    $year = date("Y", $timestamp);

    
    $timestamp2 = strtotime($from_date);
    $year2 = date("Y", $timestamp);

    if ($year == $year2 && $year != '') {
        $query = query("SHOW TABLES LIKE 'historico_$year';");
        if ($query->num_rows > 0 ) {
            $query = "SELECT pdn.id_producto,pro_nombre, ntv.id, ntv.ntv_no_nota, ntv_fecha_creacion, 
            ntv_hora_ini,FORMAT(ntv_subtotal,2) ntv_subtotal, FORMAT(ntv_total_nota,2) ntv_total_nota
            , ntv_no_mesa, ntv_no_personas, ntv_tarjeta, ntv_efectivo, SUM(pdn.pdn_cantidad) as pdn_cantidad, 
            SUM(pd.pro_precio_venta * pdn.pdn_cantidad) 'total' FROM historico_$year AS pdn
            INNER JOIN notas_venta AS ntv ON ntv.id = pdn.id_nota_venta
            INNER JOIN productos AS pd ON pd.id = pdn.id_producto 
            WHERE pdn.id_producto='$id_prod' AND pdn.pdn_estatus NOT IN ('eliminado','cancelado')
            AND ntv_estatus IN ('finalizado','impreso') AND ntv.ntv_fecha_creacion BETWEEN  '$from_date' AND '$to_date' 
			GROUP BY ntv.ntv_no_nota;";
            $result = query($query);
            $i = 0;
            while($row = $result->fetch_assoc()){
                $rowdata[$i] = $row;
                $i++;
            }
        }else{
            $query = "SELECT pdn.id_producto,pro_nombre, ntv.id, ntv.ntv_no_nota, ntv_fecha_creacion, 
            ntv_hora_ini,FORMAT(ntv_subtotal,2) ntv_subtotal, FORMAT(ntv_total_nota,2) ntv_total_nota
            , ntv_no_mesa, ntv_no_personas, ntv_tarjeta, ntv_efectivo, SUM(pdn.pdn_cantidad) as pdn_cantidad, 
            SUM(pd.pro_precio_venta * pdn.pdn_cantidad) 'total', DATE(pdn.created_at) fecha_creacion  FROM productos_nota AS pdn
            INNER JOIN notas_venta AS ntv ON ntv.id = pdn.id_nota_venta
            INNER JOIN productos AS pd ON pd.id = pdn.id_producto 
            WHERE pdn.id_producto='$id_prod' 
            AND pdn.pdn_estatus NOT IN ('eliminado','cancelado')
            AND ntv_estatus IN ('finalizado','impreso')
            AND DATE(pdn.created_at) BETWEEN  '$from_date' AND '$to_date' 
            GROUP BY ntv.ntv_no_nota;";
            $result = query($query);
            $i = 0;
            while($row = $result->fetch_assoc()){
                $rowdata[$i] = $row;
                $i++;
            }
        }
    }
    
    if ($i>0){
        $res =  json_encode($rowdata,JSON_UNESCAPED_UNICODE);
    } else {
        $res =  '[{"id_producto":"0"}]';	
    }
    
}

echo $res;
?>