<?php
// ESP32 Smart Bin API
// Accepts ESP32 data using GET or POST:
//   bin_id, level / capacity / fill_percent, temperature, humidity
// Dashboard reads latest data using GET with no data or ?latest=1

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$dataFile = __DIR__ . '/latest_bin_data.json';
date_default_timezone_set('Africa/Nairobi');

function clean_float($value, $default = 0) {
    if ($value === null || $value === '') return $default;
    return round(floatval($value), 1);
}

function clean_text($value, $default = 'ECO001') {
    $value = trim((string)$value);
    if ($value === '') return $default;
    return preg_replace('/[^A-Za-z0-9_-]/', '', $value);
}

function output_latest($dataFile) {
    header('Content-Type: application/json');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

    if (file_exists($dataFile)) {
        echo file_get_contents($dataFile);
    } else {
        echo json_encode([
            'status' => 'waiting',
            'bin_id' => 'ECO001',
            'fill_percent' => 0,
            'temperature' => 0,
            'humidity' => 0,
            'last_update' => null,
            'message' => 'No ESP32 data received yet'
        ]);
    }
    exit;
}

// Use POST data if posted, otherwise use GET data.
$input = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET;

// Dashboard request: no sensor values supplied, or explicit latest=1.
$hasSensorData = isset($input['level']) || isset($input['capacity']) || isset($input['fill_percent']) || isset($input['temperature']) || isset($input['humidity']);
if (!$hasSensorData || isset($input['latest'])) {
    // If latest=1 is used together with sensor data, still save. Otherwise read latest.
    if (!$hasSensorData) {
        output_latest($dataFile);
    }
}

$fillValue = $input['fill_percent'] ?? $input['level'] ?? $input['capacity'] ?? 0;

$reading = [
    'status' => 'online',
    'bin_id' => clean_text($input['bin_id'] ?? 'ECO001'),
    'fill_percent' => max(0, min(100, clean_float($fillValue, 0))),
    'temperature' => clean_float($input['temperature'] ?? 0),
    'humidity' => max(0, min(100, clean_float($input['humidity'] ?? 0))),
    'last_update' => date('Y-m-d H:i:s')
];

$saved = file_put_contents($dataFile, json_encode($reading, JSON_PRETTY_PRINT), LOCK_EX);

if ($saved === false) {
    header('Content-Type: text/plain');
    http_response_code(500);
    echo 'ERROR: Could not save data. Check folder permission for /dustbin/api/';
    exit;
}

// ESP32-friendly response
if (isset($input['json'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'saved' => $reading]);
} else {
    header('Content-Type: text/plain');
    echo 'OK';
}
?>
