<?php
require_once '../config/database.php';

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

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

// ESP32'den gelen veri işleme
function handleESP32Data($data) {
    global $con;
    
    try {
        // Cihazı bul veya oluştur
        $device_id = getOrCreateDevice($data);
        
        // Sensör verilerini işle
        processSensorData($device_id, $data['sensors'] ?? []);
        
        // Sistem verilerini işle
        processSystemData($device_id, $data['system'] ?? []);
        
        // Konum verilerini işle
        processLocationData($device_id, $data['location'] ?? []);
        
        // Cihaz durumunu güncelle
        updateDeviceStatus($device_id, $data);
        
        // Event oluştur
        createDeviceEvent($device_id, 'heartbeat', $data);
        
        return [
            'success' => true,
            'device_id' => $device_id,
            'processed_sensors' => count($data['sensors'] ?? []),
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// Cihazı bul veya oluştur
function getOrCreateDevice($data) {
    global $con;
    
    $device_code = $data['device_id'];
    
    // Cihazı ara
    $stmt = $con->prepare("SELECT id FROM devices WHERE device_id = ?");
    $stmt->bind_param("s", $device_code);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        return $row['id'];
    }
    
    // Yeni cihaz oluştur
    $stmt = $con->prepare("
        INSERT INTO devices (device_id, name, owner_id, esp_model, status, current_mode, config) 
        VALUES (?, ?, 1, 'ESP32', 'online', 'ONLINE', ?)
    ");
    
    $name = "ESP32 Cihazı - " . $device_code;
    $config = json_encode([
        'auto_created' => true,
        'first_seen' => date('Y-m-d H:i:s'),
        'esp_version' => $data['esp_version'] ?? 'unknown'
    ]);
    
    $stmt->bind_param("sss", $device_code, $name, $config);
    $stmt->execute();
    
    return $con->insert_id;
}

// Sensör verilerini işle
function processSensorData($device_id, $sensors) {
    global $con;
    
    foreach ($sensors as $sensor) {
        $sensor_code = $sensor['sensor_code'] ?? $sensor['code'] ?? null;
        $sensor_type = $sensor['sensor_type'] ?? $sensor['type'] ?? null;
        $value = $sensor['value'] ?? null;

        if ($sensor_code === null || $sensor_type === null || $value === null) {
            continue;
        }

        $value = (float)$value;
        $unit = $sensor['unit'] ?? null;
        $quality = $sensor['quality'] ?? 'good';
        $metadata = isset($sensor['metadata']) ? json_encode($sensor['metadata']) : json_encode([
            'pin' => $sensor['pin'] ?? null,
            'raw_value' => $sensor['raw_value'] ?? null,
            'calibrated' => $sensor['calibrated'] ?? false
        ]);

        $stmt = $con->prepare("INSERT INTO sensor_data (device_id, sensor_code, sensor_type, value, unit, quality, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("issdsss", $device_id, $sensor_code, $sensor_type, $value, $unit, $quality, $metadata);
        $stmt->execute();
    }
}

// Sistem verilerini işle
function processSystemData($device_id, $system) {
    global $con;
    
    $uptime = $system['uptime'] ?? 0;
    $free_heap = $system['free_heap'] ?? 0;
    $cpu_temp = $system['cpu_temp'] ?? null;
    $wifi_rssi = $system['wifi_rssi'] ?? null;
    
    // Sistem sensörlerini kaydet
    $system_sensors = [
        ['UPTIME', $uptime, 'seconds'],
        ['FREE_HEAP', $free_heap, 'bytes'],
        ['CPU_TEMP', $cpu_temp, '°C'],
        ['WIFI_RSSI', $wifi_rssi, 'dBm']
    ];
    
    foreach ($system_sensors as $sensor) {
        if ($sensor[1] !== null) {
            $sensor_code = $sensor[0];
            $value = $sensor[1];
            $unit = $sensor[2];
            
            $stmt = $con->prepare("
                INSERT INTO sensor_data 
                (device_id, sensor_code, sensor_type, value, unit, quality) 
                VALUES (?, ?, 'system', ?, ?, 'good')
            ");
            
            $stmt->bind_param("issds", $device_id, $sensor_code, $value, $unit);
            $stmt->execute();
        }
    }
    
    // Cihaz konfigürasyonunu güncelle
    $config = json_encode([
        'uptime' => $uptime,
        'free_heap' => $free_heap,
        'cpu_temp' => $cpu_temp,
        'wifi_rssi' => $wifi_rssi,
        'last_system_update' => date('Y-m-d H:i:s')
    ]);
    
    $stmt = $con->prepare("UPDATE devices SET config = ? WHERE id = ?");
    $stmt->bind_param("si", $config, $device_id);
    $stmt->execute();
}

// Konum verilerini işle
function processLocationData($device_id, $location) {
    if (empty($location)) return;
    
    global $con;
    
    $lat = $location['lat'] ?? null;
    $lon = $location['lon'] ?? null;
    $address = $location['address'] ?? null;
    
    if ($lat && $lon) {
        $location_data = json_encode([
            'lat' => $lat,
            'lon' => $lon,
            'address' => $address,
            'timestamp' => date('Y-m-d H:i:s')
        ]);
        
        $stmt = $con->prepare("UPDATE devices SET location = ? WHERE id = ?");
        $stmt->bind_param("si", $location_data, $device_id);
        $stmt->execute();
    }
}

// Cihaz durumunu güncelle
function updateDeviceStatus($device_id, $data) {
    global $con;
    
    $status = $data['status'] ?? 'offline';
    $mode = $data['mode'] ?? 'SETUP';
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? null;
    
    $stmt = $con->prepare("
        UPDATE devices 
        SET status = ?, current_mode = ?, last_seen = NOW(), ip_address = ? 
        WHERE id = ?
    ");
    
    $stmt->bind_param("sssi", $status, $mode, $ip_address, $device_id);
    $stmt->execute();
}

// Cihaz event'i oluştur
function createDeviceEvent($device_id, $event_type, $data) {
    global $con;
    
    $event_data = json_encode($data);
    $source = 'device';
    
    $stmt = $con->prepare("
        INSERT INTO device_events (device_id, event_type, event_data, source, status) 
        VALUES (?, ?, ?, ?, 'completed')
    ");
    
    $stmt->bind_param("isss", $device_id, $event_type, $event_data, $source);
    $stmt->execute();
}

// ESP32 konfigürasyonunu getir
function getESP32Config($device_id) {
    global $con;
    
    // Cihaz bilgilerini al
    $stmt = $con->prepare("SELECT device_id, name, esp_model, config, sensor_config FROM devices WHERE device_id = ?");
    $stmt->bind_param("s", $device_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        return ['error' => 'Device not found'];
    }

    $row = $result->fetch_assoc();
    $device = [
        'device_id' => $row['device_id'],
        'name' => $row['name'],
        'esp_model' => $row['esp_model'],
        'config' => json_decode($row['config'] ?? '{}', true),
        'sensor_config' => json_decode($row['sensor_config'] ?? '{}', true)
    ];

    $sensors = [];
    
    return [
        'device' => $device,
        'sensors' => $sensors,
        'settings' => [
            'read_interval' => 5000,
            'heartbeat_interval' => 30000,
            'retry_attempts' => 3,
            'timeout' => 10000
        ]
    ];
}

// Ana route handler
$action = $_GET['action'] ?? '';

switch ($_SERVER['REQUEST_METHOD']) {
    case 'POST':
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid JSON data']);
            break;
        }
        
        $result = handleESP32Data($input);
        echo json_encode($result);
        break;
        
    case 'GET':
        // ESP32 konfigürasyonunu getir
        if ($action === 'config') {
            $device_id = $_GET['device_id'] ?? '';
            
            if ($device_id) {
                $config = getESP32Config($device_id);
                echo json_encode($config);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'device_id required']);
            }
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
 ?>
