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

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

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

// Tüm mevcut sensör tipleri
$AVAILABLE_SENSORS = [
    'temperature' => [
        'DHT22_TEMP' => ['name' => 'DHT22 Sıcaklık', 'unit' => '°C', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'DHT11_TEMP' => ['name' => 'DHT11 Sıcaklık', 'unit' => '°C', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'DS18B20_TEMP' => ['name' => 'DS18B20 Sıcaklık', 'unit' => '°C', 'type' => 'onewire', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'BMP280_TEMP' => ['name' => 'BMP280 Sıcaklık', 'unit' => '°C', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'BME280_TEMP' => ['name' => 'BME280 Sıcaklık', 'unit' => '°C', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'THERMO_TEMP' => ['name' => 'Thermocouple', 'unit' => '°C', 'type' => 'spi', 'pin_required' => true, 'roles' => ['admin']],
        'LM35_TEMP' => ['name' => 'LM35 Sıcaklık', 'unit' => '°C', 'type' => 'analog', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'MPU6050_TEMP' => ['name' => 'MPU6050 Sıcaklık', 'unit' => '°C', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']]
    ],
    'humidity' => [
        'DHT22_HUM' => ['name' => 'DHT22 Nem', 'unit' => '%', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'DHT11_HUM' => ['name' => 'DHT11 Nem', 'unit' => '%', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'BME280_HUM' => ['name' => 'BME280 Nem', 'unit' => '%', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']]
    ],
    'pressure' => [
        'BMP280_PRESS' => ['name' => 'BMP280 Basınç', 'unit' => 'hPa', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'BME280_PRESS' => ['name' => 'BME280 Basınç', 'unit' => 'hPa', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']]
    ],
    'light' => [
        'LDR_LIGHT' => ['name' => 'LDR Işık', 'unit' => 'adc', 'type' => 'analog', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'BH1750_LIGHT' => ['name' => 'BH1750 Işık', 'unit' => 'lux', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'TSL2561_LIGHT' => ['name' => 'TSL2561 Işık', 'unit' => 'lux', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'TCS_RED' => ['name' => 'TCS34725 Kırmızı', 'unit' => 'rgb', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'TCS_GREEN' => ['name' => 'TCS34725 Yeşil', 'unit' => 'rgb', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'TCS_BLUE' => ['name' => 'TCS34725 Mavi', 'unit' => 'rgb', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']]
    ],
    'motion' => [
        'PIR_MOTION' => ['name' => 'PIR Hareket', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'MPU6050_ACCEL_X' => ['name' => 'MPU6050 X İvme', 'unit' => 'm/s²', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'MPU6050_ACCEL_Y' => ['name' => 'MPU6050 Y İvme', 'unit' => 'm/s²', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'MPU6050_ACCEL_Z' => ['name' => 'MPU6050 Z İvme', 'unit' => 'm/s²', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']]
    ],
    'distance' => [
        'ULTRASONIC_DIST' => ['name' => 'HC-SR04 Mesafe', 'unit' => 'cm', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'VL53L0X_DIST' => ['name' => 'VL53L0X Mesafe', 'unit' => 'mm', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']]
    ],
    'gas' => [
        'MQ2_GAS' => ['name' => 'MQ-2 Gaz', 'unit' => 'adc', 'type' => 'analog', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'MQ135_AIR' => ['name' => 'MQ-135 Hava Kalitesi', 'unit' => 'adc', 'type' => 'analog', 'pin_required' => true, 'roles' => ['user', 'admin']]
    ],
    'soil' => [
        'SOIL_MOISTURE' => ['name' => 'Toprak Nem', 'unit' => '%', 'type' => 'analog', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'RAIN_LEVEL' => ['name' => 'Yağmur Seviyesi', 'unit' => '%', 'type' => 'analog', 'pin_required' => true, 'roles' => ['user', 'admin']]
    ],
    'electrical' => [
        'ACS712_CURRENT' => ['name' => 'ACS712 Akım', 'unit' => 'A', 'type' => 'analog', 'pin_required' => true, 'roles' => ['admin']],
        'INA219_VOLTAGE' => ['name' => 'INA219 Voltaj', 'unit' => 'V', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['admin']],
        'INA219_CURRENT' => ['name' => 'INA219 Akım', 'unit' => 'mA', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['admin']],
        'INA219_POWER' => ['name' => 'INA219 Güç', 'unit' => 'mW', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['admin']]
    ],
    'location' => [
        'GPS_LAT' => ['name' => 'GPS Enlem', 'unit' => 'deg', 'type' => 'uart', 'pin_required' => true, 'roles' => ['admin']],
        'GPS_LON' => ['name' => 'GPS Boylam', 'unit' => 'deg', 'type' => 'uart', 'pin_required' => true, 'roles' => ['admin']],
        'GPS_ALT' => ['name' => 'GPS Yükseklik', 'unit' => 'm', 'type' => 'uart', 'pin_required' => true, 'roles' => ['admin']]
    ],
    'time' => [
        'RTC_TIME' => ['name' => 'RTC Zaman', 'unit' => 'timestamp', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'RTC_DATE' => ['name' => 'RTC Tarih', 'unit' => 'date', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'RTC_TEMP' => ['name' => 'RTC Sıcaklık', 'unit' => '°C', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'NTP_TIME' => ['name' => 'NTP Zaman', 'unit' => 'timestamp', 'type' => 'wifi', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'UPTIME' => ['name' => 'Çalışma Süresi', 'unit' => 'seconds', 'type' => 'system', 'pin_required' => false, 'roles' => ['user', 'admin']],
        'FREE_HEAP' => ['name' => 'Boş Bellek', 'unit' => 'bytes', 'type' => 'system', 'pin_required' => false, 'roles' => ['admin']],
        'CPU_TEMP' => ['name' => 'CPU Sıcaklığı', 'unit' => '°C', 'type' => 'system', 'pin_required' => false, 'roles' => ['admin']],
        'WIFI_RSSI' => ['name' => 'WiFi Sinyal', 'unit' => 'dBm', 'type' => 'system', 'pin_required' => false, 'roles' => ['user', 'admin']]
    ],
    'identification' => [
        'RFID_UID' => ['name' => 'RFID Kart', 'unit' => 'hash', 'type' => 'spi', 'pin_required' => true, 'roles' => ['admin']],
        'NFC_UID' => ['name' => 'NFC Kart', 'unit' => 'hash', 'type' => 'i2c', 'pin_required' => false, 'roles' => ['admin']]
    ],
    'buttons' => [
        'BUTTON_1' => ['name' => 'Buton 1', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin'], 'button_type' => 'momentary'],
        'BUTTON_2' => ['name' => 'Buton 2', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin'], 'button_type' => 'momentary'],
        'BUTTON_3' => ['name' => 'Buton 3', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin'], 'button_type' => 'toggle'],
        'BUTTON_4' => ['name' => 'Buton 4', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['admin'], 'button_type' => 'toggle'],
        'BUTTON_5' => ['name' => 'Buton 5', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['admin'], 'button_type' => 'momentary'],
        'BUTTON_ROLE' => ['name' => 'Role Kontrol', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['admin'], 'button_type' => 'toggle']
    ],
    'relays' => [
        'RELAY_1' => ['name' => 'Röle 1', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin'], 'relay_type' => 'spdt'],
        'RELAY_2' => ['name' => 'Röle 2', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin'], 'relay_type' => 'spdt'],
        'RELAY_3' => ['name' => 'Röle 3', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['admin'], 'relay_type' => 'spdt'],
        'RELAY_4' => ['name' => 'Röle 4', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['admin'], 'relay_type' => 'spdt']
    ],
    'displays' => [
        'TFT170x320' => ['name' => '170x320 TFT Ekran', 'unit' => 'pixels', 'type' => 'spi', 'pin_required' => true, 'roles' => ['user', 'admin'], 'resolution' => '170x320'],
        'TFT_BACKLIGHT' => ['name' => 'TFT Arka Işık', 'unit' => 'pwm', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin'], 'output_type' => 'pwm']
    ],
    'other' => [
        'PH_VALUE' => ['name' => 'PH Değeri', 'unit' => 'pH', 'type' => 'analog', 'pin_required' => true, 'roles' => ['admin']],
        'FLOW_RATE' => ['name' => 'Su Akış', 'unit' => 'L/min', 'type' => 'digital', 'pin_required' => true, 'roles' => ['admin']],
        'REED_SWITCH' => ['name' => 'Reed Switch', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['user', 'admin']],
        'BUZZER' => ['name' => 'Buzzer', 'unit' => 'bool', 'type' => 'digital', 'pin_required' => true, 'roles' => ['admin'], 'output_type' => 'pwm'],
        'LED_STRIP' => ['name' => 'LED Şerit', 'unit' => 'pwm', 'type' => 'digital', 'pin_required' => true, 'roles' => ['admin'], 'output_type' => 'pwm']
    ]
];

// ESP32 pinleri ve tipleri
$ESP32_PINS = [
    // Digital pinler
    0 => ['type' => 'digital', 'safe' => true, 'note' => 'Boot pin, pull-up ile kullan'],
    2 => ['type' => 'digital', 'safe' => true, 'note' => 'Boot pin, dahili LED'],
    4 => ['type' => 'digital', 'safe' => true, 'note' => 'Touch pin T0'],
    5 => ['type' => 'digital', 'safe' => true, 'note' => 'SS pin için ideal'],
    12 => ['type' => 'digital', 'safe' => true, 'note' => 'Boot pin, pull-down ile'],
    13 => ['type' => 'digital', 'safe' => true, 'note' => 'Touch pin T5'],
    14 => ['type' => 'digital', 'safe' => true, 'note' => 'Touch pin T6'],
    15 => ['type' => 'digital', 'safe' => true, 'note' => 'Boot pin, pull-down ile'],
    16 => ['type' => 'digital', 'safe' => true, 'note' => 'UART RX'],
    17 => ['type' => 'digital', 'safe' => true, 'note' => 'UART TX'],
    18 => ['type' => 'digital', 'safe' => true, 'note' => 'SPI SCLK'],
    19 => ['type' => 'digital', 'safe' => true, 'note' => 'SPI MISO'],
    21 => ['type' => 'digital', 'safe' => true, 'note' => 'I2C SDA'],
    22 => ['type' => 'digital', 'safe' => true, 'note' => 'I2C SCL'],
    23 => ['type' => 'digital', 'safe' => true, 'note' => 'SPI MOSI'],
    25 => ['type' => 'digital', 'safe' => true, 'note' => 'DAC1'],
    26 => ['type' => 'digital', 'safe' => true, 'note' => 'DAC2'],
    27 => ['type' => 'digital', 'safe' => true, 'note' => 'Touch pin T7'],
    
    // Analog input pinler (sadece input)
    32 => ['type' => 'analog_input', 'safe' => true, 'note' => 'ADC1_CH4, Touch pin T9'],
    33 => ['type' => 'analog_input', 'safe' => true, 'note' => 'ADC1_CH5, Touch pin T8'],
    34 => ['type' => 'analog_input', 'safe' => true, 'note' => 'ADC1_CH6'],
    35 => ['type' => 'analog_input', 'safe' => true, 'note' => 'ADC1_CH7'],
    36 => ['type' => 'analog_input', 'safe' => true, 'note' => 'ADC1_CH0'],
    39 => ['type' => 'analog_input', 'safe' => true, 'note' => 'ADC1_CH3']
];

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        $user_id = authenticate();
        
        if (!$user_id) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            break;
        }
        
        $device_id = $_GET['device_id'] ?? null;
        
        if ($device_id) {
            // Cihazın sensör atamalarını getir
            $stmt = $con->prepare("
                SELECT sa.*, s.name, s.unit, s.type as sensor_type
                FROM sensor_assignments sa
                JOIN sensors s ON sa.sensor_id = s.id
                WHERE sa.device_id = (SELECT id FROM devices WHERE device_id = ? AND user_id = ?)
                ORDER BY sa.created_at DESC
            ");
            $stmt->bind_param("si", $device_id, $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $assignments = [];
            while ($row = $result->fetch_assoc()) {
                $assignments[] = [
                    'id' => $row['id'],
                    'sensor_id' => $row['sensor_id'],
                    'sensor_code' => $row['sensor_code'],
                    'sensor_name' => $row['name'],
                    'sensor_type' => $row['sensor_type'],
                    'unit' => $row['unit'],
                    'pin' => $row['pin'],
                    'enabled' => (bool)$row['enabled'],
                    'config' => json_decode($row['config'] ?? '{}', true)
                ];
            }
            
            echo json_encode([
                'success' => true,
                'assignments' => $assignments
            ]);
        } else {
            // Tüm mevcut sensörleri ve pinleri getir
            echo json_encode([
                'success' => true,
                'available_sensors' => $AVAILABLE_SENSORS,
                'available_pins' => $ESP32_PINS
            ]);
        }
        break;
        
    case 'POST':
        $user_id = authenticate();
        
        if (!$user_id) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            break;
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['device_id']) || !isset($data['sensor_code'])) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id and sensor_code are required']);
            break;
        }
        
        $device_id = $data['device_id'];
        $sensor_code = $data['sensor_code'];
        $pin = $data['pin'] ?? null;
        $config = json_encode($data['config'] ?? []);
        
        // Cihaz yetkisi kontrolü
        $stmt = $con->prepare("
            SELECT d.id FROM devices d 
            LEFT JOIN device_permissions dp ON d.id = dp.device_id 
            WHERE d.device_id = ? AND dp.user_id = ? AND dp.permission_type IN ('owner', 'controller')
        ");
        $stmt->bind_param("si", $device_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(403);
            echo json_encode(['error' => 'No permission to configure this device']);
            break;
        }
        
        $device_db_id = $result->fetch_assoc()['id'];
        
        // Sensör kodunu doğrula
        $sensor_found = false;
        $sensor_info = null;
        foreach ($AVAILABLE_SENSORS as $category => $sensors) {
            if (isset($sensors[$sensor_code])) {
                $sensor_found = true;
                $sensor_info = $sensors[$sensor_code];
                break;
            }
        }
        
        if (!$sensor_found) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid sensor code']);
            break;
        }
        
        // Role kontrolü
        $user_role = $con->query("SELECT role FROM users WHERE id = $user_id")->fetch_assoc()['role'];
        if (!in_array($user_role, $sensor_info['roles'])) {
            http_response_code(403);
            echo json_encode(['error' => 'Insufficient role privileges for this sensor']);
            break;
        }
        
        // Pin kontrolü
        if ($sensor_info['pin_required'] && $pin === null) {
            http_response_code(400);
            echo json_encode(['error' => 'Pin is required for this sensor']);
            break;
        }
        
        if ($pin !== null && !isset($ESP32_PINS[$pin])) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid pin number']);
            break;
        }
        
        // Sensörü veritabanına ekle (sensors tablosu)
        $stmt = $con->prepare("
            INSERT IGNORE INTO sensors (sensor_code, name, unit, type) 
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("ssss", $sensor_code, $sensor_info['name'], $sensor_info['unit'], $sensor_info['type']);
        $stmt->execute();
        
        // Sensör ID'sini al
        $stmt = $con->prepare("SELECT id FROM sensors WHERE sensor_code = ?");
        $stmt->bind_param("s", $sensor_code);
        $stmt->execute();
        $sensor_db_id = $stmt->get_result()->fetch_assoc()['id'];
        
        // Atamayı yap
        $stmt = $con->prepare("
            INSERT INTO sensor_assignments (device_id, sensor_id, sensor_code, pin, config, enabled)
            VALUES (?, ?, ?, ?, ?, 1)
            ON DUPLICATE KEY UPDATE
            pin = VALUES(pin),
            config = VALUES(config),
            enabled = VALUES(enabled)
        ");
        $stmt->bind_param("iisss", $device_db_id, $sensor_db_id, $sensor_code, $pin, $config);
        
        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Sensor assigned successfully',
                'assignment_id' => $stmt->insert_id ?: $con->insert_id
            ]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to assign sensor']);
        }
        break;
        
    case 'PUT':
        $user_id = authenticate();
        
        if (!$user_id) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            break;
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['assignment_id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'assignment_id is required']);
            break;
        }
        
        $assignment_id = $data['assignment_id'];
        $enabled = $data['enabled'] ?? true;
        $config = json_encode($data['config'] ?? []);
        
        // Yetki kontrolü
        $stmt = $con->prepare("
            SELECT sa.id FROM sensor_assignments sa
            JOIN devices d ON sa.device_id = d.id
            LEFT JOIN device_permissions dp ON d.id = dp.device_id
            WHERE sa.id = ? AND dp.user_id = ? AND dp.permission_type IN ('owner', 'controller')
        ");
        $stmt->bind_param("ii", $assignment_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(403);
            echo json_encode(['error' => 'No permission to modify this assignment']);
            break;
        }
        
        // Güncelle
        $stmt = $con->prepare("
            UPDATE sensor_assignments 
            SET enabled = ?, config = ?, updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
        ");
        $stmt->bind_param("isi", $enabled, $config, $assignment_id);
        
        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Assignment updated successfully'
            ]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update assignment']);
        }
        break;
        
    case 'DELETE':
        $user_id = authenticate();
        
        if (!$user_id) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            break;
        }
        
        $assignment_id = $_GET['assignment_id'] ?? null;
        
        if (!$assignment_id) {
            http_response_code(400);
            echo json_encode(['error' => 'assignment_id is required']);
            break;
        }
        
        // Yetki kontrolü
        $stmt = $con->prepare("
            SELECT sa.id FROM sensor_assignments sa
            JOIN devices d ON sa.device_id = d.id
            LEFT JOIN device_permissions dp ON d.id = dp.device_id
            WHERE sa.id = ? AND dp.user_id = ? AND dp.permission_type IN ('owner', 'controller')
        ");
        $stmt->bind_param("ii", $assignment_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(403);
            echo json_encode(['error' => 'No permission to delete this assignment']);
            break;
        }
        
        // Sil
        $stmt = $con->prepare("DELETE FROM sensor_assignments WHERE id = ?");
        $stmt->bind_param("i", $assignment_id);
        
        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Assignment deleted successfully'
            ]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete assignment']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
