<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
if($_SESSION['sml_si']!=session_id()) {
    die();
}
require(__DIR__.'/ssp.class.php');
require(__DIR__.'/../../config/config.inc.php');
require(__DIR__.'/../functions.php');
$id_map = (int)$_GET['id_map'];
$id_user = $_SESSION['id_user'];
$map = get_map($id_map,$id_user);
$unit_map = $map['unit_map'];
$settings = get_settings();
$user_info = get_user_info($_SESSION['id_user']);
if(!isset($_SESSION['lang'])) {
    if(!empty($user_info['language'])) {
        $language = $user_info['language'];
    } else {
        $language = $settings['language'];
    }
} else {
    $language = $_SESSION['lang'];
}
$default_language = $settings['language'];
set_language($language,$settings['language_domain']);
session_write_close();
$query = "SELECT id, MIN(tracked_at) AS start_time, MAX(updated_at) AS end_time, TIMESTAMPDIFF(SECOND, MIN(tracked_at), MAX(updated_at)) AS duration_seconds, MAX(name) AS name FROM sml_live_tracking_history WHERE id_map=$id_map GROUP BY id HAVING COUNT(*)>4";
$table = "( $query ) t";
$primaryKey = 'id';
$pdo = new PDO("mysql:host=" . DATABASE_HOST . ";dbname=" . DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$distanceMap = calculateTotalDistancesAndTime($id_map, $pdo);

$columns = array(
    array(
        'db' => 'id',
        'dt' => 'DT_RowId',
        'formatter' => function( $d, $row ) {
            return $d;
        }
    ),
    array( 'db' => 'start_time',  'dt' =>0, 'formatter' => function($d,$row) {
        global $language;
        $create_date = formatTime("dd MMM y - HH:mm",$language,strtotime($d));
        return '<span style="display:none">'.strtotime($d).'</span>'.$create_date;
    }),
    array( 'db' => 'name',  'dt' =>1 ),
    array( 'db' => 'duration_seconds',  'dt' =>2, 'formatter' => function($d,$row) {
        $hours = floor($d / 3600);
        $minutes = floor(($d % 3600) / 60);
        $seconds = $d % 60;
        return '<span style="display:none">'.$d.'</span>'.sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
    }),
    array('db' => 'id', 'dt' => 3, 'formatter' => function($id, $row) use ($distanceMap) {
        global $unit_map;
        $distance = isset($distanceMap['distances'][$id]) ? $distanceMap['distances'][$id] : 0;
        switch($unit_map) {
            case 'km':
                if ($distance < 1000) {
                    return round($distance, 0) . ' m';
                } else {
                    return round($distance / 1000, 2) . ' km';
                }
                break;
            case 'miles':
                $miles = $distance * 0.000621371;
                return ($miles < 1)
                    ? round($miles * 5280, 0) . ' ft'
                    : round($miles, 2) . ' mi';
                break;
        }
    }),
    array('db' => 'id', 'dt' => 4, 'formatter' => function($id, $row) use ($distanceMap) {
        global $unit_map;
        $distance = isset($distanceMap['distances'][$id]) ? $distanceMap['distances'][$id] : 0;
        $time = $row['duration_seconds'];
        if ($time <= 0) return '0';
        $speed_mps = $distance / $time;
        switch($unit_map) {
            case 'km':
                $kmh = $speed_mps * 3.6;
                return round($kmh, 2) . ' km/h';
                break;
            case 'miles':
                $mph = $speed_mps * 2.23694;
                return round($mph, 2) . ' mph';
                break;
        }
    }),
    array( 'db' => 'id',  'dt' =>5, 'formatter' => function($d,$row) {
        return "<button onclick='delete_live_tracking(\"$d\");' style='line-height:1;' class='btn btn-sm btn-danger btn_delete_live_tracking'><i class=\"fas fa-trash\"></i></button>";
    })
);

$sql_details = array(
    'user' => DATABASE_USERNAME,
    'pass' => DATABASE_PASSWORD,
    'db' => DATABASE_NAME,
    'host' => DATABASE_HOST);

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

function calculateTotalDistancesAndTime($id_map, $pdo) {
    $stmt = $pdo->prepare("SELECT id, lat, lon, TIMESTAMPDIFF(SECOND, MIN(tracked_at), MAX(updated_at)) AS total_time 
                           FROM sml_live_tracking_history 
                           WHERE id_map = ? 
                           GROUP BY id, lat, lon, tracked_at ORDER BY id, tracked_at;");
    $stmt->execute([$id_map]);
    $distances = [];
    $times = [];
    $prev = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $id = $row['id'];
        $lat = $row['lat'];
        $lon = $row['lon'];
        $totalTime = $row['total_time'];
        if (!isset($distances[$id])) {
            $distances[$id] = 0;
            $times[$id] = $totalTime;
            $prev[$id] = ['lat' => $lat, 'lon' => $lon];
            continue;
        }
        $prevLat = $prev[$id]['lat'];
        $prevLon = $prev[$id]['lon'];
        $distances[$id] += haversineDistance($prevLat, $prevLon, $lat, $lon);
        $prev[$id] = ['lat' => $lat, 'lon' => $lon];
    }
    return ['distances' => $distances, 'times' => $times];
}

function haversineDistance($lat1, $lon1, $lat2, $lon2) {
    $earthRadius = 6371000; // meters
    $latFrom = deg2rad($lat1);
    $lonFrom = deg2rad($lon1);
    $latTo = deg2rad($lat2);
    $lonTo = deg2rad($lon2);
    $latDelta = $latTo - $latFrom;
    $lonDelta = $lonTo - $lonFrom;
    $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
    return $earthRadius * $angle;
}
