isset($_GET['serialnumber']) ? trim($_GET['serialnumber']) : null, 'type' => isset($_GET['type']) ? trim($_GET['type']) : null, 'start' => isset($_GET['start']) ? trim($_GET['start']) : date("Y-m-d", strtotime("-270 days")), 'end' => isset($_GET['end']) ? trim($_GET['end']) : date("Y-m-d", strtotime("+1 days")) ]; // ============================================ // Build Query with Prepared Statements // ============================================ $whereClauses = []; $params = []; // Serial Number Filter if ($filters['serialnumber']) { $whereClauses[] = 'h.description LIKE :serialnumber'; $params[':serialnumber'] = "%historycreated%SN%:" . $filters['serialnumber'] . "%"; $whereClauses[] = 'h.type != :excluded_type'; $params[':excluded_type'] = 'SRIncluded'; } // Type Filter if ($filters['type']) { if ($filters['type'] === 'latest') { // Get only the latest record per equipment if ($filters['serialnumber']) { $whereClauses[] = 'h.rowID IN ( SELECT MAX(h2.rowID) FROM equipment_history h2 GROUP BY h2.equipmentid )'; } else { $whereClauses[] = "h.description LIKE '%historycreated%'"; $whereClauses[] = 'h.rowID IN ( SELECT MAX(h2.rowID) FROM equipment_history h2 WHERE h2.description LIKE :history_created GROUP BY h2.equipmentid )'; $params[':history_created'] = '%historycreated%'; } } else { // Specific type filter $whereClauses[] = 'h.type = :type'; $params[':type'] = $filters['type']; } } // Default filter if no other filters applied if (empty($whereClauses)) { $whereClauses[] = "h.description LIKE '%historycreated%'"; } // Date Range Filter $whereClauses[] = 'h.created BETWEEN :start_date AND :end_date'; $params[':start_date'] = $filters['start']; $params[':end_date'] = $filters['end']; // ============================================ // Execute Query // ============================================ $whereClause = 'WHERE ' . implode(' AND ', $whereClauses); $sql = "SELECT h.rowID, h.description FROM equipment_history h $whereClause ORDER BY h.created DESC"; try { $stmt = $pdo->prepare($sql); $stmt->execute($params); $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); // ============================================ // Format Response // ============================================ $results = []; foreach ($messages as $message) { $record = json_decode($message['description'], true); // Handle JSON decode errors if (json_last_error() !== JSON_ERROR_NONE) { continue; // Skip invalid JSON } $record['historyID'] = (int)$message['rowID']; $results[] = $record; } // Set proper headers header('Content-Type: application/json; charset=utf-8'); echo json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } catch (PDOException $e) { // Log error (don't expose to client in production) error_log("Database error: " . $e->getMessage()); //header('Content-Type: application/json; charset=utf-8', true, 500); echo json_encode([ 'error' => 'An error occurred while processing your request' ]); } ?>