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

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

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

// Authentication (device or user)
function authenticateDevice() {
    $headers = getallheaders();
    $auth_header = $headers['Authorization'] ?? '';
    
    // Device authentication via device_id header
    $device_id_header = $headers['X-Device-ID'] ?? '';
    if ($device_id_header) {
        $stmt = $GLOBALS['con']->prepare("SELECT id, user_id FROM devices WHERE device_id = ?");
        $stmt->bind_param("s", $device_id_header);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            return $result->fetch_assoc();
        }
    }
    
    return null;
}

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        // Get device configuration
        $device = authenticateDevice();
        
        if (!$device) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            break;
        }
        
        $device_id = $device['id'];
        
        $stmt = $con->prepare("
            SELECT sensor_interval, heartbeat_interval, enabled_sensors, auto_commands 
            FROM device_config 
            WHERE device_id = ?
        ");
        $stmt->bind_param("i", $device_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $config = $result->fetch_assoc();
            echo json_encode([
                'success' => true,
                'config' => [
                    'sensor_interval' => (int)$config['sensor_interval'],
                    'heartbeat_interval' => (int)$config['heartbeat_interval'],
                    'enabled_sensors' => json_decode($config['enabled_sensors'] ?? '[]', true),
                    'auto_commands' => json_decode($config['auto_commands'] ?? '[]', true)
                ]
            ]);
        } else {
            // Default configuration
            echo json_encode([
                'success' => true,
                'config' => [
                    'sensor_interval' => 900000,    // 15 dakika
                    'heartbeat_interval' => 900000,  // 15 dakika
                    'enabled_sensors' => ['DHT22_TEMP', 'DHT22_HUM', 'BMP280_PRESS'],
                    'auto_commands' => []
                ]
            ]);
        }
        break;
        
    case 'POST':
    case 'PUT':
        // Update device configuration (user authentication required)
        $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'])) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id is required']);
            break;
        }
        
        $device_id = $data['device_id'];
        $sensor_interval = $data['sensor_interval'] ?? 900000;      // 15 dakika
        $heartbeat_interval = $data['heartbeat_interval'] ?? 900000;  // 15 dakika
        $enabled_sensors = json_encode($data['enabled_sensors'] ?? []);
        $auto_commands = json_encode($data['auto_commands'] ?? []);
        
        // Check permissions
        $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'];
        
        // Update or insert configuration
        $stmt = $con->prepare("
            INSERT INTO device_config (device_id, sensor_interval, heartbeat_interval, enabled_sensors, auto_commands)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
            sensor_interval = VALUES(sensor_interval),
            heartbeat_interval = VALUES(heartbeat_interval),
            enabled_sensors = VALUES(enabled_sensors),
            auto_commands = VALUES(auto_commands)
        ");
        $stmt->bind_param("iiiss", $device_db_id, $sensor_interval, $heartbeat_interval, $enabled_sensors, $auto_commands);
        
        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Configuration updated successfully'
            ]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update configuration']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
