<?php
// export_csv.php

// Ważne: nie pokazuj błędów w output, bo popsują CSV
ini_set('display_errors', '0'); // nie wyświetlaj błędów w odpowiedzi [web:175]
error_reporting(E_ALL);

$host = "pittdroid.pl";
$user = "pittdroid";
$password = "androidek119";
$database = "lora";
$port = 3306;

$delimiter = ';';

// Nagłówki pobierania
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="dane_sensory.csv"');

// Połączenie z bazą
$conn = new mysqli($host, $user, $password, $database, $port);
if ($conn->connect_error) {
    http_response_code(500);
    exit;
}
$conn->set_charset("utf8mb4");

// BOM dla Excela + hint separatora
echo "\xEF\xBB\xBF";
echo "sep={$delimiter}\n";

$output = fopen('php://output', 'w');

// Nagłówki CSV
fputcsv(
    $output,
    ['id', 'timestamp', 'lat', 'lng', 'gps_alt', 'sats', 'temperature', 'humidity', 'pressure', 'bme_alt'],
    separator: $delimiter,
    enclosure: '"',
    escape: "" // usuwa deprecation w PHP 8.4+ [web:169]
);

// Pobierz dane
$sql = "SELECT id, timestamp, lat, lng, gps_alt, sats, temperature, humidity, pressure, bme_alt
        FROM lora_data
        ORDER BY id DESC";
$result = $conn->query($sql);

if ($result) {
    while ($row = $result->fetch_assoc()) {
        fputcsv(
            $output,
            $row,
            separator: $delimiter,
            enclosure: '"',
            escape: "" // usuwa deprecation w PHP 8.4+ [web:169]
        );
    }
}

fclose($output);
$conn->close();
exit;
?>
