<?php

include_once("server/lib/mod_dbm/package.dbm.php");
include_once("server/class/GeoUtils.php");
include_once("server/class/EeSsManager.php");

class DespachoManager {

    public static function getDespachos($user, $from, $to, $machineId = null) {
        $despachos = array();

        //if($unitId && v


        $query = sprintf("SELECT id_despacho, fecha as fecha_timestamp, DATE_FORMAT(DATE(from_unixtime(fecha)),'%%d/%%m/%%y') as fecha, 
                            DATE_FORMAT(TIME(from_unixtime(fecha)),'%%h:%%m') as hora, u.machine_id as unit_id, u.machine_name as unit_name, u.id_combustible, 
                            vol_despachado, odometro, horometro, 
                            Razón_social,dd.departamento, ll.localidad, e.Dirección, e.Distribuidora, e.Teléfono , u.consumo_esperado, u.metrica
                            FROM combustible_despachos d
                            LEFT JOIN ee_ss e ON e.id_ee_ss = d.id_ee_ss
                            LEFT JOIN geo_departamentos_ee_ss dd ON e.id_departamento = dd.id_departamento
                            LEFT JOIN geo_localidades_ee_ss ll ON e.id_localidad = ll.id_localidad
                            LEFT JOIN machines u ON u.machine_id = d.machine_id
                            WHERE fecha >= %d AND fecha <= %d  %s
                            ORDER BY fecha_timestamp", $from, $to, (($machineId) ? (" AND d.machine_id = " . $machineId) : ""));
        $dao = new dbObject();
        $despachos = $dao->fetchQuery($query);
        if (is_array($despachos) && count($despachos)) {
            foreach ($despachos as $i => $despacho) {
                $despachoPrevio = self::getDespachoPrevio($despacho['unit_id'], $despacho['fecha_timestamp'],$despacho['id_despacho']);
                if ($despachoPrevio) {
                    $despachos[$i]['odometro_previo'] = $despachoPrevio['odometro'];
                    $despachos[$i]['vol_previo'] = $despachoPrevio['vol_despachado'];
                    $despachos[$i]['horometro_previo'] = $despachoPrevio['horometro'];
                    $despachos[$i]['kml'] = ($despacho['vol_despachado']) ? number_format(($despacho['odometro'] - $despachoPrevio['odometro']) / $despacho['vol_despachado'], 2) : "";
                    $despachos[$i]['lh'] = ($despacho['vol_despachado']) ? number_format(($despacho['horometro'] - $despachoPrevio['horometro']) / $despacho['vol_despachado'], 2) : "";
                } else {
                    $despachos[$i]['odometro_previo'] = "";
                    $despachos[$i]['vol_previo'] = "";
                    $despachos[$i]['horometro_previo'] = "";
                    $despachos[$i]['kml'] = "";
                    $despachos[$i]['lh'] = "";
                }
                $despachos[$i]['kml_esperado'] = ($despacho['metrica'] == 1) ? $despacho['consumo_esperado'] : "";
                $despachos[$i]['lh_esperado'] = ($despacho['metrica'] == 2) ? $despacho['consumo_esperado'] : "";
            }
        } 
        
        return $despachos;
    }

    public static function getDespachoPrevio($machineId, $fecha, $idDespacho) {
        $query = sprintf("SELECT * FROM combustible_despachos WHERE fecha < %d AND machine_id = %d AND id_despacho != %d ORDER BY fecha DESC, id_despacho ASC LIMIT 0,1;", $fecha, $machineId, $idDespacho);
        $dao = new dbObject();
        $res = $dao->fetchQuery($query);
        return ($res) ? $res[0] : false;
    }

    public static function getCandidateEESS($machineId, $timestamp) {
        $from = $timestamp;
        $to = $timestamp + 86400;
        $q = sprintf("SELECT gps_timestamp as timestamp, lat, lng FROM log_ignition 
                    WHERE machine_id = %d AND event_id = \"GTIGF\"
                    AND gps_timestamp BETWEEN %d AND %d", $machineId, $from, $to);
        $dao = new dbObject();
        $paradas = $dao->fetchQuery($q);
        $candidates = false;
        if (is_array($paradas) && count($paradas)) {
            $eessManager = new EeSsManager();
            foreach ($paradas as $parada) {
                $closerStation = $eessManager->getCloserEESS($parada['lat'], $parada['lng']);
                if($closerStation && GeoUtils::getTheDistance($parada['lat'], $parada['lng'], $closerStation['lat'], $closerStation['lng']) < EESS_RADIUS){
                    $closerStation['timestamp'] = $parada['timestamp'];
                    $candidates[] = $closerStation;
                }
            }
        }
        return $candidates;
    }

}

?>