'Missing required parameters: awal, akhir, tid', 'required_format' => [ 'awal' => 'YYYY-MM-DD HH:MM:SS', 'akhir' => 'YYYY-MM-DD HH:MM:SS', 'tid' => 'tracking_id', 'license' => 'license_plate (optional)' ] ]); exit; } // Sanitize input parameters $awal = trim($_GET['awal']); $akhir = trim($_GET['akhir']); $tid = trim($_GET['tid']); $license = isset($_GET['license']) ? trim($_GET['license']) : 'Unknown'; // Debug: Log sanitized parameters // error_log("Table History API - Sanitized params: awal={$awal}, akhir={$akhir}, tid={$tid}, license={$license}"); // Validasi format datetime $awalTime = DateTime::createFromFormat('Y-m-d H:i:s', $awal); $akhirTime = DateTime::createFromFormat('Y-m-d H:i:s', $akhir); if (!$awalTime || !$akhirTime) { http_response_code(400); echo json_encode([ 'error' => 'Invalid datetime format. Use: YYYY-MM-DD HH:MM:SS', 'received' => [ 'awal' => $awal, 'akhir' => $akhir ] ]); exit; } // Validasi range waktu (maksimal 7 hari untuk performance) $diffDays = $akhirTime->diff($awalTime)->days; if ($diffDays > 7) { http_response_code(400); echo json_encode([ 'error' => 'Date range too large. Maximum 7 days allowed.', 'requested_days' => $diffDays ]); exit; } // Get GMT setting dari session (default 7 jika tidak ada) $gmt = isset($_SESSION['GMT']) ? $_SESSION['GMT'] : 7; // Debug: Log GMT setting // error_log("Table History API - GMT setting: " . $gmt); // Generate unique request ID untuk tracking $num = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); $number = $num[rand(0, 9)]; $requestId = "A" . date("d-m-Y_H:i:s") . "+" . $number; // Debug: Log request ID // error_log("Table History API - Request ID: " . $requestId); // Build SQL query untuk mendapatkan location history $sql = "SELECT lat, lon, speed, course, CONVERT(VARCHAR(19), DATEADD(HOUR, {$gmt}, receiveTime), 120) AS receiveTime, status, oilLevel FROM tblocations WHERE DATEADD(HOUR, {$gmt}, receiveTime) BETWEEN ? AND ? AND tid = ? AND fixGPS = '1' ORDER BY receiveTime ASC"; // Debug: Log SQL query // error_log("Table History API - SQL Query: " . $sql); // error_log("Table History API - Query params: " . json_encode([$awal, $akhir, $tid])); // Execute query $pdo = Database::getConnection(); $stmt = $pdo->prepare($sql); $stmt->execute([$awal, $akhir, $tid]); $data = $stmt->fetchAll(); // Debug: Log query result // error_log("Table History API - Query result count: " . count($data)); // Process data untuk menghitung jarak dan format response $newd = array(); $total = count($data); $jarak = array(); // Array untuk menyimpan jarak per segment // Debug: Log data processing start // error_log("Table History API - Processing {$total} records"); for ($i = 0; $i <= ($total - 1); $i++) { // Hitung jarak dari titik sebelumnya if ($i == 0) { // Titik pertama, jarak = 0 $jarak[$i] = 0; } else if ($data[$i]['speed'] == 0) { // Jika kecepatan 0, tidak ada pergerakan $jarak[$i] = 0; } else { // Hitung jarak dari titik sebelumnya menggunakan formula haversine $z = $i - 1; $lat1 = $data[$z]['lat']; $lon1 = $data[$z]['lon']; $lat2 = $data[$i]['lat']; $lon2 = $data[$i]['lon']; $jarak[$i] = round(SessionHelper::calculateDistance($lat1, $lon1, $lat2, $lon2), 2); } // Format oil level indicator if ($data[$i]['oilLevel'] == 0) { $oilLevel = ""; } else { $oilLevel = "_"; } // Build response data array // Format: [license, datetime, direction, engine_status, speed, cumulative_distance] $dd = array( $license, // License plate date('d/m/y H:i:s', strtotime($data[$i]['receiveTime'])), // Formatted datetime SessionHelper::fArah($data[$i]['course']), // Direction in Indonesian ($data[$i]['status'] < 260000 ? 'Mati' : 'Hidup'), // Engine status round($data[$i]['speed']) . ' KM/Jam', // Speed with unit number_format(array_sum($jarak), 2) . " KM" . $oilLevel // Cumulative distance with oil indicator ); $newd[] = $dd; // Debug: Log sample processed record // if ($i < 3) { // error_log("Table History API - Sample record {$i}: " . json_encode($dd)); // } } // Debug: Log final processing result // error_log("Table History API - Final response count: " . count($newd)); // if (count($newd) > 0) { // $totalDistance = array_sum($jarak); // error_log("Table History API - Total distance: " . number_format($totalDistance, 2) . " KM"); // } // Set response headers header('Content-Type: application/json'); // Return JSON response echo json_encode($newd); } catch (Exception $e) { // Log error untuk debugging error_log("Table History API Error: " . $e->getMessage()); error_log("Table History API Error Trace: " . $e->getTraceAsString()); http_response_code(500); echo json_encode([ 'error' => 'Failed to retrieve location history: ' . $e->getMessage() // Debug version dengan stack trace: // 'error' => 'Failed to retrieve location history: ' . $e->getMessage(), // 'trace' => $e->getTraceAsString(), // 'user' => $user, // 'parameters' => [ // 'awal' => $_GET['awal'] ?? 'not set', // 'akhir' => $_GET['akhir'] ?? 'not set', // 'tid' => $_GET['tid'] ?? 'not set', // 'license' => $_GET['license'] ?? 'not set' // ] ]); }