<?php
$user_id = authenticate();

switch ($method) {
    case 'GET':
        if ($resource_id) {
            // Get button states for specific device
            $device_id = $resource_id;
            
            // Check permissions
            $stmt = $GLOBALS['con']->prepare("
                SELECT COUNT(*) as count FROM device_permissions 
                WHERE device_id = ? AND 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;
            }
            
            $stmt = $GLOBALS['con']->prepare("
                SELECT * FROM button_states 
                WHERE device_id = ? 
                ORDER BY button_id
            ");
            $stmt->bind_param("i", $device_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $button_states = [];
            while ($row = $result->fetch_assoc()) {
                $button_states[] = $row;
            }
            
            echo json_encode($button_states);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Device ID is required']);
        }
        break;
        
    case 'POST':
        // Update button states (for ESP32 devices)
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['device_id']) || !isset($data['button_states'])) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id and button_states are required']);
            break;
        }
        
        $device_id = $data['device_id'];
        $button_states = $data['button_states'];
        
        // Verify device 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(404);
            echo json_encode(['error' => 'Device not found']);
            break;
        }
        
        $device_db_id = $result->fetch_assoc()['id'];
        
        // Update button states
        $success = true;
        $GLOBALS['con']->begin_transaction();
        
        foreach ($button_states as $button) {
            if (!isset($button['button_id']) || !isset($button['button_type']) || !isset($button['state'])) {
                $success = false;
                break;
            }
            
            $button_id = $button['button_id'];
            $button_type = $button['button_type'];
            $state = $button['state'];
            
            // Use INSERT ... ON DUPLICATE KEY UPDATE
            $stmt = $GLOBALS['con']->prepare("
                INSERT INTO button_states (device_id, button_id, button_type, state) 
                VALUES (?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE 
                state = VALUES(state), 
                last_changed = CURRENT_TIMESTAMP
            ");
            $stmt->bind_param("isss", $device_db_id, $button_id, $button_type, $state);
            
            if (!$stmt->execute()) {
                $success = false;
                break;
            }
        }
        
        if ($success) {
            $GLOBALS['con']->commit();
            
            // Update device last_seen
            $stmt = $GLOBALS['con']->prepare("UPDATE devices SET last_seen = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->bind_param("i", $device_db_id);
            $stmt->execute();
            
            echo json_encode(['success' => true]);
        } else {
            $GLOBALS['con']->rollback();
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update button states']);
        }
        break;
        
    case 'PUT':
        if (!$resource_id) {
            http_response_code(400);
            echo json_encode(['error' => 'Device ID is required']);
            break;
        }
        
        $device_id = $resource_id;
        
        // Check permissions (only controller or owner can control buttons)
        $stmt = $GLOBALS['con']->prepare("
            SELECT permission_type FROM device_permissions 
            WHERE device_id = ? AND user_id = ? AND permission_type IN ('owner', 'controller')
        ");
        $stmt->bind_param("ii", $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 control this device']);
            break;
        }
        
        // Control specific button
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['button_id']) || !isset($data['state'])) {
            http_response_code(400);
            echo json_encode(['error' => 'button_id and state are required']);
            break;
        }
        
        $button_id = $data['button_id'];
        $state = $data['state'];
        
        if (!in_array($state, ['on', 'off'])) {
            http_response_code(400);
            echo json_encode(['error' => 'State must be "on" or "off"']);
            break;
        }
        
        // Create command for device
        $stmt = $GLOBALS['con']->prepare("
            INSERT INTO device_commands (device_id, user_id, command_type, command_data, status) 
            VALUES (?, ?, 'button_control', ?, 'pending')
        ");
        $command_data = json_encode(['button_id' => $button_id, 'state' => $state]);
        $stmt->bind_param("iiss", $device_id, $user_id, $command_data);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'command_id' => $stmt->insert_id]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to create command']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
