<?php
$user_id = authenticate();

switch ($method) {
    case 'GET':
        if ($resource_id) {
            // Get specific device
            $stmt = $GLOBALS['con']->prepare("
                SELECT d.*, u.email as owner_email 
                FROM devices d 
                JOIN users u ON d.owner_id = u.id 
                WHERE d.id = ? AND (
                    d.owner_id = ? OR 
                    d.id IN (
                        SELECT dp.device_id FROM device_permissions dp 
                        WHERE dp.user_id = ?
                    )
                )
            ");
            $stmt->bind_param("iii", $resource_id, $user_id, $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $device = $result->fetch_assoc();
                echo json_encode($device);
            } else {
                http_response_code(404);
                echo json_encode(['error' => 'Device not found']);
            }
        } else {
            // Get all user devices
            $stmt = $GLOBALS['con']->prepare("
                SELECT d.*, u.email as owner_email,
                       CASE 
                           WHEN d.owner_id = ? THEN 'owner'
                           ELSE dp.permission_type 
                       END as permission_type
                FROM devices d 
                JOIN users u ON d.owner_id = u.id 
                LEFT JOIN device_permissions dp ON d.id = dp.device_id AND dp.user_id = ?
                WHERE d.owner_id = ? OR dp.user_id = ?
                ORDER BY d.last_seen DESC
            ");
            $stmt->bind_param("iiii", $user_id, $user_id, $user_id, $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $devices = [];
            while ($row = $result->fetch_assoc()) {
                $devices[] = $row;
            }
            
            echo json_encode($devices);
        }
        break;
        
    case 'POST':
        // Register new device
        $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'];
        $device_name = $data['device_name'] ?? null;
        $device_type = $data['device_type'] ?? 'ESP32_ST7789_170x320';
        $screen_type = $data['screen_type'] ?? 'ST7789_170x320';
        $profile_config = $data['profile_config'] ?? null;
        
        // Check if device already exists
        $stmt = $GLOBALS['con']->prepare("SELECT id FROM devices WHERE device_id = ?");
        $stmt->bind_param("s", $device_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            http_response_code(409);
            echo json_encode(['error' => 'Device already registered']);
            break;
        }
        
        // Insert new device
        $stmt = $GLOBALS['con']->prepare("
            INSERT INTO devices (device_id, user_id, device_name, device_type, screen_type, profile_config) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("sissss", $device_id, $user_id, $device_name, $device_type, $screen_type, $profile_config);
        
        if ($stmt->execute()) {
            $device_id_db = $stmt->insert_id;
            
            // Add owner permission
            $stmt = $GLOBALS['con']->prepare("
                INSERT INTO device_permissions (device_id, user_id, permission_type, granted_by) 
                VALUES (?, ?, 'owner', ?)
            ");
            $stmt->bind_param("iii", $device_id_db, $user_id, $user_id);
            $stmt->execute();
            
            echo json_encode(['success' => true, 'device_id' => $device_id_db]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to register device']);
        }
        break;
        
    case 'PUT':
        if (!$resource_id) {
            http_response_code(400);
            echo json_encode(['error' => 'Device ID is required']);
            break;
        }
        
        // Check permissions
        $stmt = $GLOBALS['con']->prepare("
            SELECT permission_type FROM device_permissions 
            WHERE device_id = ? AND user_id = ?
        ");
        $stmt->bind_param("ii", $resource_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 update this device']);
            break;
        }
        
        $permission = $result->fetch_assoc()['permission_type'];
        if ($permission !== 'owner' && $permission !== 'controller') {
            http_response_code(403);
            echo json_encode(['error' => 'Insufficient permissions']);
            break;
        }
        
        // Update device
        $data = json_decode(file_get_contents('php://input'), true);
        $updates = [];
        $params = [];
        $types = "";
        
        if (isset($data['device_name'])) {
            $updates[] = "device_name = ?";
            $params[] = $data['device_name'];
            $types .= "s";
        }
        
        if (isset($data['status'])) {
            $updates[] = "status = ?";
            $params[] = $data['status'];
            $types .= "s";
        }
        
        if (isset($data['profile_config'])) {
            $updates[] = "profile_config = ?";
            $params[] = $data['profile_config'];
            $types .= "s";
        }
        
        if (empty($updates)) {
            http_response_code(400);
            echo json_encode(['error' => 'No valid fields to update']);
            break;
        }
        
        $updates[] = "last_seen = CURRENT_TIMESTAMP";
        $params[] = $resource_id;
        $types .= "i";
        
        $sql = "UPDATE devices SET " . implode(", ", $updates) . " WHERE id = ?";
        $stmt = $GLOBALS['con']->prepare($sql);
        $stmt->bind_param($types, ...$params);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update device']);
        }
        break;
        
    case 'DELETE':
        if (!$resource_id) {
            http_response_code(400);
            echo json_encode(['error' => 'Device ID is required']);
            break;
        }
        
        // Check if user is owner
        $stmt = $GLOBALS['con']->prepare("
            SELECT permission_type FROM device_permissions 
            WHERE device_id = ? AND user_id = ? AND permission_type = 'owner'
        ");
        $stmt->bind_param("ii", $resource_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(403);
            echo json_encode(['error' => 'Only owner can delete device']);
            break;
        }
        
        // Delete device (cascades will handle related records)
        $stmt = $GLOBALS['con']->prepare("DELETE FROM devices WHERE id = ?");
        $stmt->bind_param("i", $resource_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete device']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
