<?php

// When called directly (not via api/index.php router), bootstrap minimal context
if (!isset($GLOBALS['con'])) {
    require_once '../config/database.php';
}

if (!isset($method)) {
    $method = $_SERVER['REQUEST_METHOD'];
}

// ESP32 direct ingest mode: POST JSON { device_id: "DM-...", sensors: [ {sensor_code, sensor_type, value, unit?} ] }
if ($method === 'POST' && !isset($resource_id)) {
    $data = json_decode(file_get_contents('php://input'), true);
    if (!isset($data['device_id']) || !isset($data['sensors']) || !is_array($data['sensors'])) {
        http_response_code(400);
        echo json_encode(['error' => 'device_id and sensors are required']);
        exit;
    }

    $device_code = $data['device_id'];
    $stmt = $GLOBALS['con']->prepare("SELECT id FROM devices WHERE device_id = ?");
    $stmt->bind_param("s", $device_code);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows === 0) {
        http_response_code(404);
        echo json_encode(['error' => 'Device not found']);
        exit;
    }
    $device_db_id = (int)$res->fetch_assoc()['id'];

    $GLOBALS['con']->begin_transaction();
    $ok = true;
    foreach ($data['sensors'] as $sensor) {
        if (!isset($sensor['sensor_code']) || !isset($sensor['sensor_type']) || !isset($sensor['value'])) {
            $ok = false;
            break;
        }
        $sensor_code = $sensor['sensor_code'];
        $sensor_type = $sensor['sensor_type'];
        $value = (float)$sensor['value'];
        $unit = $sensor['unit'] ?? null;
        $quality = $sensor['quality'] ?? 'good';
        $metadata = isset($sensor['metadata']) ? json_encode($sensor['metadata']) : null;

        $stmt = $GLOBALS['con']->prepare("INSERT INTO sensor_data (device_id, sensor_code, sensor_type, value, unit, quality, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("issdsss", $device_db_id, $sensor_code, $sensor_type, $value, $unit, $quality, $metadata);
        if (!$stmt->execute()) {
            $ok = false;
            break;
        }
    }

    if ($ok) {
        $GLOBALS['con']->commit();
        $upd = $GLOBALS['con']->prepare("UPDATE devices SET last_seen = CURRENT_TIMESTAMP WHERE id = ?");
        $upd->bind_param("i", $device_db_id);
        $upd->execute();
        echo json_encode(['success' => true]);
    } else {
        $GLOBALS['con']->rollback();
        http_response_code(500);
        echo json_encode(['error' => 'Failed to save sensor data']);
    }
    exit;
}

// Router mode (api/index.php) requires authenticate + permissions
$user_id = authenticate();

switch ($method) {
    case 'GET':
        if ($resource_id) {
            // Get sensor data for specific device
            $device_id = $resource_id;
            
            // Check permissions
            $stmt = $GLOBALS['con']->prepare("
                SELECT COUNT(*) as count FROM device_permissions dp
                JOIN devices d ON dp.device_id = d.id
                WHERE d.id = ? AND dp.user_id = ?
            ");
            $stmt->bind_param("ii", $device_id, $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->fetch_assoc()['count'] == 0) {
                http_response_code(403);
                echo json_encode(['error' => 'No permission to view this device']);
                break;
            }
            
            // Get query parameters
            $limit = $_GET['limit'] ?? 100;
            $sensor_code = $_GET['sensor_code'] ?? null;
            $start_time = $_GET['start_time'] ?? null;
            $end_time = $_GET['end_time'] ?? null;
            
            $where_conditions = ["device_id = ?"];
            $params = [$device_id];
            $types = "i";
            
            if ($sensor_code) {
                $where_conditions[] = "sensor_code = ?";
                $params[] = $sensor_code;
                $types .= "s";
            }
            
            if ($start_time) {
                $where_conditions[] = "timestamp >= ?";
                $params[] = $start_time;
                $types .= "s";
            }
            
            if ($end_time) {
                $where_conditions[] = "timestamp <= ?";
                $params[] = $end_time;
                $types .= "s";
            }
            
            $sql = "
                SELECT * FROM sensor_data 
                WHERE " . implode(" AND ", $where_conditions) . "
                ORDER BY timestamp DESC 
                LIMIT ?
            ";
            $params[] = $limit;
            $types .= "i";
            
            $stmt = $GLOBALS['con']->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $sensor_data = [];
            while ($row = $result->fetch_assoc()) {
                $sensor_data[] = $row;
            }
            
            echo json_encode($sensor_data);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Device ID is required']);
        }
        break;
        
    case 'POST':
        http_response_code(400);
        echo json_encode(['error' => 'Use direct POST format {device_id, sensors} without auth, or call router with correct payload']);
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
