<?php
include 'conexion.php';
    $recived = $_REQUEST['cadena'];
    $rcut = explode(",",$recived);
    $mensaje = str_replace(" ","",$rcut[0]);
    $mensajeSeparado = $rcut[0];
    $codigobd = (string)$rcut[1];
    $fecha_hora = $rcut[2];
    $conn = mysqli_connect($server,$user,$pass,$db.$codigobd);
    $header = substr($mensaje,0,6);
    $header = hex2String($header);

    if($header == '308'){
        $bindias = array('0','0','0','0','0','0','0');
        $numChar = hex2String(substr($mensaje,6,2));
        $a = hexdec($numChar)*2;
        $nombreRutina = hex2String(substr($mensaje,8,$a));
        $numAAuxiliar = hex2String(substr($mensaje,8+$a,4));
        $numAlimentadores = hexdec($numAAuxiliar);
        $c = ($numAlimentadores * 3) * 2;
        $alimentadores = hex2String(substr($mensaje,12+$a,$c));
        $arrayAlimentadores;
        $aux = 0;
        for ($i = 0; $i < $numAlimentadores; $i++)
        {
            $arrayAlimentadores[$i] = substr($alimentadores,$aux,3);
            $aux = $aux + 3;
        }
        $indexNewStart = 12+$a+$c;
        $diasAlimentacion = decbin(hexdec(hex2String(substr($mensaje,$indexNewStart,4)))); $indexNewStart += 4;
        $q = 0;
        (string)$binDiasAlimentacion = '';
        for($i = strlen($diasAlimentacion)-1; $i>=0; $i--){
            $bindias[$q] = substr($diasAlimentacion,$i,1);
            $q++;
        }
        foreach (array_reverse($bindias) as $dia) {
            $binDiasAlimentacion .= $dia;
        }
        $horaInicio = hour2min(hex2float(substr($mensaje,$indexNewStart,8))); $indexNewStart += 8;
        $horaFin = hour2min(hex2float(substr($mensaje,$indexNewStart,8))); $indexNewStart += 8;
        $intervalo = hex2float(substr($mensaje,$indexNewStart,8)); $indexNewStart += 8;
        $duracion = hex2float(substr($mensaje,$indexNewStart,8)); $indexNewStart += 8;
        $velMin = hex2float(substr($mensaje,$indexNewStart,8)); $indexNewStart += 8;
        $velMax = hex2float(substr($mensaje,$indexNewStart,8)); $indexNewStart += 8;
        $distribucion = hex2String(substr($mensaje,$indexNewStart,2));
        /*echo 'Dias de Alimentación: '.$binDiasAlimentacion; echo "<br>"; echo 'Hora Inicio: '.$horaInicio; echo "<br>"; echo 'Hora Fin: '.$horaFin; echo "<br>"; echo 'Intervalo en Segundos: '.$intervalo; echo "<br>"; echo 'Duración en Segundos: '.$duracion; echo "<br>"; echo 'Velocidad Minima en %'.$velMin; echo "<br>"; echo 'Velocidad Máxima en %'.$velMax; echo "<br>"; echo 'Distribución: '.$distribucion; echo "<br>";*/
        $sql = "SELECT idvelocidad FROM velocidades WHERE porcentaje_min = '$velMin' AND porcentaje_max = '$velMax';";
        $resultado = mysqli_query($conn,$sql);
        $fila = mysqli_fetch_row($resultado);
        $idVelocidad = $fila[0];
        mysqli_free_result($resultado);
        $porcion = $duracion * 40;
        $pizza  = "porción1 porción2 porción3 porción4 porción5 porción6";
        $parts = explode(" ", $fecha_hora);
        $fecha = $parts[0];
        $hora = $parts[1];
        $check = false;
        $sql = "INSERT INTO rutinas_ejecucion(nombre,intervalo,duracion,porcion,dias_alimentacion,hora_inicio,hora_final,distribucion_uniforme,idvelocidad,hora_cambio,fecha_cambio,rutina_diaria,omitido,adelantado) VALUES('".$nombreRutina."','".$intervalo."','".$duracion."','".$porcion."','".$binDiasAlimentacion."','".$horaInicio."','".$horaFin."','".$distribucion."','".$idVelocidad."','".$hora."','".$fecha."','0','0','0');";
        if (mysqli_query($conn,$sql)) {
            $idgenerado = mysqli_insert_id($conn);
            // echo "Record added successfully";
            // echo "<br>";
            $check = true;
        }
        else {
            echo "Error adding record: " . $conn->error;
            echo "<br>";
            $check = false;
        }
        foreach($arrayAlimentadores as $idAlimentador){
            $update = "UPDATE alimentadores SET idrutina = '".$idgenerado."' WHERE idalimentador_disp = '".$idAlimentador."';";
            if ($conn->query($update) === TRUE) {
                // echo "Record updated successfully";
                // echo "<br>";
                $check = true;
            } else {
                echo "Error updating record: " . $conn->error;
                echo "<br>";
                $check = false;
            }
        }
        if($check){
            echo '1';
        }else{
            echo '0';
        }
    }
    
    
        
    elseif($header == '38B'){

        $numChar = hex2String(substr($mensaje,6,2));
        $a = hexdec($numChar)*2;
        $nombreRutina = hex2String(substr($mensaje,8,$a));
        $numAAuxiliar = hex2String(substr($mensaje,8+$a,4));
        $numAlimentadores = hexdec($numAAuxiliar);
        $c = ($numAlimentadores * 3) * 2;
        $alimentadores = hex2String(substr($mensaje,12+$a,$c));
        $arrayAlimentadores;
        $aux = 0;
        for ($i = 0; $i < $numAlimentadores; $i++)
        {
            $arrayAlimentadores[$i] = substr($alimentadores,$aux,3);
            $aux = $aux + 3;
        }

        $parts = explode(" ", $fecha_hora);
        $fecha = $parts[0];
        $hora = $parts[1];
        $check = false;
        $idvelocidad = 1;
       $sql = "INSERT INTO rutinas_ejecucion(nombre,idvelocidad,hora_cambio,fecha_cambio,rutina_diaria,cadena) VALUES('".$nombreRutina."',".$idvelocidad.",'".$hora."','".$fecha."','1','".$mensajeSeparado."');";


        if (mysqli_query($conn,$sql)) {
            $idgenerado = mysqli_insert_id($conn);           
            $check = true;
        }
        else {
            echo "Error adding record: " . $conn->error;
            echo "<br>";
            $check = false;
        }
        foreach($arrayAlimentadores as $idAlimentador){
            $update = "UPDATE alimentadores SET idrutina = '".$idgenerado."' WHERE idalimentador_disp = '".$idAlimentador."';";
            if ($conn->query($update) === TRUE) {
                $check = true;
            } else {
                echo "Error updating record: " . $conn->error;
                echo "<br>";
                $check = false;
            }
        }
        if($check){
            echo '1';
        }else{
            echo '0';
        }
    }//Fin header 38B
        
    elseif($header == '322'){
        $check = false;
        $numAlimentadores = hexdec(hex2String(substr($mensaje,12,4)));
        $alimentadores = hex2String(substr($mensaje,12+4,($numAlimentadores*2)*3));
        $arrayAlimentadores;
        $arrayNuevoTotalAli;
        $aux = 0;
        for($i = 0; $i < $numAlimentadores; $i++){
            $arrayAlimentadores[$i] = substr($alimentadores,$aux,3);
            $aux += 3;
        }
        $index = (12+4) + (($numAlimentadores*2) * 3);
        $alimLanzado = (string)hex2float(substr($mensaje,$index,8)); $index += 8;

        $totales = substr($mensaje,$index,8*$numAlimentadores);
        $aux2 = 0;
        for($i = 0; $i < $numAlimentadores; $i++){
           $arrayNuevoTotalAli[$i] = (string)hex2float(substr($totales,$aux2,8));
           $aux2 += 8;
        }

        $nuevoTotal = (string)hex2float(substr($mensaje,$index,8));
        $idAlimentador = 0;
        $idMarcaAlimento = 0;
        $idAlimento = 0;
        $parts = explode(" ", $fecha_hora);
        $fecha = $parts[0];
        $hora = $parts[1];
        $added = 0;
        if(strpos($alimLanzado  ,'-') !== false){
            $added = 0;
        }else{
            $added = 1;
        }
        $count = 0;
        foreach($arrayAlimentadores as $s){
            $sql = "SELECT a.idalimentador,b.idmarcas_alimento,a.idalimento FROM alimentadores a INNER JOIN alimento b ON a.idalimento = b.idalimento WHERE a.idalimentador_disp = '$s'";
            $resultado = mysqli_query($conn,$sql);
            $fila = mysqli_fetch_row($resultado);
            $idAlimentador = $fila[0];
            $idMarcaAlimento = $fila[1];
            $idAlimento = $fila[2];
            mysqli_free_result($resultado);
            if($added == 0){
                $alimLanzado = trim($alimLanzado, '-');
                //str_replace($alimLanzado,'-','');
                $sql = "INSERT INTO historial_alimento(cantidad_lanzada,total,fecha,hora,idalimentador,idmarcas_alimento) VALUES ('$alimLanzado',NULL,'$fecha','$hora','$idAlimentador','$idMarcaAlimento');";
                if (mysqli_query($conn,$sql)) {
                    // echo "Record added successfully";
                    // echo "<br>";
                    $check = true;
                }
                else {
                    // echo "Error adding record: " . $conn->error;
                    // echo "<br>";
                    $check = false;
                }
            }
            $update = "UPDATE `alimento` SET `cantidad_total`= '$arrayNuevoTotalAli[$count]' WHERE `idalimento` = '$idAlimento';";
            if ($conn->query($update) === TRUE) {
                //echo "Record updated successfully";
                //echo "<br>";
                $check = true;
            } else {
                //echo "Error updating record: " . $conn->error;
                //echo "<br>";
                $check = false;
            }
            $count++;
        }
        if($check){
            echo '1';
        }else{
            echo '0';
        }
    }
    else if($header == '320'){
        $parts = explode(" ", $fecha_hora);
        $fecha = $parts[0];
        $hora = $parts[1];
        $alimentador = hex2String(substr($mensaje,6,6));
        $index = 12;
        $motor1 = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $motor2 = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $bateria = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $panel = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $cant_alimento = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $tiempo_restante = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $update = "UPDATE `alimentadores` SET `motor1` = '$motor1', `motor2` = '$motor2', `bateria` = '$bateria', 
        `panel` = '$panel', `senal` = '1' WHERE `idalimentador_disp` = '$alimentador';";
        if ($conn->query($update) === TRUE) {
            // echo "Record updated successfully";
            // echo "<br>";
            $check = true;
            $idAlimentador = 0;
            $idMarcaAlimento = 0;
            $idAlimento = 0;
            $cantidad_total = 0;
            $sql = "SELECT a.idalimentador,b.idmarcas_alimento,a.idalimento,b.cantidad_total FROM alimentadores a INNER JOIN alimento b ON a.idalimento = b.idalimento WHERE a.idalimentador_disp = '$alimentador'";
            $resultado = mysqli_query($conn,$sql);
            $fila = mysqli_fetch_row($resultado);
            $idAlimentador = $fila[0];
            $idMarcaAlimento = $fila[1];
            $idAlimento = $fila[2];
            $cantidad_total = $fila[3];
            mysqli_free_result($resultado);
            $check = true;
            /*$sql = "INSERT INTO historial_alimento(cantidad_lanzada,fecha,hora,idalimentador,idmarcas_alimento) VALUES ('$cant_alimento','$fecha','$hora','$idAlimentador','$idMarcaAlimento');";
            if (mysqli_query($conn,$sql)) {
                // echo "Record added successfully";
                // echo "<br>";
                $check = true;
                $resta;
                if ($cantidad_total < $cant_alimento)
                {
                    $resta = 0;
                }
                else
                {
                    $resta = $cantidad_total - $cant_alimento;
                }
                $update = "UPDATE `alimento` SET `cantidad_total`= '$resta' WHERE `idalimento` = '$idAlimento';";
                if ($conn->query($update) === TRUE) {
                    // echo "Record updated successfully";
                    // echo "<br>";
                    $check = true;
                } else {
                    // echo "Error updating record: " . $conn->error;
                    // echo "<br>";
                    $check = false;
                }
            }
            else {
                // echo "Error adding record: " . $conn->error;
                // echo "<br>";
                $check = false;
            }*/
            
        } else {
            // echo "Error updating record: " . $conn->error;
            // echo "<br>";
            $check = false;
        }
        if($check){
            echo '1';
        }else{
            echo '0';
        }
    }
    else if($header == '388'){
        $monitor = hex2String(substr($mensaje,6,6));
        $alimentador = hex2String(substr($mensaje,12,6));
        $idRutina = 0;
        $countRutinas = 0;
        $sql = "SELECT idrutina FROM alimentadores WHERE idalimentador_disp = '$alimentador';";
        $resultado = mysqli_query($conn,$sql);
        $fila = mysqli_fetch_row($resultado);
        $idRutina = $fila[0];
        mysqli_free_result($resultado);
        $update = "UPDATE `alimentadores` SET `idrutina`= NULL WHERE `idalimentador_disp` = '$alimentador';";
        //echo $update;
        if ($conn->query($update) === TRUE) {
            $check = true;
            $sql = "SELECT COUNT(*) FROM alimentadores WHERE idrutina = '$idRutina'";
            $resultado = mysqli_query($conn,$sql);
            $fila = mysqli_fetch_row($resultado);
            $countRutinas = $fila[0];
            mysqli_free_result($resultado);
            if($countRutinas == 0){
                $delete = "DELETE FROM `rutinas_ejecucion` WHERE `idrutina` = '$idRutina';";
                if ($conn->query($delete) === TRUE) {
                    $check = true;
                }else{
                    $check = true;
                    // echo "Error updating record: " . $conn->error;
                }
            }else{
                $check = true;
            }
        }else {
            // echo "Error updating record: " . $conn->error;
            // echo "<br>";
            $check = false;
        }
        if($check){
            echo '1';
        }else{
            echo '0';
        }
    }else if($header == '302'){
        $parts = explode(" ", $fecha_hora);
        $fecha = $parts[0];
        $hora = $parts[1];
        $alimentador = hex2String(substr($mensaje,6,6));
        $index = 12;
        $motor1 = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $motor2 = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $bateria = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $panel = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $cant_alimento = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $tiempo_restante = (string)hex2float(substr($mensaje,$index,8)); $index += 8;
        $update = "UPDATE `alimentadores` SET `motor1` = '$motor1', `motor2` = '$motor2', `bateria` = '$bateria', 
        `panel` = '$panel', `senal` = '1' WHERE `idalimentador_disp` = '$alimentador';";
        if ($conn->query($update) === TRUE) {
            // echo "Record updated successfully";
            // echo "<br>";
            $check = true;
            $idAlimentador = 0;
            $idMarcaAlimento = 0;
            $idAlimento = 0;
            $cantidad_total = 0;
            $sql = "SELECT a.idalimentador,b.idmarcas_alimento,a.idalimento,b.cantidad_total,a.nombre,m.grxseg FROM alimentadores a INNER JOIN alimento b ON a.idalimento = b.idalimento INNER JOIN marcas_alimento m ON b.idmarcas_alimento = m.idmarcas_alimento WHERE a.idalimentador_disp = '$alimentador'";
            $resultado = mysqli_query($conn,$sql);
            $fila = mysqli_fetch_row($resultado);
            $idAlimentador = $fila[0];
            $idMarcaAlimento = $fila[1];
            $idAlimento = $fila[2];
            $cantidad_total = $fila[3];
            $nombreAlimentador = $fila[4];
            $grxseg = $fila[5];
            mysqli_free_result($resultado);
            $check = true;
            //
            $segundos = intval($cant_alimento) / 40;
            $cant_alimento = ($segundos * intval($grxseg));
            //
            $sql = "INSERT INTO historial_alimento(cantidad_lanzada,fecha,hora,idalimentador,idmarcas_alimento) VALUES ('$cant_alimento','$fecha','$hora','$idAlimentador','$idMarcaAlimento');";
            if (mysqli_query($conn,$sql)) {
                // echo "Record added successfully";
                // echo "<br>";
                $check = true;
                $resta;
                if ($cantidad_total < $cant_alimento)
                {
                    $resta = 0;
                }
                else
                {
                    $resta = $cantidad_total - $cant_alimento;
                }
                $update = "UPDATE `alimento` SET `cantidad_total`= '$resta' WHERE `idalimento` = '$idAlimento';";
                if ($conn->query($update) === TRUE) {
                    // echo "Record updated successfully";
                    // echo "<br>";
                    $check = true;
                } else {
                    // echo "Error updating record: " . $conn->error;
                    // echo "<br>";
                    $check = false;
                }
            }
            else {
                // echo "Error adding record: " . $conn->error;
                // echo "<br>";
                $check = false;
            }
            
        } else {
            // echo "Error updating record: " . $conn->error;
            // echo "<br>";
            $check = false;
        }
        if($check){
            echo '1';
        }else{
            echo '0';
        }
    }

    function hour2min($time) {
        $format = '%02d:%02d';
        if ($time < 1) {
            return;
        }
        $hours = floor($time / 60);
        $minutes = ($time % 60);
        return sprintf($format, $hours, $minutes);
    }

    function hex2float($strHex) {
        $hex = sscanf($strHex, "%02x%02x%02x%02x");
        $hex = array_reverse($hex);
        $bin = implode('', array_map('chr', $hex));
        $array = unpack("f", $bin);
        return $array[1];
    }

    function hex2ByteArray($hexString) {
        $string = hex2bin($hexString);
        return unpack('C*', $string);
    }

    function byteArray2String($byteArray) {
        $chars = array_map("chr", $byteArray);
        return join($chars);
    }

    function string2Hex($string) {
        return bin2hex($string);
    }

    function hex2String($hexString) {
        return hex2bin($hexString);
    }
?>