<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

include_once("server/class/User.php");

class FleetManager
{

    public static function unitIsAccessible(string $unitId, string $apiKey)
    {
        $apiRqKey = self::getUnitApiRequiredKey($unitId);
        return ($apiRqKey === $apiKey);
    }

    public static function getUnitApiRequiredkey($unitId)
    {
        try {
            $dao = new dbObject();
            $q = sprintf("SELECT api_key FROM units u "
                . "LEFT JOIN flotas f ON f.id_flota = u.id_flota "
                . "LEFT JOIN organizaciones o ON o.id_organizacion "
                . "WHERE u.unit_id = '%s' AND api_enabled=1", $unitId);
            $res = $dao->fetchQuery($q);
            if (is_array($res) && count($res) == 1) {
                return $res[0]['api_key'];
            }
        } catch (Exception $e) {
        }
        return null;
    }

    public static function getApiKeyUnitsList(string $apiKey)
    {

        $unitsList = array();

        if ($apiKey) {
            $dao = new dbObject();
            $q = sprintf("SELECT unit_id, nombre_comun, matricula,f.id_organizacion,nombre_organizacion,u.id_flota,nombre_flota FROM units u LEFT JOIN flotas f ON u.id_flota = f.id_flota LEFT JOIN organizaciones o ON o.id_organizacion = f.id_organizacion WHERE o.api_key = '%s' AND o.api_enabled = 1", $apiKey);
            $unitsList = $dao->fetchQuery($q);
        }
        return $unitsList;
    }

    public static function getUnitRestrictions(User $user, $activeOnly)
    {
        if ($user->isRoot()) {
            $condition = "true";
        } elseif ($user->isOrgAdmin()) {
            $condition = sprintf("(m.id_grupo IN (SELECT id_grupo FROM grupos WHERE id_organizacion = %d))", $user->getIdOrganizacion());
        } else {
            $condition = sprintf("m.id_grupo in (%s)", $user->getGroupsString($activeOnly));
        }
        return $condition;
    }

    public static function getUnitPositions(User $user, bool $activeOnly = true, $maxDataAge = 86400, $baseTimestamp)
    {
        $res = array();

        try {
            $unitRestrictions = self::getUnitRestrictions($user, $activeOnly);
            $query = sprintf("SELECT m.*,i.*
                                FROM machines m 
                                LEFT JOIN icons i ON i.icon_id = m.icon_id 
                                WHERE m.activa = %d AND %s 
                                ORDER BY IF((%d-m.last_message_timestamp)<%d,0,1), m.machine_name", (($activeOnly) ? 1 : 0), $unitRestrictions, time(), $maxDataAge);

            $dao = new dbObject();
            $res = $dao->fetchQuery($query);

            if (is_array($res) && count($res)) {

                foreach ($res as $index => $machine) {
                    $events = array();
                    if ($machine['alert_engine_events'] || $machine['alert_stop_events']) {
                        $eventList = FleetManager::getDynEvents($machine['machine_id'], $baseTimestamp, $dao, $machine['alert_engine_events'], $machine['alert_stop_events']);
                        if ($eventList) {
                            $a = 0;
                        }
                        $events = ($eventList) ? array_merge($events, $eventList) : $events;
                    }
                    if ($machine['alert_speed_events']) {
                        $eventList = FleetManager::getSpeedEvents($machine['machine_id'], $baseTimestamp, $dao);
                        $events = ($eventList) ? array_merge($events, $eventList) : $events;
                    }
                    if ($machine['alert_temp_events']) {
                        $eventList = FleetManager::getThEvents($machine['machine_id'], $baseTimestamp, $dao);
                        $events = ($eventList) ? array_merge($events, $eventList) : $events;
                    }
                    $res[$index]['events'] = $events;
                }
            }
        } catch (Exception $e) {
        }

        return $res;
    }

    private static function getDynEvents($machineId, $baseTimestamp, $dao, $engineEvents, $stopEvents)
    {
        if ($engineEvents && $stopEvents) {
            $cond = "";
        } else {
            if ($engineEvents) {
                $cond = "AND event_id IN ('GTIGN','GTIGF','DBG01')";
            } elseif ($stopEvents) {
                $cond = "AND event_id IN ('GTSTR','GTSTP','GTLSP','DBG02')";
            }
        }
        $q = sprintf("SELECT ignition_id as alert_id, gps_timestamp, lat, lng, location_id, poi_id, event_id, ign_on_off_duration as metadata
                      FROM log_ignition i
                      -- LEFT JOIN log_raw r ON i.log_id = r.log_id
                      WHERE machine_id = '%s' AND gps_timestamp >= %d %s;", $machineId, $baseTimestamp, $cond);

        $res = $dao->fetchQuery($q);
        return $res;
    }

    private static function getSpeedEvents($machineId, $baseTimestamp, $dao)
    {
        $q = sprintf("SELECT speeding_id as alert_id, gps_timestamp, lat, lng, location_id, poi_id, 'GTSPD' as event_id, in_range as metadata FROM log_ignition WHERE machine_id = '%s' AND gps_timestamp > %d;", $machineId, $baseTimestamp);
        $res = $dao->fetchQuery($q);
        return $res;
    }

    private static function getThEvents($machineId, $baseTimestamp, $dao)
    {
        $q = sprintf("SELECT th_id as alert_id, gps_timestamp, lat, lng, null as location_id, null as poi_id, 'GTTMP' as event_id, temp as metadata FROM log_ignition WHERE machine_id = '%s' AND gps_timestamp > %d AND is_alert=1;", $machineId, $baseTimestamp);
        $res = $dao->fetchQuery($q);
        return $res;
    }

    public static function getUnitsList(User $user, bool $activeOnly = true)
    {
        $res = null;
        try {
            $condition = $user->getGroupsString($activeOnly);
            //$query = sprintf("SELECT u.unit_id, u.nombre_comun, u.matricula FROM units u WHERE u.activo AND id_flota IN (%s) and u.activo = %d ", $condition, ($activeOnly) ? 1 : 0);
            $query = sprintf("SELECT machine_id, machine_name, matricula FROM machines m WHERE id_grupo IN (%s) and m.activa = %d ORDER BY machine_name", $condition, ($activeOnly) ? 1 : 0);
            $dao = new dbObject();
            $res = $dao->fetchQuery($query);
        } catch (Exception $e) {
        }
        return $res;
    }

    public static function getMachinesEditionList(User $user, bool $activeOnly = true)
    {

        try {
            $condition = $user->getGroupsString($activeOnly);

            /*
              $query = sprintf("SELECT u.unit_id, u.nombre_comun, u.matricula, u.costo_km, u.costo_hr, u.costo_moneda, ma.id_marca, ma.marca, mo.id_modelo, mo.modelo, u.max_allowed_speed, p.total_mileage, p.total_hours, u.km_offset, u.hour_offset, u.activo
              FROM units u
              LEFT JOIN modelos mo ON u.id_modelo = mo.id_modelo
              LEFT JOIN marcas ma ON ma.id_marca = mo.id_marca
              LEFT JOIN log_position p ON p.log_id = u.current_position
              WHERE id_flota IN (%s) %s", $condition, ($activeOnly) ? "AND u.activo=1" : "");
             */
            $query = sprintf("SELECT m.machine_id, m.machine_name, m.costo_km, m.costo_hr, m.costo_moneda, m.icon_id, 
                ma.machine_brand_id as id_marca, ma.machine_brand_name as marca, m.machine_model_id as id_modelo, mo.machine_model_name as modelo, m.id_combustible,
                m.current_mileage, m.current_hours, mileage_offset, hour_offset,m.matricula, m.max_allowed_speed, m.consumo_esperado, m.metrica, m.notification_mask, m.activa,
                ic.icon_url 
                                FROM machines m
                                LEFT JOIN ICONS ic ON ic.icon_id = m.icon_id
                                LEFT JOIN machine_models mo ON m.machine_model_id = mo.machine_model_id
                                LEFT JOIN machine_brands ma ON ma.machine_brand_id = mo.machine_brand_id
                                WHERE m.id_grupo IN (%s) %s", $condition, ($activeOnly) ? "AND m.activa=1" : "");
            $dao = new dbObject();
            $res = $dao->fetchQuery($query);
        } catch (Exception $e) {
            $res = null;
        }
        return $res;
    }
}
